blob: 759dce79cf21eb5788d697aeecee61cf83a9e3c3 [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
187 private static final int SAMPLE_INTERVAL_ELAPSED_REQURST_CODE = 0;
188
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,
664 SAMPLE_INTERVAL_ELAPSED_REQURST_CODE, intent, 0);
665
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);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002302 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002303 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002304
2305 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002306 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002307 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002308 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002309 } catch (RemoteException e) {
2310 // ignored; service lives in system_server
2311 }
2312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313 }
2314
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002315 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2316 if (DBG) log("Captive portal check " + info);
2317 int type = info.getType();
2318 final NetworkStateTracker thisNet = mNetTrackers[type];
2319 if (mNetConfigs[type].isDefault()) {
2320 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2321 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2322 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002323 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002324 return;
2325 } else {
2326 if (DBG) log("Tear down low priority net " + info.getTypeName());
2327 teardown(thisNet);
2328 return;
2329 }
2330 }
2331 }
2332
Wink Saville674777e2013-08-07 16:22:47 -07002333 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002334 thisNet.captivePortalCheckComplete();
2335 }
2336
2337 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002338 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002339 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002340 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002341 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002342 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002343 }
2344
Wink Saville674777e2013-08-07 16:22:47 -07002345 /** @hide */
2346 @Override
2347 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2348 enforceConnectivityInternalPermission();
2349 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2350 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2351 }
2352
The Android Open Source Project28527d22009-03-03 19:31:44 -08002353 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002354 * Setup data activity tracking for the given network interface.
2355 *
2356 * Every {@code setupDataActivityTracking} should be paired with a
2357 * {@link removeDataActivityTracking} for cleanup.
2358 */
2359 private void setupDataActivityTracking(int type) {
2360 final NetworkStateTracker thisNet = mNetTrackers[type];
2361 final String iface = thisNet.getLinkProperties().getInterfaceName();
2362
2363 final int timeout;
2364
2365 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002366 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2367 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002368 0);
2369 // Canonicalize mobile network type
2370 type = ConnectivityManager.TYPE_MOBILE;
2371 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002372 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2373 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002374 0);
2375 } else {
2376 // do not track any other networks
2377 timeout = 0;
2378 }
2379
2380 if (timeout > 0 && iface != null) {
2381 try {
2382 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2383 } catch (RemoteException e) {
2384 }
2385 }
2386 }
2387
2388 /**
2389 * Remove data activity tracking when network disconnects.
2390 */
2391 private void removeDataActivityTracking(int type) {
2392 final NetworkStateTracker net = mNetTrackers[type];
2393 final String iface = net.getLinkProperties().getInterfaceName();
2394
2395 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2396 ConnectivityManager.TYPE_WIFI == type)) {
2397 try {
2398 // the call fails silently if no idletimer setup for this interface
2399 mNetd.removeIdleTimer(iface);
2400 } catch (RemoteException e) {
2401 }
2402 }
2403 }
2404
2405 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002406 * After a change in the connectivity state of a network. We're mainly
2407 * concerned with making sure that the list of DNS servers is set up
2408 * according to which networks are connected, and ensuring that the
2409 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002410 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002411 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002412 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker49db4222013-07-15 16:34:04 -07002413 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002414 if (VDBG) {
2415 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2416 + " resetMask=" + resetMask);
2417 }
Wink Saville051a6642011-07-13 13:44:13 -07002418
The Android Open Source Project28527d22009-03-03 19:31:44 -08002419 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002420 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002421 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002422 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002423 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002424
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002425 LinkProperties curLp = mCurrentLinkProperties[netType];
2426 LinkProperties newLp = null;
2427
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002428 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002429 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002430 if (VDBG) {
2431 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2432 " doReset=" + doReset + " resetMask=" + resetMask +
2433 "\n curLp=" + curLp +
2434 "\n newLp=" + newLp);
2435 }
2436
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002437 if (curLp != null) {
2438 if (curLp.isIdenticalInterfaceName(newLp)) {
2439 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2440 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2441 for (LinkAddress linkAddr : car.removed) {
2442 if (linkAddr.getAddress() instanceof Inet4Address) {
2443 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2444 }
2445 if (linkAddr.getAddress() instanceof Inet6Address) {
2446 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2447 }
Wink Saville051a6642011-07-13 13:44:13 -07002448 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002449 if (DBG) {
2450 log("handleConnectivityChange: addresses changed" +
2451 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2452 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002453 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002454 } else {
2455 if (DBG) {
2456 log("handleConnectivityChange: address are the same reset per doReset" +
2457 " linkProperty[" + netType + "]:" +
2458 " resetMask=" + resetMask);
2459 }
Wink Saville051a6642011-07-13 13:44:13 -07002460 }
2461 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002462 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002463 if (DBG) {
2464 log("handleConnectivityChange: interface not not equivalent reset both" +
2465 " linkProperty[" + netType + "]:" +
2466 " resetMask=" + resetMask);
2467 }
Wink Saville051a6642011-07-13 13:44:13 -07002468 }
Wink Saville051a6642011-07-13 13:44:13 -07002469 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002470 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002471 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002472 }
2473 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002474 if (VDBG) {
2475 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2476 " doReset=" + doReset + " resetMask=" + resetMask +
2477 "\n curLp=" + curLp +
2478 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002479 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002480 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002481 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker49db4222013-07-15 16:34:04 -07002482 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002483
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002484 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002485 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002486 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002487 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002488 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002489 if (TextUtils.isEmpty(iface) == false) {
2490 if (resetMask != 0) {
2491 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2492 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002493
Lorenzo Colitti63839822013-03-20 19:22:58 +09002494 // Tell VPN the interface is down. It is a temporary
2495 // but effective fix to make VPN aware of the change.
2496 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002497 synchronized(mVpns) {
2498 for (int i = 0; i < mVpns.size(); i++) {
2499 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2500 }
2501 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002502 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002503 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002504 if (resetDns) {
2505 flushVmDnsCache();
2506 if (VDBG) log("resetting DNS cache for " + iface);
2507 try {
2508 mNetd.flushInterfaceDnsCache(iface);
2509 } catch (Exception e) {
2510 // never crash - catch them all
2511 if (DBG) loge("Exception resetting dns cache: " + e);
2512 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002513 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002514 } else {
2515 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002516 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002517 }
2518 }
2519 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002520
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002521 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002522 NetworkStateTracker tracker = mNetTrackers[netType];
2523 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002524
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002525 // If the connection was previously using clat, but is not using it now, stop the clat
2526 // daemon. Normally, this happens automatically when the connection disconnects, but if
2527 // the disconnect is not reported, or if the connection's LinkProperties changed for
2528 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2529 // still be running. If it's not running, then stopping it is a no-op.
2530 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2531 mClat.stopClat();
2532 }
2533 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002534 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2535 mClat.startClat(tracker);
2536 } else {
2537 mClat.stopClat();
2538 }
2539 }
2540
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002541 // TODO: Temporary notifying upstread change to Tethering.
2542 // @see bug/4455071
2543 /** Notify TetheringService if interface name has been changed. */
2544 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002545 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002546 if (isTetheringSupported()) {
2547 mTethering.handleTetherIfaceChange();
2548 }
2549 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002550 }
2551
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002552 /**
2553 * Add and remove routes using the old properties (null if not previously connected),
2554 * new properties (null if becoming disconnected). May even be double null, which
2555 * is a noop.
2556 * Uses isLinkDefault to determine if default routes should be set or conversely if
2557 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002558 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002559 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002560 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker49db4222013-07-15 16:34:04 -07002561 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002562 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002563 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2564 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002565 if (curLp != null) {
2566 // check for the delta between the current set and the new
Lorenzo Colittie1b47422013-07-31 23:23:21 +09002567 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002568 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002569 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002570 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002571 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002572 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002573
Robert Greenwalt8d777252011-08-15 12:31:55 -07002574 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2575
Robert Greenwalt98107422011-07-22 11:55:33 -07002576 for (RouteInfo r : routeDiff.removed) {
2577 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002578 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002579 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2580 }
2581 if (isLinkDefault == false) {
2582 // remove from a secondary route table
2583 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002584 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002585 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002586
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002587 if (!isLinkDefault) {
2588 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002589 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002590 // routes changed - remove all old dns entries and add new
2591 if (curLp != null) {
2592 for (InetAddress oldDns : curLp.getDnses()) {
2593 removeRouteToAddress(curLp, oldDns);
2594 }
2595 }
2596 if (newLp != null) {
2597 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002598 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002599 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002600 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002601 } else {
2602 // no change in routes, check for change in dns themselves
2603 for (InetAddress oldDns : dnsDiff.removed) {
2604 removeRouteToAddress(curLp, oldDns);
2605 }
2606 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002607 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002608 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002609 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002610 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002611
2612 for (RouteInfo r : routeDiff.added) {
2613 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002614 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002615 } else {
2616 // add to a secondary route table
Chad Brubaker49db4222013-07-15 16:34:04 -07002617 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002618
2619 // many radios add a default route even when we don't want one.
2620 // remove the default route unless somebody else has asked for it
2621 String ifaceName = newLp.getInterfaceName();
Chad Brubaker49db4222013-07-15 16:34:04 -07002622 synchronized (mRoutesLock) {
2623 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2624 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2625 try {
2626 mNetd.removeRoute(ifaceName, r);
2627 } catch (Exception e) {
2628 // never crash - catch them all
2629 if (DBG) loge("Exception trying to remove a route: " + e);
2630 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002631 }
2632 }
2633 }
2634 }
2635
Robert Greenwalt8d777252011-08-15 12:31:55 -07002636 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002637 }
2638
2639
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002640 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002641 * Reads the network specific TCP buffer sizes from SystemProperties
2642 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2643 * wide use
2644 */
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002645 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002646 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002647 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002648
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002649 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002650 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002651
2652 // Setting to default values so we won't be stuck to previous values
2653 key = "net.tcp.buffersize.default";
2654 bufferSizes = SystemProperties.get(key);
2655 }
2656
2657 // Set values in kernel
2658 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002659 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002660 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002661 + "] which comes from [" + key + "]");
2662 }
2663 setBufferSize(bufferSizes);
2664 }
2665 }
2666
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002667 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002668 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2669 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2670 *
2671 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2672 * writeMin, writeInitial, writeMax"
2673 */
2674 private void setBufferSize(String bufferSizes) {
2675 try {
2676 String[] values = bufferSizes.split(",");
2677
2678 if (values.length == 6) {
2679 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002680 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2681 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2682 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2683 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2684 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2685 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002686 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002687 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002688 }
2689 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002690 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002691 }
2692 }
2693
Robert Greenwalt2034b912009-08-12 16:08:25 -07002694 /**
2695 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2696 * on the highest priority active net which this process requested.
2697 * If there aren't any, clear it out
2698 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002699 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002700 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002701 if (VDBG) log("reassessPidDns for pid " + pid);
2702 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002703 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002704 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002705 continue;
2706 }
2707 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002708 if (nt.getNetworkInfo().isConnected() &&
2709 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002710 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002711 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002712 if (mNetRequestersPids[i].contains(myPid)) {
2713 try {
2714 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2715 } catch (Exception e) {
2716 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002717 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002718 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002719 }
2720 }
2721 }
2722 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002723 try {
2724 mNetd.clearDnsInterfaceForPid(pid);
2725 } catch (Exception e) {
2726 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002727 }
2728 }
2729
Mattias Falkd697aa22011-08-23 14:15:13 +02002730 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002731 /*
2732 * Tell the VMs to toss their DNS caches
2733 */
2734 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2735 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002736 /*
2737 * Connectivity events can happen before boot has completed ...
2738 */
2739 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002740 final long ident = Binder.clearCallingIdentity();
2741 try {
2742 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2743 } finally {
2744 Binder.restoreCallingIdentity(ident);
2745 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002746 }
2747
Chia-chi Yehcc844502011-07-14 18:01:57 -07002748 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002749 private void updateDnsLocked(String network, String iface,
Chad Brubaker73652d02013-07-23 17:13:36 -07002750 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002751 int last = 0;
2752 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002753 dnses = new ArrayList();
2754 dnses.add(mDefaultDns);
2755 if (DBG) {
2756 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002757 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002758 }
2759
Mattias Falkd697aa22011-08-23 14:15:13 +02002760 try {
2761 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker73652d02013-07-23 17:13:36 -07002762 if (defaultDns) {
2763 mNetd.setDefaultInterfaceForDns(iface);
2764 }
2765
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002766 for (InetAddress dns : dnses) {
2767 ++last;
2768 String key = "net.dns" + last;
2769 String value = dns.getHostAddress();
2770 SystemProperties.set(key, value);
2771 }
2772 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2773 String key = "net.dns" + i;
2774 SystemProperties.set(key, "");
2775 }
2776 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002777 } catch (Exception e) {
2778 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002779 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002780 }
2781
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002782 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002783 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002784 NetworkStateTracker nt = mNetTrackers[netType];
2785 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002786 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002787 if (p == null) return;
2788 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002789 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002790 String network = nt.getNetworkInfo().getTypeName();
2791 synchronized (mDnsLock) {
Chad Brubaker5fdc1462013-07-23 17:44:41 -07002792 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002793 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002794 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002795 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002796 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002797 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002798 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002799 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002800 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002801 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002802 List<Integer> pids = mNetRequestersPids[netType];
2803 for (Integer pid : pids) {
2804 try {
2805 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2806 } catch (Exception e) {
2807 Slog.e(TAG, "exception setting interface for pid: " + e);
2808 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002809 }
2810 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002811 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002812 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002813 }
2814
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002815 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002816 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2817 NETWORK_RESTORE_DELAY_PROP_NAME);
2818 if(restoreDefaultNetworkDelayStr != null &&
2819 restoreDefaultNetworkDelayStr.length() != 0) {
2820 try {
2821 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2822 } catch (NumberFormatException e) {
2823 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002824 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002825 // if the system property isn't set, use the value for the apn type
2826 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2827
2828 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2829 (mNetConfigs[networkType] != null)) {
2830 ret = mNetConfigs[networkType].restoreTime;
2831 }
2832 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002833 }
2834
2835 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002836 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2837 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002838 if (mContext.checkCallingOrSelfPermission(
2839 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002840 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002841 pw.println("Permission Denial: can't dump ConnectivityService " +
2842 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2843 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002844 return;
2845 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002846
2847 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002848 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002849 for (int i = 0; i < mNetTrackers.length; i++) {
2850 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002851 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002852 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2853 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002854 if (nst.getNetworkInfo().isConnected()) {
2855 pw.println("Active network: " + nst.getNetworkInfo().
2856 getTypeName());
2857 }
2858 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002859 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002860 pw.println(nst);
2861 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002862 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002863 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002864 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002865
2866 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002867 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002868 for (int net : mPriorityList) {
2869 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002870 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002871 pidString = pidString + pid.toString() + ", ";
2872 }
2873 pw.println(pidString);
2874 }
2875 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002876 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002877
2878 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002879 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002880 for (Object requester : mFeatureUsers) {
2881 pw.println(requester.toString());
2882 }
2883 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002884 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002885
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002886 synchronized (this) {
2887 pw.println("NetworkTranstionWakeLock is currently " +
2888 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2889 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2890 }
2891 pw.println();
2892
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002893 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002894
2895 if (mInetLog != null) {
2896 pw.println();
2897 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002898 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002899 for(int i = 0; i < mInetLog.size(); i++) {
2900 pw.println(mInetLog.get(i));
2901 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002902 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002903 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002904 }
2905
Robert Greenwalt2034b912009-08-12 16:08:25 -07002906 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002907 private class NetworkStateTrackerHandler extends Handler {
2908 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002909 super(looper);
2910 }
2911
The Android Open Source Project28527d22009-03-03 19:31:44 -08002912 @Override
2913 public void handleMessage(Message msg) {
2914 NetworkInfo info;
2915 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002916 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002917 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002918 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002919
Wink Savillea7d56572011-09-21 11:05:43 -07002920 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Savilleb1a32022013-09-05 12:02:25 -07002921 (state == NetworkInfo.State.DISCONNECTED) ||
2922 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002923 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002924 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002925 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002926 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002927
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002928 // Since mobile has the notion of a network/apn that can be used for
2929 // provisioning we need to check every time we're connected as
2930 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2931 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2932 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2933 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2934 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002935 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2936 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleb1a32022013-09-05 12:02:25 -07002937 && ((state == NetworkInfo.State.CONNECTED)
2938 || info.isConnectedToProvisioningNetwork())) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002939 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002940 }
2941
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002942 EventLogTags.writeConnectivityStateChanged(
2943 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002944
2945 if (info.getDetailedState() ==
2946 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002947 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002948 } else if (info.getDetailedState() ==
2949 DetailedState.CAPTIVE_PORTAL_CHECK) {
2950 handleCaptivePortalTrackerCheck(info);
Wink Savilleb1a32022013-09-05 12:02:25 -07002951 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002952 /**
2953 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2954 * for now its an in between network, its a network that
2955 * is actually a default network but we don't want it to be
2956 * announced as such to keep background applications from
2957 * trying to use it. It turns out that some still try so we
2958 * take the additional step of clearing any default routes
2959 * to the link that may have incorrectly setup by the lower
2960 * levels.
2961 */
2962 LinkProperties lp = getLinkProperties(info.getType());
2963 if (DBG) {
2964 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2965 }
2966
2967 // Clear any default routes setup by the radio so
2968 // any activity by applications trying to use this
2969 // connection will fail until the provisioning network
2970 // is enabled.
2971 for (RouteInfo r : lp.getRoutes()) {
2972 removeRoute(lp, r, TO_DEFAULT_TABLE);
2973 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002974 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002975 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002976 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002977 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002978 // the logic here is, handle SUSPENDED the same as
2979 // DISCONNECTED. The only difference being we are
2980 // broadcasting an intent with NetworkInfo that's
2981 // suspended. This allows the applications an
2982 // opportunity to handle DISCONNECTED and SUSPENDED
2983 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002984 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002985 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002986 handleConnect(info);
2987 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002988 if (mLockdownTracker != null) {
2989 mLockdownTracker.onNetworkInfoChanged(info);
2990 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002991 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002992 }
2993 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002994 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002995 // TODO: Temporary allowing network configuration
2996 // change not resetting sockets.
2997 // @see bug/4455071
2998 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002999 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003000 }
3001 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003002 info = (NetworkInfo) msg.obj;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003003 int type = info.getType();
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003004 updateNetworkSettings(mNetTrackers[type]);
3005 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003006 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003007 }
3008 }
3009 }
3010
3011 private class InternalHandler extends Handler {
3012 public InternalHandler(Looper looper) {
3013 super(looper);
3014 }
3015
3016 @Override
3017 public void handleMessage(Message msg) {
3018 NetworkInfo info;
3019 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003020 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003021 String causedBy = null;
3022 synchronized (ConnectivityService.this) {
3023 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3024 mNetTransitionWakeLock.isHeld()) {
3025 mNetTransitionWakeLock.release();
3026 causedBy = mNetTransitionWakeLockCausedBy;
3027 }
3028 }
3029 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003030 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003031 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003032 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003033 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003034 FeatureUser u = (FeatureUser)msg.obj;
3035 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003036 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003037 case EVENT_INET_CONDITION_CHANGE:
3038 {
3039 int netType = msg.arg1;
3040 int condition = msg.arg2;
3041 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003042 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003043 }
3044 case EVENT_INET_CONDITION_HOLD_END:
3045 {
3046 int netType = msg.arg1;
3047 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00003048 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003049 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003050 }
3051 case EVENT_SET_NETWORK_PREFERENCE:
3052 {
3053 int preference = msg.arg1;
3054 handleSetNetworkPreference(preference);
3055 break;
3056 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003057 case EVENT_SET_MOBILE_DATA:
3058 {
3059 boolean enabled = (msg.arg1 == ENABLED);
3060 handleSetMobileData(enabled);
3061 break;
3062 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003063 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
3064 {
3065 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003066 break;
3067 }
3068 case EVENT_SET_DEPENDENCY_MET:
3069 {
3070 boolean met = (msg.arg1 == ENABLED);
3071 handleSetDependencyMet(msg.arg2, met);
3072 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003073 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07003074 case EVENT_SEND_STICKY_BROADCAST_INTENT:
3075 {
3076 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003077 sendStickyBroadcast(intent);
3078 break;
3079 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003080 case EVENT_SET_POLICY_DATA_ENABLE: {
3081 final int networkType = msg.arg1;
3082 final boolean enabled = msg.arg2 == ENABLED;
3083 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003084 break;
3085 }
3086 case EVENT_VPN_STATE_CHANGED: {
3087 if (mLockdownTracker != null) {
3088 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3089 }
3090 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003091 }
Wink Saville32506bc2013-06-29 21:10:57 -07003092 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3093 int tag = mEnableFailFastMobileDataTag.get();
3094 if (msg.arg1 == tag) {
3095 MobileDataStateTracker mobileDst =
3096 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3097 if (mobileDst != null) {
3098 mobileDst.setEnableFailFastMobileData(msg.arg2);
3099 }
3100 } else {
3101 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3102 + " != tag:" + tag);
3103 }
3104 }
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07003105 case EVENT_SAMPLE_INTERVAL_ELAPSED:
3106 handleNetworkSamplingTimeout();
3107 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003108 }
3109 }
3110 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003111
3112 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003113 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003114 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003115
3116 if (isTetheringSupported()) {
3117 return mTethering.tether(iface);
3118 } else {
3119 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3120 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003121 }
3122
3123 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003124 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003125 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003126
3127 if (isTetheringSupported()) {
3128 return mTethering.untether(iface);
3129 } else {
3130 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3131 }
3132 }
3133
3134 // javadoc from interface
3135 public int getLastTetherError(String iface) {
3136 enforceTetherAccessPermission();
3137
3138 if (isTetheringSupported()) {
3139 return mTethering.getLastTetherError(iface);
3140 } else {
3141 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3142 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003143 }
3144
3145 // TODO - proper iface API for selection by property, inspection, etc
3146 public String[] getTetherableUsbRegexs() {
3147 enforceTetherAccessPermission();
3148 if (isTetheringSupported()) {
3149 return mTethering.getTetherableUsbRegexs();
3150 } else {
3151 return new String[0];
3152 }
3153 }
3154
3155 public String[] getTetherableWifiRegexs() {
3156 enforceTetherAccessPermission();
3157 if (isTetheringSupported()) {
3158 return mTethering.getTetherableWifiRegexs();
3159 } else {
3160 return new String[0];
3161 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003162 }
3163
Danica Chang96567052010-08-11 14:54:43 -07003164 public String[] getTetherableBluetoothRegexs() {
3165 enforceTetherAccessPermission();
3166 if (isTetheringSupported()) {
3167 return mTethering.getTetherableBluetoothRegexs();
3168 } else {
3169 return new String[0];
3170 }
3171 }
3172
Mike Lockwooded4a1742011-07-19 13:04:47 -07003173 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003174 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003175 if (isTetheringSupported()) {
3176 return mTethering.setUsbTethering(enable);
3177 } else {
3178 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3179 }
3180 }
3181
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003182 // TODO - move iface listing, queries, etc to new module
3183 // javadoc from interface
3184 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003185 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003186 return mTethering.getTetherableIfaces();
3187 }
3188
3189 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003190 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003191 return mTethering.getTetheredIfaces();
3192 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003193
Jeff Sharkey300f08f2011-09-16 01:52:49 -07003194 @Override
3195 public String[] getTetheredIfacePairs() {
3196 enforceTetherAccessPermission();
3197 return mTethering.getTetheredIfacePairs();
3198 }
3199
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003200 public String[] getTetheringErroredIfaces() {
3201 enforceTetherAccessPermission();
3202 return mTethering.getErroredIfaces();
3203 }
3204
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003205 // if ro.tether.denied = true we default to no tethering
3206 // gservices could set the secure setting to 1 though to enable it on a build where it
3207 // had previously been turned off.
3208 public boolean isTetheringSupported() {
3209 enforceTetherAccessPermission();
3210 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003211 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3212 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt368095f2013-07-18 14:24:42 -07003213 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3214 mTethering.getTetherableWifiRegexs().length != 0 ||
3215 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3216 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003217 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003218
3219 // An API NetworkStateTrackers can call when they lose their network.
3220 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3221 // whichever happens first. The timer is started by the first caller and not
3222 // restarted by subsequent callers.
3223 public void requestNetworkTransitionWakelock(String forWhom) {
3224 enforceConnectivityInternalPermission();
3225 synchronized (this) {
3226 if (mNetTransitionWakeLock.isHeld()) return;
3227 mNetTransitionWakeLockSerialNumber++;
3228 mNetTransitionWakeLock.acquire();
3229 mNetTransitionWakeLockCausedBy = forWhom;
3230 }
3231 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003232 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003233 mNetTransitionWakeLockSerialNumber, 0),
3234 mNetTransitionWakeLockTimeout);
3235 return;
3236 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003237
Robert Greenwalt986c7412010-09-08 15:24:47 -07003238 // 100 percent is full good, 0 is full bad.
3239 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003240 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003241 mContext.enforceCallingOrSelfPermission(
3242 android.Manifest.permission.STATUS_BAR,
3243 "ConnectivityService");
3244
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003245 if (DBG) {
3246 int pid = getCallingPid();
3247 int uid = getCallingUid();
3248 String s = pid + "(" + uid + ") reports inet is " +
3249 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3250 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3251 mInetLog.add(s);
3252 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3253 mInetLog.remove(0);
3254 }
3255 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003256 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003257 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3258 }
3259
3260 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003261 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003262 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003263 return;
3264 }
3265 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003266 if (DBG) log("handleInetConditionChange: net=" + netType +
3267 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003268 return;
3269 }
Wink Savillea7d56572011-09-21 11:05:43 -07003270 if (VDBG) {
3271 log("handleInetConditionChange: net=" +
3272 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003273 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003274 }
Wink Saville151eaa62013-01-31 00:30:13 +00003275 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003276 int delay;
3277 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003278 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003279 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003280 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003281 delay = Settings.Global.getInt(mContext.getContentResolver(),
3282 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003283 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003284 delay = Settings.Global.getInt(mContext.getContentResolver(),
3285 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003286 }
3287 mInetConditionChangeInFlight = true;
3288 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003289 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003290 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003291 // we've set the new condition, when this hold ends that will get picked up
3292 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003293 }
3294 }
3295
Wink Saville151eaa62013-01-31 00:30:13 +00003296 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003297 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003298 log("handleInetConditionHoldEnd: net=" + netType +
3299 ", condition=" + mDefaultInetCondition +
3300 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003301 }
3302 mInetConditionChangeInFlight = false;
3303
3304 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003305 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003306 return;
3307 }
3308 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003309 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003310 return;
3311 }
Wink Saville151eaa62013-01-31 00:30:13 +00003312 // TODO: Figure out why this optimization sometimes causes a
3313 // change in mDefaultInetCondition to be missed and the
3314 // UI to not be updated.
3315 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3316 // if (DBG) log("no change in condition - aborting");
3317 // return;
3318 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003319 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3320 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003321 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003322 return;
3323 }
Wink Saville151eaa62013-01-31 00:30:13 +00003324 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003325 sendInetConditionBroadcast(networkInfo);
3326 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003327 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003328
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003329 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003330 // this information is already available as a world read/writable jvm property
3331 // so this API change wouldn't have a benifit. It also breaks the passing
3332 // of proxy info to all the JVMs.
3333 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003334 synchronized (mProxyLock) {
Jason Monka5bf2842013-07-03 17:04:33 -04003335 ProxyProperties ret = mGlobalProxy;
3336 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3337 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003338 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003339 }
3340
3341 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003342 enforceConnectivityInternalPermission();
Jason Monka5bf2842013-07-03 17:04:33 -04003343
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003344 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003345 if (proxyProperties == mGlobalProxy) return;
3346 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3347 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3348
3349 String host = "";
3350 int port = 0;
3351 String exclList = "";
Jason Monka5bf2842013-07-03 17:04:33 -04003352 String pacFileUrl = "";
3353 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3354 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003355 mGlobalProxy = new ProxyProperties(proxyProperties);
3356 host = mGlobalProxy.getHost();
3357 port = mGlobalProxy.getPort();
3358 exclList = mGlobalProxy.getExclusionList();
Jason Monka5bf2842013-07-03 17:04:33 -04003359 if (proxyProperties.getPacFileUrl() != null) {
3360 pacFileUrl = proxyProperties.getPacFileUrl();
3361 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003362 } else {
3363 mGlobalProxy = null;
3364 }
3365 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003366 final long token = Binder.clearCallingIdentity();
3367 try {
3368 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3369 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3370 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3371 exclList);
Jason Monka5bf2842013-07-03 17:04:33 -04003372 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003373 } finally {
3374 Binder.restoreCallingIdentity(token);
3375 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003376 }
3377
3378 if (mGlobalProxy == null) {
3379 proxyProperties = mDefaultProxy;
3380 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003381 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003382 }
3383
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003384 private void loadGlobalProxy() {
3385 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003386 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3387 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3388 String exclList = Settings.Global.getString(res,
3389 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monka5bf2842013-07-03 17:04:33 -04003390 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3391 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3392 ProxyProperties proxyProperties;
3393 if (!TextUtils.isEmpty(pacFileUrl)) {
3394 proxyProperties = new ProxyProperties(pacFileUrl);
3395 } else {
3396 proxyProperties = new ProxyProperties(host, port, exclList);
3397 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003398 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003399 mGlobalProxy = proxyProperties;
3400 }
3401 }
3402 }
3403
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003404 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003405 // this information is already available as a world read/writable jvm property
3406 // so this API change wouldn't have a benifit. It also breaks the passing
3407 // of proxy info to all the JVMs.
3408 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003409 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003410 return mGlobalProxy;
3411 }
3412 }
3413
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003414 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04003415 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3416 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003417 proxy = null;
3418 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003419 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003420 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003421 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003422 mDefaultProxy = proxy;
3423
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003424 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003425 if (!mDefaultProxyDisabled) {
3426 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003427 }
3428 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003429 }
3430
3431 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003432 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3433 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003434 if (!TextUtils.isEmpty(proxy)) {
3435 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003436 if (data.length == 0) {
3437 return;
3438 }
3439
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003440 String proxyHost = data[0];
3441 int proxyPort = 8080;
3442 if (data.length > 1) {
3443 try {
3444 proxyPort = Integer.parseInt(data[1]);
3445 } catch (NumberFormatException e) {
3446 return;
3447 }
3448 }
3449 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3450 setGlobalProxy(p);
3451 }
3452 }
3453
3454 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003455 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monka5bf2842013-07-03 17:04:33 -04003456 mPacManager.setCurrentProxyScriptUrl(proxy);
Robert Greenwalt78f28112011-08-02 17:18:41 -07003457 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003458 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003459 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3460 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003461 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003462 final long ident = Binder.clearCallingIdentity();
3463 try {
3464 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3465 } finally {
3466 Binder.restoreCallingIdentity(ident);
3467 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003468 }
3469
3470 private static class SettingsObserver extends ContentObserver {
3471 private int mWhat;
3472 private Handler mHandler;
3473 SettingsObserver(Handler handler, int what) {
3474 super(handler);
3475 mHandler = handler;
3476 mWhat = what;
3477 }
3478
3479 void observe(Context context) {
3480 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003481 resolver.registerContentObserver(Settings.Global.getUriFor(
3482 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003483 }
3484
3485 @Override
3486 public void onChange(boolean selfChange) {
3487 mHandler.obtainMessage(mWhat).sendToTarget();
3488 }
3489 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003490
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003491 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003492 Slog.d(TAG, s);
3493 }
3494
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003495 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003496 Slog.e(TAG, s);
3497 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003498
repo syncf5de5572011-07-29 23:55:49 -07003499 int convertFeatureToNetworkType(int networkType, String feature) {
3500 int usedNetworkType = networkType;
3501
3502 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3503 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3504 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3505 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3506 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3507 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3508 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3509 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3510 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3511 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3512 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3513 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3514 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3515 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3516 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3517 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3518 } else {
3519 Slog.e(TAG, "Can't match any mobile netTracker!");
3520 }
3521 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3522 if (TextUtils.equals(feature, "p2p")) {
3523 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3524 } else {
3525 Slog.e(TAG, "Can't match any wifi netTracker!");
3526 }
3527 } else {
3528 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003529 }
repo syncf5de5572011-07-29 23:55:49 -07003530 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003531 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003532
3533 private static <T> T checkNotNull(T value, String message) {
3534 if (value == null) {
3535 throw new NullPointerException(message);
3536 }
3537 return value;
3538 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003539
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003540 /**
3541 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003542 * VpnBuilder and not available in ConnectivityManager. Permissions
3543 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003544 * @hide
3545 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003546 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003547 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003548 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003549 try {
3550 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003551 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003552 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003553 synchronized(mVpns) {
3554 mVpns.get(user).protect(socket,
3555 mNetTrackers[type].getLinkProperties().getInterfaceName());
3556 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003557 return true;
3558 }
3559 } catch (Exception e) {
3560 // ignore
3561 } finally {
3562 try {
3563 socket.close();
3564 } catch (Exception e) {
3565 // ignore
3566 }
3567 }
3568 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003569 }
3570
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003571 /**
3572 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003573 * and not available in ConnectivityManager. Permissions are checked
3574 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003575 * @hide
3576 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003577 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003578 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003579 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003580 int user = UserHandle.getUserId(Binder.getCallingUid());
3581 synchronized(mVpns) {
3582 return mVpns.get(user).prepare(oldPackage, newPackage);
3583 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003584 }
3585
Chad Brubaker11f22252013-07-11 13:29:30 -07003586 @Override
3587 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3588 enforceMarkNetworkSocketPermission();
3589 final long token = Binder.clearCallingIdentity();
3590 try {
3591 int mark = mNetd.getMarkForUid(uid);
3592 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3593 if (mark == -1) {
3594 mark = 0;
3595 }
3596 NetworkUtils.markSocket(socket.getFd(), mark);
3597 } catch (RemoteException e) {
3598 } finally {
3599 Binder.restoreCallingIdentity(token);
3600 }
3601 }
3602
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003603 /**
3604 * Configure a TUN interface and return its file descriptor. Parameters
3605 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003606 * and not available in ConnectivityManager. Permissions are checked in
3607 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003608 * @hide
3609 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003610 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003611 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003612 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003613 int user = UserHandle.getUserId(Binder.getCallingUid());
3614 synchronized(mVpns) {
3615 return mVpns.get(user).establish(config);
3616 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003617 }
3618
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003619 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003620 * Start legacy VPN, controlling native daemons as needed. Creates a
3621 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003622 */
3623 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003624 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003625 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003626 final LinkProperties egress = getActiveLinkProperties();
3627 if (egress == null) {
3628 throw new IllegalStateException("Missing active network connection");
3629 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003630 int user = UserHandle.getUserId(Binder.getCallingUid());
3631 synchronized(mVpns) {
3632 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3633 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003634 }
3635
3636 /**
3637 * Return the information of the ongoing legacy VPN. This method is used
3638 * by VpnSettings and not available in ConnectivityManager. Permissions
3639 * are checked in Vpn class.
3640 * @hide
3641 */
3642 @Override
3643 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003644 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003645 int user = UserHandle.getUserId(Binder.getCallingUid());
3646 synchronized(mVpns) {
3647 return mVpns.get(user).getLegacyVpnInfo();
3648 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003649 }
3650
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003651 /**
Chad Brubaker94f3c8c2013-07-16 18:59:12 -07003652 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3653 * not available in ConnectivityManager.
3654 * Permissions are checked in Vpn class.
3655 * @hide
3656 */
3657 @Override
3658 public VpnConfig getVpnConfig() {
3659 int user = UserHandle.getUserId(Binder.getCallingUid());
3660 synchronized(mVpns) {
3661 return mVpns.get(user).getVpnConfig();
3662 }
3663 }
3664
3665 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003666 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3667 * through NetworkStateTracker since it works differently. For example, it
3668 * needs to override DNS servers but never takes the default routes. It
3669 * relies on another data network, and it could keep existing connections
3670 * alive after reconnecting, switching between networks, or even resuming
3671 * from deep sleep. Calls from applications should be done synchronously
3672 * to avoid race conditions. As these are all hidden APIs, refactoring can
3673 * be done whenever a better abstraction is developed.
3674 */
3675 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003676 private VpnCallback() {
3677 }
3678
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003679 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003680 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003681 }
3682
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003683 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003684 if (dnsServers == null) {
3685 restore();
3686 return;
3687 }
3688
3689 // Convert DNS servers into addresses.
3690 List<InetAddress> addresses = new ArrayList<InetAddress>();
3691 for (String address : dnsServers) {
3692 // Double check the addresses and remove invalid ones.
3693 try {
3694 addresses.add(InetAddress.parseNumericAddress(address));
3695 } catch (Exception e) {
3696 // ignore
3697 }
3698 }
3699 if (addresses.isEmpty()) {
3700 restore();
3701 return;
3702 }
3703
3704 // Concatenate search domains into a string.
3705 StringBuilder buffer = new StringBuilder();
3706 if (searchDomains != null) {
3707 for (String domain : searchDomains) {
3708 buffer.append(domain).append(' ');
3709 }
3710 }
3711 String domains = buffer.toString().trim();
3712
3713 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003714 synchronized (mDnsLock) {
Chad Brubaker73652d02013-07-23 17:13:36 -07003715 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003716 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003717
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003718 // Temporarily disable the default proxy (not global).
3719 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003720 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003721 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003722 sendProxyBroadcast(null);
3723 }
3724 }
3725
3726 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003727 }
3728
Chia-chi Yehcc844502011-07-14 18:01:57 -07003729 public void restore() {
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003730 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003731 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003732 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003733 sendProxyBroadcast(mDefaultProxy);
3734 }
3735 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003736 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003737
3738 public void protect(ParcelFileDescriptor socket) {
3739 try {
3740 final int mark = mNetd.getMarkForProtect();
3741 NetworkUtils.markSocket(socket.getFd(), mark);
3742 } catch (RemoteException e) {
3743 }
3744 }
3745
3746 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3747 for (RouteInfo route : routes) {
3748 try {
3749 mNetd.setMarkedForwardingRoute(interfaze, route);
3750 } catch (RemoteException e) {
3751 }
3752 }
3753 }
3754
3755 public void setMarkedForwarding(String interfaze) {
3756 try {
3757 mNetd.setMarkedForwarding(interfaze);
3758 } catch (RemoteException e) {
3759 }
3760 }
3761
3762 public void clearMarkedForwarding(String interfaze) {
3763 try {
3764 mNetd.clearMarkedForwarding(interfaze);
3765 } catch (RemoteException e) {
3766 }
3767 }
3768
3769 public void addUserForwarding(String interfaze, int uid) {
3770 int uidStart = uid * UserHandle.PER_USER_RANGE;
3771 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3772 addUidForwarding(interfaze, uidStart, uidEnd);
3773 }
3774
3775 public void clearUserForwarding(String interfaze, int uid) {
3776 int uidStart = uid * UserHandle.PER_USER_RANGE;
3777 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3778 clearUidForwarding(interfaze, uidStart, uidEnd);
3779 }
3780
3781 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3782 try {
3783 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3784 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3785 } catch (RemoteException e) {
3786 }
3787
3788 }
3789
3790 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3791 try {
3792 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3793 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3794 } catch (RemoteException e) {
3795 }
3796
3797 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003798 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003799
3800 @Override
3801 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003802 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3803 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3804 return false;
3805 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003806
3807 // Tear down existing lockdown if profile was removed
3808 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3809 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003810 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003811 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3812 return false;
3813 }
3814
3815 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3816 final VpnProfile profile = VpnProfile.decode(
3817 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003818 int user = UserHandle.getUserId(Binder.getCallingUid());
3819 synchronized(mVpns) {
3820 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3821 profile));
3822 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003823 } else {
3824 setLockdownTracker(null);
3825 }
3826
3827 return true;
3828 }
3829
3830 /**
3831 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3832 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3833 */
3834 private void setLockdownTracker(LockdownVpnTracker tracker) {
3835 // Shutdown any existing tracker
3836 final LockdownVpnTracker existing = mLockdownTracker;
3837 mLockdownTracker = null;
3838 if (existing != null) {
3839 existing.shutdown();
3840 }
3841
3842 try {
3843 if (tracker != null) {
3844 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003845 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003846 mLockdownTracker = tracker;
3847 mLockdownTracker.init();
3848 } else {
3849 mNetd.setFirewallEnabled(false);
3850 }
3851 } catch (RemoteException e) {
3852 // ignored; NMS lives inside system_server
3853 }
3854 }
3855
3856 private void throwIfLockdownEnabled() {
3857 if (mLockdownEnabled) {
3858 throw new IllegalStateException("Unavailable in lockdown mode");
3859 }
3860 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003861
3862 public void supplyMessenger(int networkType, Messenger messenger) {
3863 enforceConnectivityInternalPermission();
3864
3865 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3866 mNetTrackers[networkType].supplyMessenger(messenger);
3867 }
3868 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003869
3870 public int findConnectionTypeForIface(String iface) {
3871 enforceConnectivityInternalPermission();
3872
3873 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3874 for (NetworkStateTracker tracker : mNetTrackers) {
3875 if (tracker != null) {
3876 LinkProperties lp = tracker.getLinkProperties();
3877 if (lp != null && iface.equals(lp.getInterfaceName())) {
3878 return tracker.getNetworkInfo().getType();
3879 }
3880 }
3881 }
3882 return ConnectivityManager.TYPE_NONE;
3883 }
Wink Saville32506bc2013-06-29 21:10:57 -07003884
3885 /**
3886 * Have mobile data fail fast if enabled.
3887 *
3888 * @param enabled DctConstants.ENABLED/DISABLED
3889 */
3890 private void setEnableFailFastMobileData(int enabled) {
3891 int tag;
3892
3893 if (enabled == DctConstants.ENABLED) {
3894 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3895 } else {
3896 tag = mEnableFailFastMobileDataTag.get();
3897 }
3898 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3899 enabled));
3900 }
3901
Wink Savilled23fa092013-08-16 17:17:28 -07003902 private boolean isMobileDataStateTrackerReady() {
3903 MobileDataStateTracker mdst =
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003904 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilled23fa092013-08-16 17:17:28 -07003905 return (mdst != null) && (mdst.isReady());
3906 }
3907
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003908 /**
3909 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3910 */
3911
3912 /**
3913 * No connection was possible to the network.
Wink Saville9685cd12013-09-06 09:53:08 -07003914 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003915 */
Wink Saville9685cd12013-09-06 09:53:08 -07003916 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003917
3918 /**
3919 * A connection was made to the internet, all is well.
Wink Saville9685cd12013-09-06 09:53:08 -07003920 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003921 */
Wink Saville9685cd12013-09-06 09:53:08 -07003922 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003923
3924 /**
3925 * A connection was made but no dns server was available to resolve a name to address.
Wink Saville9685cd12013-09-06 09:53:08 -07003926 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003927 */
Wink Saville9685cd12013-09-06 09:53:08 -07003928 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003929
3930 /**
3931 * A connection was made but could not open a TCP connection.
Wink Saville9685cd12013-09-06 09:53:08 -07003932 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003933 */
Wink Saville9685cd12013-09-06 09:53:08 -07003934 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3935
3936 /**
3937 * A connection was made but there was a redirection, we appear to be in walled garden.
3938 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3939 */
3940 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003941
3942 /**
3943 * The mobile network is a provisioning network.
Wink Saville9685cd12013-09-06 09:53:08 -07003944 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003945 */
Wink Saville9685cd12013-09-06 09:53:08 -07003946 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003947
Wink Saville9685cd12013-09-06 09:53:08 -07003948 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003949
Wink Saville32506bc2013-06-29 21:10:57 -07003950 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003951 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3952 int timeOutMs = -1;
3953 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3954 enforceConnectivityInternalPermission();
Wink Savilled469c472013-07-02 10:55:14 -07003955
Wink Saville32506bc2013-06-29 21:10:57 -07003956 final long token = Binder.clearCallingIdentity();
3957 try {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003958 timeOutMs = suggestedTimeOutMs;
3959 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3960 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3961 }
3962
3963 // Check that mobile networks are supported
3964 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3965 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3966 if (DBG) log("checkMobileProvisioning: X no mobile network");
3967 return timeOutMs;
3968 }
3969
3970 // If we're already checking don't do it again
3971 // TODO: Add a queue of results...
3972 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3973 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3974 return timeOutMs;
3975 }
3976
3977 // Start off with notification off
3978 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
3979
3980 // See if we've alreadying determined if we've got a provsioning connection
3981 // if so we don't need to do anything active
3982 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
3983 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3984 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
3985
3986 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
3987 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3988 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
3989
3990 if (isDefaultProvisioning || isHipriProvisioning) {
3991 if (mIsNotificationVisible) {
3992 if (DBG) {
3993 log("checkMobileProvisioning: provisioning-ignore notification is visible");
3994 }
3995 } else {
3996 NetworkInfo ni = null;
3997 if (isDefaultProvisioning) {
3998 ni = mdstDefault.getNetworkInfo();
3999 }
4000 if (isHipriProvisioning) {
4001 ni = mdstHipri.getNetworkInfo();
4002 }
4003 String url = getMobileProvisioningUrl();
4004 if ((ni != null) && (!TextUtils.isEmpty(url))) {
4005 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(), url);
4006 } else {
4007 if (DBG) log("checkMobileProvisioning: provisioning but no url, ignore");
4008 }
4009 }
4010 mIsCheckingMobileProvisioning.set(false);
4011 return timeOutMs;
4012 }
4013
Wink Saville32506bc2013-06-29 21:10:57 -07004014 CheckMp checkMp = new CheckMp(mContext, this);
4015 CheckMp.CallBack cb = new CheckMp.CallBack() {
4016 @Override
4017 void onComplete(Integer result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004018 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004019 NetworkInfo ni =
4020 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4021 switch(result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004022 case CMP_RESULT_CODE_CONNECTABLE:
Wink Saville9685cd12013-09-06 09:53:08 -07004023 case CMP_RESULT_CODE_NO_CONNECTION:
4024 case CMP_RESULT_CODE_NO_DNS:
4025 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004026 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville32506bc2013-06-29 21:10:57 -07004027 break;
4028 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004029 case CMP_RESULT_CODE_REDIRECTED: {
4030 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt39d56012013-07-16 12:06:09 -07004031 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004032 if (TextUtils.isEmpty(url)) {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004033 url = getMobileRedirectedProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004034 }
4035 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004036 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4037 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4038 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004039 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004040 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004041 }
4042 break;
4043 }
Wink Saville9685cd12013-09-06 09:53:08 -07004044 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004045 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004046 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004047 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4048 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4049 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004050 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004051 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004052 }
4053 break;
4054 }
4055 default: {
4056 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4057 break;
4058 }
4059 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004060 mIsCheckingMobileProvisioning.set(false);
Wink Saville32506bc2013-06-29 21:10:57 -07004061 }
4062 };
4063 CheckMp.Params params =
4064 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004065 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville32506bc2013-06-29 21:10:57 -07004066 checkMp.execute(params);
4067 } finally {
4068 Binder.restoreCallingIdentity(token);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004069 if (DBG) log("checkMobileProvisioning: X");
Wink Saville32506bc2013-06-29 21:10:57 -07004070 }
4071 return timeOutMs;
4072 }
4073
4074 static class CheckMp extends
4075 AsyncTask<CheckMp.Params, Void, Integer> {
4076 private static final String CHECKMP_TAG = "CheckMp";
4077 public static final int MAX_TIMEOUT_MS = 60000;
4078 private static final int SOCKET_TIMEOUT_MS = 5000;
4079 private Context mContext;
4080 private ConnectivityService mCs;
4081 private TelephonyManager mTm;
4082 private Params mParams;
4083
4084 /**
4085 * Parameters for AsyncTask.execute
4086 */
4087 static class Params {
4088 private String mUrl;
4089 private long mTimeOutMs;
4090 private CallBack mCb;
4091
4092 Params(String url, long timeOutMs, CallBack cb) {
4093 mUrl = url;
4094 mTimeOutMs = timeOutMs;
4095 mCb = cb;
4096 }
4097
4098 @Override
4099 public String toString() {
4100 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4101 }
4102 }
4103
4104 /**
4105 * The call back object passed in Params. onComplete will be called
4106 * on the main thread.
4107 */
4108 abstract static class CallBack {
4109 // Called on the main thread.
4110 abstract void onComplete(Integer result);
4111 }
4112
4113 public CheckMp(Context context, ConnectivityService cs) {
4114 mContext = context;
4115 mCs = cs;
4116
4117 // Setup access to TelephonyService we'll be using.
4118 mTm = (TelephonyManager) mContext.getSystemService(
4119 Context.TELEPHONY_SERVICE);
4120 }
4121
4122 /**
4123 * Get the default url to use for the test.
4124 */
4125 public String getDefaultUrl() {
4126 // See http://go/clientsdns for usage approval
4127 String server = Settings.Global.getString(mContext.getContentResolver(),
4128 Settings.Global.CAPTIVE_PORTAL_SERVER);
4129 if (server == null) {
4130 server = "clients3.google.com";
4131 }
4132 return "http://" + server + "/generate_204";
4133 }
4134
4135 /**
4136 * Detect if its possible to connect to the http url. DNS based detection techniques
4137 * do not work at all hotspots. The best way to check is to perform a request to
4138 * a known address that fetches the data we expect.
4139 */
4140 private synchronized Integer isMobileOk(Params params) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004141 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004142 Uri orgUri = Uri.parse(params.mUrl);
4143 Random rand = new Random();
4144 mParams = params;
4145
Wink Saville69e2de02013-08-13 12:41:06 -07004146 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4147 log("isMobileOk: not mobile capable");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004148 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville69e2de02013-08-13 12:41:06 -07004149 return result;
4150 }
Wink Saville32506bc2013-06-29 21:10:57 -07004151
Wink Saville69e2de02013-08-13 12:41:06 -07004152 try {
Wink Saville32506bc2013-06-29 21:10:57 -07004153 // Continue trying to connect until time has run out
4154 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville15f12922013-08-07 11:02:57 -07004155
Wink Savilled23fa092013-08-16 17:17:28 -07004156 if (!mCs.isMobileDataStateTrackerReady()) {
4157 // Wait for MobileDataStateTracker to be ready.
4158 if (DBG) log("isMobileOk: mdst is not ready");
4159 while(SystemClock.elapsedRealtime() < endTime) {
4160 if (mCs.isMobileDataStateTrackerReady()) {
4161 // Enable fail fast as we'll do retries here and use a
4162 // hipri connection so the default connection stays active.
4163 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4164 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4165 break;
4166 }
4167 sleep(1);
4168 }
4169 }
4170
4171 log("isMobileOk: start hipri url=" + params.mUrl);
4172
Wink Saville15f12922013-08-07 11:02:57 -07004173 // First wait until we can start using hipri
4174 Binder binder = new Binder();
4175 while(SystemClock.elapsedRealtime() < endTime) {
4176 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4177 Phone.FEATURE_ENABLE_HIPRI, binder);
4178 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4179 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4180 log("isMobileOk: hipri started");
4181 break;
4182 }
4183 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004184 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville15f12922013-08-07 11:02:57 -07004185 sleep(1);
4186 }
4187
4188 // Continue trying to connect until time has run out
Wink Saville32506bc2013-06-29 21:10:57 -07004189 while(SystemClock.elapsedRealtime() < endTime) {
4190 try {
4191 // Wait for hipri to connect.
4192 // TODO: Don't poll and handle situation where hipri fails
4193 // because default is retrying. See b/9569540
4194 NetworkInfo.State state = mCs
4195 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4196 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004197 if (true/*VDBG*/) {
Wink Savilled28eef42013-07-31 15:49:04 -07004198 log("isMobileOk: not connected ni=" +
Wink Saville32506bc2013-06-29 21:10:57 -07004199 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Savilled28eef42013-07-31 15:49:04 -07004200 }
Wink Saville32506bc2013-06-29 21:10:57 -07004201 sleep(1);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004202 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004203 continue;
4204 }
4205
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004206 // Hipri has started check if this is a provisioning url
4207 MobileDataStateTracker mdst = (MobileDataStateTracker)
4208 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4209 if (mdst.isProvisioningNetwork()) {
Wink Saville9685cd12013-09-06 09:53:08 -07004210 if (DBG) log("isMobileOk: isProvisioningNetwork is true");
4211 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004212 return result;
4213 } else {
4214 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4215 }
4216
Wink Saville32506bc2013-06-29 21:10:57 -07004217 // Get of the addresses associated with the url host. We need to use the
4218 // address otherwise HttpURLConnection object will use the name to get
4219 // the addresses and is will try every address but that will bypass the
4220 // route to host we setup and the connection could succeed as the default
4221 // interface might be connected to the internet via wifi or other interface.
4222 InetAddress[] addresses;
4223 try {
4224 addresses = InetAddress.getAllByName(orgUri.getHost());
4225 } catch (UnknownHostException e) {
4226 log("isMobileOk: UnknownHostException");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004227 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville32506bc2013-06-29 21:10:57 -07004228 return result;
4229 }
4230 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4231
4232 // Get the type of addresses supported by this link
4233 LinkProperties lp = mCs.getLinkProperties(
4234 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti09de4182013-08-08 11:00:12 +09004235 boolean linkHasIpv4 = lp.hasIPv4Address();
4236 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville32506bc2013-06-29 21:10:57 -07004237 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4238 + " linkHasIpv6=" + linkHasIpv6);
4239
4240 // Loop through at most 3 valid addresses or all of the address or until
4241 // we run out of time
4242 int loops = Math.min(3, addresses.length);
4243 for(int validAddr=0, addrTried=0;
4244 (validAddr < loops) && (addrTried < addresses.length)
4245 && (SystemClock.elapsedRealtime() < endTime);
4246 addrTried ++) {
4247
4248 // Choose the address at random but make sure its type is supported
4249 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4250 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4251 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4252 // Valid address, so use it
4253 validAddr += 1;
4254 } else {
4255 // Invalid address so try next address
4256 continue;
4257 }
4258
4259 // Make a route to host so we check the specific interface.
4260 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4261 hostAddr.getAddress())) {
4262 // Wait a short time to be sure the route is established ??
4263 log("isMobileOk:"
4264 + " wait to establish route to hostAddr=" + hostAddr);
4265 sleep(3);
4266 } else {
4267 log("isMobileOk:"
4268 + " could not establish route to hostAddr=" + hostAddr);
4269 continue;
4270 }
4271
4272 // Rewrite the url to have numeric address to use the specific route.
4273 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4274 // is used which is useless in this case.
4275 URL newUrl = new URL(orgUri.getScheme() + "://"
4276 + hostAddr.getHostAddress() + orgUri.getPath());
4277 log("isMobileOk: newUrl=" + newUrl);
4278
4279 HttpURLConnection urlConn = null;
4280 try {
4281 // Open the connection set the request header and get the response
4282 urlConn = (HttpURLConnection) newUrl.openConnection(
4283 java.net.Proxy.NO_PROXY);
4284 urlConn.setInstanceFollowRedirects(false);
4285 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4286 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4287 urlConn.setUseCaches(false);
4288 urlConn.setAllowUserInteraction(false);
4289 urlConn.setRequestProperty("Connection", "close");
4290 int responseCode = urlConn.getResponseCode();
Wink Saville9685cd12013-09-06 09:53:08 -07004291
4292 // For debug display the headers
4293 Map<String, List<String>> headers = urlConn.getHeaderFields();
4294 log("isMobileOk: headers=" + headers);
4295
4296 // Close the connection
Wink Saville32506bc2013-06-29 21:10:57 -07004297 urlConn.disconnect();
4298 urlConn = null;
Wink Saville9685cd12013-09-06 09:53:08 -07004299
4300 if (responseCode == 204) {
4301 // Return
4302 log("isMobileOk: expected responseCode=" + responseCode);
4303 result = CMP_RESULT_CODE_CONNECTABLE;
4304 return result;
4305 } else {
4306 // Retry to be sure this was redirected, we've gotten
4307 // occasions where a server returned 200 even though
4308 // the device didn't have a "warm" sim.
4309 log("isMobileOk: not expected responseCode=" + responseCode);
4310 result = CMP_RESULT_CODE_REDIRECTED;
4311 }
Wink Saville32506bc2013-06-29 21:10:57 -07004312 } catch (Exception e) {
4313 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Saville9685cd12013-09-06 09:53:08 -07004314 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004315 if (urlConn != null) {
4316 urlConn.disconnect();
4317 urlConn = null;
4318 }
4319 }
4320 }
Wink Saville9685cd12013-09-06 09:53:08 -07004321 log("isMobileOk: loops|timed out result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004322 return result;
4323 } catch (Exception e) {
4324 log("isMobileOk: Exception e=" + e);
4325 continue;
4326 }
4327 }
4328 log("isMobileOk: timed out");
4329 } finally {
4330 log("isMobileOk: F stop hipri");
4331 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4332 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4333 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004334
4335 // Wait for hipri to disconnect.
4336 long endTime = SystemClock.elapsedRealtime() + 5000;
4337
4338 while(SystemClock.elapsedRealtime() < endTime) {
4339 NetworkInfo.State state = mCs
4340 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4341 if (state != NetworkInfo.State.DISCONNECTED) {
4342 if (VDBG) {
4343 log("isMobileOk: connected ni=" +
4344 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4345 }
4346 sleep(1);
4347 continue;
4348 }
4349 }
4350
Wink Saville32506bc2013-06-29 21:10:57 -07004351 log("isMobileOk: X result=" + result);
4352 }
4353 return result;
4354 }
4355
4356 @Override
4357 protected Integer doInBackground(Params... params) {
4358 return isMobileOk(params[0]);
4359 }
4360
4361 @Override
4362 protected void onPostExecute(Integer result) {
4363 log("onPostExecute: result=" + result);
4364 if ((mParams != null) && (mParams.mCb != null)) {
4365 mParams.mCb.onComplete(result);
4366 }
4367 }
4368
4369 private String inetAddressesToString(InetAddress[] addresses) {
4370 StringBuffer sb = new StringBuffer();
4371 boolean firstTime = true;
4372 for(InetAddress addr : addresses) {
4373 if (firstTime) {
4374 firstTime = false;
4375 } else {
4376 sb.append(",");
4377 }
4378 sb.append(addr);
4379 }
4380 return sb.toString();
4381 }
4382
4383 private void printNetworkInfo() {
4384 boolean hasIccCard = mTm.hasIccCard();
4385 int simState = mTm.getSimState();
4386 log("hasIccCard=" + hasIccCard
4387 + " simState=" + simState);
4388 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4389 if (ni != null) {
4390 log("ni.length=" + ni.length);
4391 for (NetworkInfo netInfo: ni) {
4392 log("netInfo=" + netInfo.toString());
4393 }
4394 } else {
4395 log("no network info ni=null");
4396 }
4397 }
4398
4399 /**
4400 * Sleep for a few seconds then return.
4401 * @param seconds
4402 */
4403 private static void sleep(int seconds) {
4404 try {
4405 Thread.sleep(seconds * 1000);
4406 } catch (InterruptedException e) {
4407 e.printStackTrace();
4408 }
4409 }
4410
Wink Saville32506bc2013-06-29 21:10:57 -07004411 private void log(String s) {
4412 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4413 }
4414 }
4415
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004416 // TODO: Move to ConnectivityManager and make public?
4417 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4418 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville32506bc2013-06-29 21:10:57 -07004419
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004420 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4421 @Override
4422 public void onReceive(Context context, Intent intent) {
4423 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4424 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4425 }
4426 }
4427 };
4428
4429 private void handleMobileProvisioningAction(String url) {
4430 // Notication mark notification as not visible
4431 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
4432
4433 // If provisioning network handle as a special case,
4434 // otherwise launch browser with the intent directly.
4435 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Savilleb1a32022013-09-05 12:02:25 -07004436 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004437 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4438 MobileDataStateTracker mdst = (MobileDataStateTracker)
4439 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4440 mdst.enableMobileProvisioning(url);
4441 } else {
4442 if (DBG) log("handleMobileProvisioningAction: on default network");
4443 Intent newIntent =
4444 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4445 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4446 Intent.FLAG_ACTIVITY_NEW_TASK);
4447 try {
4448 mContext.startActivity(newIntent);
4449 } catch (ActivityNotFoundException e) {
4450 loge("handleMobileProvisioningAction: startActivity failed" + e);
4451 }
4452 }
4453 }
4454
4455 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4456 private volatile boolean mIsNotificationVisible = false;
4457
4458 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4459 String url) {
4460 if (DBG) {
4461 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4462 + " extraInfo=" + extraInfo + " url=" + url);
4463 }
Wink Saville32506bc2013-06-29 21:10:57 -07004464
4465 Resources r = Resources.getSystem();
4466 NotificationManager notificationManager = (NotificationManager) mContext
4467 .getSystemService(Context.NOTIFICATION_SERVICE);
4468
4469 if (visible) {
4470 CharSequence title;
4471 CharSequence details;
4472 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004473 Intent intent;
4474 Notification notification = new Notification();
4475 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004476 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004477 title = r.getString(R.string.wifi_available_sign_in, 0);
4478 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004479 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004480 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004481 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4482 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4483 Intent.FLAG_ACTIVITY_NEW_TASK);
4484 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004485 break;
4486 case ConnectivityManager.TYPE_MOBILE:
4487 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004488 title = r.getString(R.string.network_available_sign_in, 0);
4489 // TODO: Change this to pull from NetworkInfo once a printable
4490 // name has been added to it
4491 details = mTelephonyManager.getNetworkOperatorName();
4492 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004493 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4494 intent.putExtra("EXTRA_URL", url);
4495 intent.setFlags(0);
4496 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004497 break;
4498 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004499 title = r.getString(R.string.network_available_sign_in, 0);
4500 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004501 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004502 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004503 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4504 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4505 Intent.FLAG_ACTIVITY_NEW_TASK);
4506 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004507 break;
4508 }
4509
Wink Saville32506bc2013-06-29 21:10:57 -07004510 notification.when = 0;
4511 notification.icon = icon;
4512 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004513 notification.tickerText = title;
4514 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4515
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004516 try {
4517 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4518 } catch (NullPointerException npe) {
4519 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4520 npe.printStackTrace();
4521 }
Wink Saville32506bc2013-06-29 21:10:57 -07004522 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004523 try {
4524 notificationManager.cancel(NOTIFICATION_ID, 1);
4525 } catch (NullPointerException npe) {
4526 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4527 npe.printStackTrace();
4528 }
Wink Saville32506bc2013-06-29 21:10:57 -07004529 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004530 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004531 }
4532
Robert Greenwalt39d56012013-07-16 12:06:09 -07004533 /** Location to an updatable file listing carrier provisioning urls.
4534 * An example:
4535 *
4536 * <?xml version="1.0" encoding="utf-8"?>
4537 * <provisioningUrls>
4538 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4539 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4540 * </provisioningUrls>
4541 */
4542 private static final String PROVISIONING_URL_PATH =
4543 "/data/misc/radio/provisioning_urls.xml";
4544 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004545
Robert Greenwalt39d56012013-07-16 12:06:09 -07004546 /** XML tag for root element. */
4547 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4548 /** XML tag for individual url */
4549 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4550 /** XML tag for redirected url */
4551 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4552 /** XML attribute for mcc */
4553 private static final String ATTR_MCC = "mcc";
4554 /** XML attribute for mnc */
4555 private static final String ATTR_MNC = "mnc";
4556
4557 private static final int REDIRECTED_PROVISIONING = 1;
4558 private static final int PROVISIONING = 2;
4559
4560 private String getProvisioningUrlBaseFromFile(int type) {
4561 FileReader fileReader = null;
4562 XmlPullParser parser = null;
4563 Configuration config = mContext.getResources().getConfiguration();
4564 String tagType;
4565
4566 switch (type) {
4567 case PROVISIONING:
4568 tagType = TAG_PROVISIONING_URL;
4569 break;
4570 case REDIRECTED_PROVISIONING:
4571 tagType = TAG_REDIRECTED_URL;
4572 break;
4573 default:
4574 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4575 type);
4576 }
4577
4578 try {
4579 fileReader = new FileReader(mProvisioningUrlFile);
4580 parser = Xml.newPullParser();
4581 parser.setInput(fileReader);
4582 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4583
4584 while (true) {
4585 XmlUtils.nextElement(parser);
4586
4587 String element = parser.getName();
4588 if (element == null) break;
4589
4590 if (element.equals(tagType)) {
4591 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4592 try {
4593 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4594 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4595 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4596 parser.next();
4597 if (parser.getEventType() == XmlPullParser.TEXT) {
4598 return parser.getText();
4599 }
4600 }
4601 }
4602 } catch (NumberFormatException e) {
4603 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4604 }
4605 }
4606 }
4607 return null;
4608 } catch (FileNotFoundException e) {
4609 loge("Carrier Provisioning Urls file not found");
4610 } catch (XmlPullParserException e) {
4611 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4612 } catch (IOException e) {
4613 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4614 } finally {
4615 if (fileReader != null) {
4616 try {
4617 fileReader.close();
4618 } catch (IOException e) {}
4619 }
4620 }
4621 return null;
4622 }
4623
Wink Saville8432cf42013-07-20 20:31:59 -07004624 @Override
4625 public String getMobileRedirectedProvisioningUrl() {
4626 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004627 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4628 if (TextUtils.isEmpty(url)) {
4629 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4630 }
4631 return url;
4632 }
4633
Wink Saville8432cf42013-07-20 20:31:59 -07004634 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004635 public String getMobileProvisioningUrl() {
4636 enforceConnectivityInternalPermission();
4637 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4638 if (TextUtils.isEmpty(url)) {
4639 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004640 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004641 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004642 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004643 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004644 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004645 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004646 String phoneNumber = mTelephonyManager.getLine1Number();
4647 if (TextUtils.isEmpty(phoneNumber)) {
4648 phoneNumber = "0000000000";
4649 }
Wink Saville32506bc2013-06-29 21:10:57 -07004650 url = String.format(url,
4651 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4652 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004653 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004654 }
4655
Wink Saville32506bc2013-06-29 21:10:57 -07004656 return url;
4657 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004658
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004659 @Override
4660 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4661 String extraInfo, String url) {
4662 enforceConnectivityInternalPermission();
4663 setProvNotificationVisible(visible, networkType, extraInfo, url);
4664 }
Wink Savillecb117d32013-08-29 14:57:08 -07004665
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004666 private void onUserStart(int userId) {
4667 synchronized(mVpns) {
4668 Vpn userVpn = mVpns.get(userId);
4669 if (userVpn != null) {
4670 loge("Starting user already has a VPN");
4671 return;
4672 }
4673 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4674 mVpns.put(userId, userVpn);
4675 userVpn.startMonitoring(mContext, mTrackerHandler);
4676 }
4677 }
4678
4679 private void onUserStop(int userId) {
4680 synchronized(mVpns) {
4681 Vpn userVpn = mVpns.get(userId);
4682 if (userVpn == null) {
4683 loge("Stopping user has no VPN");
4684 return;
4685 }
4686 mVpns.delete(userId);
4687 }
4688 }
4689
4690 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4691 @Override
4692 public void onReceive(Context context, Intent intent) {
4693 final String action = intent.getAction();
4694 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4695 if (userId == UserHandle.USER_NULL) return;
4696
4697 if (Intent.ACTION_USER_STARTING.equals(action)) {
4698 onUserStart(userId);
4699 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4700 onUserStop(userId);
4701 }
4702 }
4703 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004704
4705 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004706 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004707 enforceAccessPermission();
4708 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004709 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004710 } else {
4711 return null;
4712 }
4713 }
4714
4715 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004716 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004717 enforceAccessPermission();
4718 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004719 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004720 } else {
4721 return null;
4722 }
4723 }
4724
4725 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004726 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004727 enforceAccessPermission();
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004728 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004729 for (NetworkStateTracker tracker : mNetTrackers) {
4730 if (tracker != null) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004731 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004732 if (li != null) {
4733 result.add(li);
4734 }
4735 }
4736 }
4737
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004738 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004739 }
4740
4741 /* Infrastructure for network sampling */
4742
4743 private void handleNetworkSamplingTimeout() {
4744
4745 log("Sampling interval elapsed, updating statistics ..");
4746
4747 // initialize list of interfaces ..
4748 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4749 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4750 for (NetworkStateTracker tracker : mNetTrackers) {
4751 if (tracker != null) {
4752 String ifaceName = tracker.getNetworkInterfaceName();
4753 if (ifaceName != null) {
4754 mapIfaceToSample.put(ifaceName, null);
4755 }
4756 }
4757 }
4758
4759 // Read samples for all interfaces
4760 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4761
4762 // process samples for all networks
4763 for (NetworkStateTracker tracker : mNetTrackers) {
4764 if (tracker != null) {
4765 String ifaceName = tracker.getNetworkInterfaceName();
4766 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4767 if (ss != null) {
4768 // end the previous sampling cycle
4769 tracker.stopSampling(ss);
4770 // start a new sampling cycle ..
4771 tracker.startSampling(ss);
4772 }
4773 }
4774 }
4775
4776 log("Done.");
4777
4778 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4779 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4780 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4781
4782 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4783
4784 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4785 }
4786
4787 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4788 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4789 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4790 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004791}
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004792