blob: a9b4f19f7a33b899dd34411793e6a93ab40d1d6b [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 Deshapndedb7abcb2013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Saville690cb182013-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 Saville89c87b92013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkeyf2e722a2012-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 Sharkeyf2e722a2012-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 Greenwalt7ddc6c92013-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 Sheriffba8388b2012-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;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Jeff Sharkey86dc7a82013-09-10 21:03:27 -070062import android.net.LinkQualityInfo;
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 Deshapndedb7abcb2013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monk43324ee2013-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 Saville690cb182013-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 Greenwalt030e1d32012-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 Sharkey5663b6e2012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070093import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080094import android.os.SystemProperties;
Dianne Hackbornbc55bd12012-08-29 18:32:08 -070095import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080096import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070097import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -070098import android.security.KeyStore;
Wink Saville690cb182013-06-29 21:10:57 -070099import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700100import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800101import android.util.Slog;
Chad Brubakerccae0d32013-06-14 11:16:51 -0700102import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800105
Wink Saville690cb182013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk43324ee2013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700108import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700109import com.android.internal.net.VpnConfig;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700110import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-06-29 21:10:57 -0700111import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700112import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700113import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700114import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700115import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700116import com.android.server.am.BatteryStatsService;
John Spurlock4ba7e412013-06-24 14:20:23 -0400117import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900118import com.android.server.connectivity.Nat464Xlat;
Jason Monk43324ee2013-07-03 17:04:33 -0400119import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700126
tk.mun093f55c2011-10-13 22:51:57 +0900127import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700128
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700129import org.xmlpull.v1.XmlPullParser;
130import org.xmlpull.v1.XmlPullParserException;
131
132import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import java.io.FileDescriptor;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700134import java.io.FileNotFoundException;
135import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700136import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800137import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900138import java.lang.reflect.Constructor;
Wink Saville690cb182013-06-29 21:10:57 -0700139import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700140import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700141import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700142import java.net.InetAddress;
Wink Saville690cb182013-06-29 21:10:57 -0700143import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700144import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700145import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700146import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700147import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700148import java.util.GregorianCalendar;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700149import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700150import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700151import java.util.List;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700152import java.util.Map;
Wink Saville690cb182013-06-29 21:10:57 -0700153import java.util.Random;
Wink Saville89c87b92013-08-29 08:55:16 -0700154import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville690cb182013-06-29 21:10:57 -0700155import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156
157/**
158 * @hide
159 */
160public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700161 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700163 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700164 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800165
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700166 private static final boolean LOGD_RULES = false;
167
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700168 // TODO: create better separation between radio types and network types
169
Robert Greenwalt2034b912009-08-12 16:08:25 -0700170 // how long to wait before switching back to a radio's default network
171 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
172 // system property that can override the above value
173 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
174 "android.telephony.apn-restore";
175
Wink Saville690cb182013-06-29 21:10:57 -0700176 // Default value if FAIL_FAST_TIME_MS is not set
177 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
178 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
179 private static final String FAIL_FAST_TIME_MS =
180 "persist.radio.fail_fast_time_ms";
181
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700182 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
183 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
184
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700185 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700186
187 private PendingIntent mSampleIntervalElapsedIntent;
188
189 // Set network sampling interval at 12 minutes, this way, even if the timers get
190 // aggregated, it will fire at around 15 minutes, which should allow us to
191 // aggregate this timer with other timers (specially the socket keep alive timers)
192 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
193
194 // start network sampling a minute after booting ...
195 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
196
197 AlarmManager mAlarmManager;
198
Robert Greenwaltbd492212011-05-06 17:10:53 -0700199 // used in recursive route setting to add gateways for the host for which
200 // a host route was requested.
201 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
202
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800203 private Tethering mTethering;
204
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700205 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700206
Chad Brubakerccae0d32013-06-14 11:16:51 -0700207 @GuardedBy("mVpns")
208 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700209 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700210
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700211 private boolean mLockdownEnabled;
212 private LockdownVpnTracker mLockdownTracker;
213
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900214 private Nat464Xlat mClat;
215
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700216 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
217 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700218 /** Currently active network rules by UID. */
219 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700220 /** Set of ifaces that are costly. */
221 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700222
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223 /**
224 * Sometimes we want to refer to the individual network state
225 * trackers separately, and sometimes we just want to treat them
226 * abstractly.
227 */
228 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700229
Irfan Sheriffba8388b2012-08-16 12:49:23 -0700230 /* Handles captive portal check on a network */
231 private CaptivePortalTracker mCaptivePortalTracker;
232
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233 /**
Wink Saville051a6642011-07-13 13:44:13 -0700234 * The link properties that define the current links
235 */
236 private LinkProperties mCurrentLinkProperties[];
237
238 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700239 * A per Net list of the PID's that requested access to the net
240 * used both as a refcount and for per-PID DNS selection
241 */
Mattias Falkdc919012011-08-23 14:15:13 +0200242 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700243
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244 // priority order of the nettrackers
245 // (excluding dynamically set mNetworkPreference)
246 // TODO - move mNetworkTypePreference into this
247 private int[] mPriorityList;
248
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249 private Context mContext;
250 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700251 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700252 // 0 is full bad, 100 is full good
Wink Saville3e866722013-01-31 00:30:13 +0000253 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700254 private int mDefaultInetConditionPublished = 0;
255 private boolean mInetConditionChangeInFlight = false;
256 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800257
Chia-chi Yehcc844502011-07-14 18:01:57 -0700258 private Object mDnsLock = new Object();
Robert Greenwaltd44340d2013-02-11 15:25:10 -0800259 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800260
261 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700262 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800263
Robert Greenwalt355205c2011-05-10 15:05:02 -0700264 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700265 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700266
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700267 private static final int ENABLED = 1;
268 private static final int DISABLED = 0;
269
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700270 private static final boolean ADD = true;
271 private static final boolean REMOVE = false;
272
273 private static final boolean TO_DEFAULT_TABLE = true;
274 private static final boolean TO_SECONDARY_TABLE = false;
275
Chad Brubaker78850f32013-07-15 16:34:04 -0700276 private static final boolean EXEMPT = true;
277 private static final boolean UNEXEMPT = false;
278
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700279 /**
280 * used internally as a delayed event to make us switch back to the
281 * default network
282 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700283 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700284
285 /**
286 * used internally to change our mobile data enabled flag
287 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700288 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700289
290 /**
291 * used internally to change our network preference setting
292 * arg1 = networkType to prefer
293 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700294 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700295
296 /**
297 * used internally to synchronize inet condition reports
298 * arg1 = networkType
299 * arg2 = condition (0 bad, 100 good)
300 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700301 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700302
303 /**
304 * used internally to mark the end of inet condition hold periods
305 * arg1 = networkType
306 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700307 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700308
309 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700310 * used internally to set enable/disable cellular data
311 * arg1 = ENBALED or DISABLED
312 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700313 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700314
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700315 /**
316 * used internally to clear a wakelock when transitioning
317 * from one net to another
318 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700319 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700320
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700321 /**
322 * used internally to reload global proxy settings
323 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700324 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700325
Robert Greenwalt34848c02011-03-25 13:09:25 -0700326 /**
327 * used internally to set external dependency met/unmet
328 * arg1 = ENABLED (met) or DISABLED (unmet)
329 * arg2 = NetworkType
330 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700331 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700332
Chia-chi Yehcc844502011-07-14 18:01:57 -0700333 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700334 * used internally to send a sticky broadcast delayed.
335 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700336 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700337
Jeff Sharkey805662d2011-08-19 02:24:24 -0700338 /**
339 * Used internally to
340 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
341 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700342 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700343
Chad Brubakera8e81122013-07-23 17:44:41 -0700344 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700345
Wink Saville690cb182013-06-29 21:10:57 -0700346 /**
347 * Used internally to disable fail fast of mobile data
348 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700349 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville690cb182013-06-29 21:10:57 -0700350
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700351 /**
352 * user internally to indicate that data sampling interval is up
353 */
354 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
355
Jason Monk445cea82013-10-10 14:02:51 -0400356 /**
357 * PAC manager has received new port.
358 */
359 private static final int EVENT_PROXY_HAS_CHANGED = 16;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700360
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700361 /** Handler used for internal events. */
362 private InternalHandler mHandler;
363 /** Handler used for incoming {@link NetworkStateTracker} events. */
364 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700365
366 // list of DeathRecipients used to make sure features are turned off when
367 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500368 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700369
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400370 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800371 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400372
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700373 private PowerManager.WakeLock mNetTransitionWakeLock;
374 private String mNetTransitionWakeLockCausedBy = "";
375 private int mNetTransitionWakeLockSerialNumber;
376 private int mNetTransitionWakeLockTimeout;
377
Robert Greenwalt94daa182010-09-01 11:34:05 -0700378 private InetAddress mDefaultDns;
379
Chad Brubaker78850f32013-07-15 16:34:04 -0700380 // Lock for protecting access to mAddedRoutes and mExemptAddresses
381 private final Object mRoutesLock = new Object();
382
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700383 // this collection is used to refcount the added routes - if there are none left
384 // it's time to remove the route from the route table
Chad Brubaker78850f32013-07-15 16:34:04 -0700385 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700386 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
387
Chad Brubaker78850f32013-07-15 16:34:04 -0700388 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
389 // used to handle cleanup of exempt rules
390 @GuardedBy("mRoutesLock")
391 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
392
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700393 // used in DBG mode to track inet condition reports
394 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
395 private ArrayList mInetLog;
396
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700397 // track the current default http proxy - tell the world if we get a new one (real change)
398 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltda77cb12013-04-05 17:14:19 -0700399 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700400 private boolean mDefaultProxyDisabled = false;
401
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700402 // track the global proxy.
403 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700404
Jason Monk43324ee2013-07-03 17:04:33 -0400405 private PacManager mPacManager = null;
406
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700407 private SettingsObserver mSettingsObserver;
408
Robert Greenwalt34848c02011-03-25 13:09:25 -0700409 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700410 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700411
Robert Greenwalt12c44552009-12-07 11:33:18 -0800412 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700413 public int mSimultaneity;
414 public int mType;
415 public RadioAttributes(String init) {
416 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700417 mType = Integer.parseInt(fragments[0]);
418 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700419 }
420 }
421 RadioAttributes[] mRadioAttributes;
422
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700423 // the set of network types that can only be enabled by system/sig apps
424 List mProtectedNetworks;
425
John Spurlock4ba7e412013-06-24 14:20:23 -0400426 private DataConnectionStats mDataConnectionStats;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700427
Wink Saville690cb182013-06-29 21:10:57 -0700428 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
429
430 TelephonyManager mTelephonyManager;
431
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700432 public ConnectivityService(Context context, INetworkManagementService netd,
433 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700434 // Currently, omitting a NetworkFactory will create one internally
435 // TODO: create here when we have cleaner WiMAX support
436 this(context, netd, statsService, policyManager, null);
437 }
438
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700439 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700440 INetworkStatsService statsService, INetworkPolicyManager policyManager,
441 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800442 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800443
Wink Saville775aad62010-09-02 19:23:52 -0700444 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
445 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700446 mHandler = new InternalHandler(handlerThread.getLooper());
447 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700448
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700449 if (netFactory == null) {
450 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
451 }
452
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800453 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800454 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
455 String id = Settings.Secure.getString(context.getContentResolver(),
456 Settings.Secure.ANDROID_ID);
457 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700458 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800459 SystemProperties.set("net.hostname", name);
460 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800461 }
462
Robert Greenwalt94daa182010-09-01 11:34:05 -0700463 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700464 String dns = Settings.Global.getString(context.getContentResolver(),
465 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700466 if (dns == null || dns.length() == 0) {
467 dns = context.getResources().getString(
468 com.android.internal.R.string.config_default_dns_server);
469 }
470 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800471 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
472 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800473 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700474 }
475
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700476 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700477 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700478 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700479 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700480 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700481
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700482 try {
483 mPolicyManager.registerListener(mPolicyListener);
484 } catch (RemoteException e) {
485 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700486 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700487 }
488
489 final PowerManager powerManager = (PowerManager) context.getSystemService(
490 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700491 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
492 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
493 com.android.internal.R.integer.config_networkTransitionTimeout);
494
Robert Greenwalt2034b912009-08-12 16:08:25 -0700495 mNetTrackers = new NetworkStateTracker[
496 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700497 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700498
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700499 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700500 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700501
Robert Greenwalt2034b912009-08-12 16:08:25 -0700502 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700503 String[] raStrings = context.getResources().getStringArray(
504 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 for (String raString : raStrings) {
506 RadioAttributes r = new RadioAttributes(raString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700507 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700508 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800509 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700510 continue;
511 }
512 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800513 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700514 r.mType);
515 continue;
516 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700517 mRadioAttributes[r.mType] = r;
518 }
519
Wink Saville23ee8db2013-04-23 14:26:51 -0700520 // TODO: What is the "correct" way to do determine if this is a wifi only device?
521 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
522 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700523 String[] naStrings = context.getResources().getStringArray(
524 com.android.internal.R.array.networkAttributes);
525 for (String naString : naStrings) {
526 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700527 NetworkConfig n = new NetworkConfig(naString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700528 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700529 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800530 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700531 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700532 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700533 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700534 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
535 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
536 n.type);
537 continue;
538 }
Wink Savillef2a62832011-04-07 14:23:45 -0700539 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800540 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700541 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700542 continue;
543 }
Wink Savillef2a62832011-04-07 14:23:45 -0700544 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800545 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700546 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700547 continue;
548 }
Wink Savillef2a62832011-04-07 14:23:45 -0700549 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700550 mNetworksDefined++;
551 } catch(Exception e) {
552 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553 }
554 }
Wink Saville70dbdcc2013-07-29 15:00:57 -0700555 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700557 mProtectedNetworks = new ArrayList<Integer>();
558 int[] protectedNetworks = context.getResources().getIntArray(
559 com.android.internal.R.array.config_protectedNetworks);
560 for (int p : protectedNetworks) {
561 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
562 mProtectedNetworks.add(p);
563 } else {
564 if (DBG) loge("Ignoring protectedNetwork " + p);
565 }
566 }
567
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700568 // high priority first
569 mPriorityList = new int[mNetworksDefined];
570 {
571 int insertionPoint = mNetworksDefined-1;
572 int currentLowest = 0;
573 int nextLowest = 0;
574 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700575 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700576 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700577 if (na.priority < currentLowest) continue;
578 if (na.priority > currentLowest) {
579 if (na.priority < nextLowest || nextLowest == 0) {
580 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700581 }
582 continue;
583 }
Wink Savillef2a62832011-04-07 14:23:45 -0700584 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700585 }
586 currentLowest = nextLowest;
587 nextLowest = 0;
588 }
589 }
590
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800591 // Update mNetworkPreference according to user mannually first then overlay config.xml
592 mNetworkPreference = getPersistedNetworkPreference();
593 if (mNetworkPreference == -1) {
594 for (int n : mPriorityList) {
595 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
596 mNetworkPreference = n;
597 break;
598 }
599 }
600 if (mNetworkPreference == -1) {
601 throw new IllegalStateException(
602 "You should set at least one default Network in config.xml!");
603 }
604 }
605
Mattias Falkdc919012011-08-23 14:15:13 +0200606 mNetRequestersPids =
607 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700608 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200609 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700610 }
611
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500612 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700613
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700614 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
615 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700616
617 // Create and start trackers for hard-coded networks
618 for (int targetNetworkType : mPriorityList) {
619 final NetworkConfig config = mNetConfigs[targetNetworkType];
620 final NetworkStateTracker tracker;
621 try {
622 tracker = netFactory.createTracker(targetNetworkType, config);
623 mNetTrackers[targetNetworkType] = tracker;
624 } catch (IllegalArgumentException e) {
625 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
626 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700627 continue;
628 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700629
630 tracker.startMonitoring(context, mTrackerHandler);
631 if (config.isDefault()) {
632 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800633 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700634 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800635
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700636 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800637
Robert Greenwalt00eb17f2013-07-19 14:30:49 -0700638 //set up the listener for user state for creating user VPNs
Chad Brubakerccae0d32013-06-14 11:16:51 -0700639 IntentFilter intentFilter = new IntentFilter();
640 intentFilter.addAction(Intent.ACTION_USER_STARTING);
641 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
642 mContext.registerReceiverAsUser(
643 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900644 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
645
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700646 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700647 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700648 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900649 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700650 } catch (RemoteException e) {
651 loge("Error registering observer :" + e);
652 }
653
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700654 if (DBG) {
655 mInetLog = new ArrayList();
656 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700657
658 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
659 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800660
John Spurlock4ba7e412013-06-24 14:20:23 -0400661 mDataConnectionStats = new DataConnectionStats(mContext);
662 mDataConnectionStats.startMonitoring();
Jason Monk43324ee2013-07-03 17:04:33 -0400663
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700664 // start network sampling ..
665 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
666 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700667 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700668
669 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
670 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
671
672 IntentFilter filter = new IntentFilter();
673 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
674 mContext.registerReceiver(
675 new BroadcastReceiver() {
676 @Override
677 public void onReceive(Context context, Intent intent) {
678 String action = intent.getAction();
679 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
680 mHandler.sendMessage(mHandler.obtainMessage
681 (EVENT_SAMPLE_INTERVAL_ELAPSED));
682 }
683 }
684 },
685 new IntentFilter(filter));
686
Jason Monk445cea82013-10-10 14:02:51 -0400687 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville3ade4872013-08-29 14:57:08 -0700688
689 filter = new IntentFilter();
Wink Saville89c87b92013-08-29 08:55:16 -0700690 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
691 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800692 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700693
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700694 /**
695 * Factory that creates {@link NetworkStateTracker} instances using given
696 * {@link NetworkConfig}.
697 */
698 public interface NetworkFactory {
699 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
700 }
701
702 private static class DefaultNetworkFactory implements NetworkFactory {
703 private final Context mContext;
704 private final Handler mTrackerHandler;
705
706 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
707 mContext = context;
708 mTrackerHandler = trackerHandler;
709 }
710
711 @Override
712 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
713 switch (config.radio) {
714 case TYPE_WIFI:
715 return new WifiStateTracker(targetNetworkType, config.name);
716 case TYPE_MOBILE:
717 return new MobileDataStateTracker(targetNetworkType, config.name);
718 case TYPE_DUMMY:
719 return new DummyDataStateTracker(targetNetworkType, config.name);
720 case TYPE_BLUETOOTH:
721 return BluetoothTetheringDataTracker.getInstance();
722 case TYPE_WIMAX:
723 return makeWimaxStateTracker(mContext, mTrackerHandler);
724 case TYPE_ETHERNET:
725 return EthernetDataTracker.getInstance();
726 default:
727 throw new IllegalArgumentException(
728 "Trying to create a NetworkStateTracker for an unknown radio type: "
729 + config.radio);
730 }
731 }
732 }
733
734 /**
735 * Loads external WiMAX library and registers as system service, returning a
736 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
737 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
738 */
739 private static NetworkStateTracker makeWimaxStateTracker(
740 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700741 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900742 DexClassLoader wimaxClassLoader;
743 Class wimaxStateTrackerClass = null;
744 Class wimaxServiceClass = null;
745 Class wimaxManagerClass;
746 String wimaxJarLocation;
747 String wimaxLibLocation;
748 String wimaxManagerClassName;
749 String wimaxServiceClassName;
750 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800751
tk.mun093f55c2011-10-13 22:51:57 +0900752 NetworkStateTracker wimaxStateTracker = null;
753
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700754 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900755 com.android.internal.R.bool.config_wimaxEnabled);
756
757 if (isWimaxEnabled) {
758 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700759 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900760 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700761 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900762 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700763 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900764 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700765 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900766 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700767 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900768 com.android.internal.R.string.config_wimaxStateTrackerClassname);
769
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800770 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900771 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700772 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900773 wimaxLibLocation, ClassLoader.getSystemClassLoader());
774
775 try {
776 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
777 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
778 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
779 } catch (ClassNotFoundException ex) {
780 loge("Exception finding Wimax classes: " + ex.toString());
781 return null;
782 }
783 } catch(Resources.NotFoundException ex) {
784 loge("Wimax Resources does not exist!!! ");
785 return null;
786 }
787
788 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800789 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900790
791 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
792 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700793 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
794 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900795
796 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
797 (new Class[] {Context.class, wimaxStateTrackerClass});
798 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700799 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900800 wmxSrvConst.setAccessible(false);
801
802 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
803
804 } catch(Exception ex) {
805 loge("Exception creating Wimax classes: " + ex.toString());
806 return null;
807 }
808 } else {
809 loge("Wimax is not enabled or not added to the network attributes!!! ");
810 return null;
811 }
812
813 return wimaxStateTracker;
814 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700815
The Android Open Source Project28527d22009-03-03 19:31:44 -0800816 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700817 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800818 * @param preference the new preference
819 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700820 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800821 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700822
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700823 mHandler.sendMessage(
824 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800825 }
826
827 public int getNetworkPreference() {
828 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700829 int preference;
830 synchronized(this) {
831 preference = mNetworkPreference;
832 }
833 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800834 }
835
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700836 private void handleSetNetworkPreference(int preference) {
837 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700838 mNetConfigs[preference] != null &&
839 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700840 if (mNetworkPreference != preference) {
841 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700842 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700843 synchronized(this) {
844 mNetworkPreference = preference;
845 }
846 enforcePreference();
847 }
848 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800849 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700850
Wink Saville4f0de1e2011-08-04 15:01:58 -0700851 private int getConnectivityChangeDelay() {
852 final ContentResolver cr = mContext.getContentResolver();
853
854 /** Check system properties for the default value then use secure settings value, if any. */
855 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700856 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
857 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
858 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700859 defaultDelay);
860 }
861
The Android Open Source Project28527d22009-03-03 19:31:44 -0800862 private int getPersistedNetworkPreference() {
863 final ContentResolver cr = mContext.getContentResolver();
864
Jeff Brown87272712012-09-25 15:03:20 -0700865 final int networkPrefSetting = Settings.Global
866 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800867
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800868 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700870
The Android Open Source Project28527d22009-03-03 19:31:44 -0800871 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700872 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800873 * In this method, we only tear down a non-preferred network. Establishing
874 * a connection to the preferred network is taken care of when we handle
875 * the disconnect event from the non-preferred network
876 * (see {@link #handleDisconnect(NetworkInfo)}).
877 */
878 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700879 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800880 return;
881
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882 if (!mNetTrackers[mNetworkPreference].isAvailable())
883 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800884
Robert Greenwalt2034b912009-08-12 16:08:25 -0700885 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700886 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700887 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700888 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800889 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700890 " in enforcePreference");
891 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800893 }
894 }
895 }
896
897 private boolean teardown(NetworkStateTracker netTracker) {
898 if (netTracker.teardown()) {
899 netTracker.setTeardownRequested(true);
900 return true;
901 } else {
902 return false;
903 }
904 }
905
906 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700907 * Check if UID should be blocked from using the network represented by the
908 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700909 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700910 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
911 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700912
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700913 final boolean networkCostly;
914 final int uidRules;
915 synchronized (mRulesLock) {
916 networkCostly = mMeteredIfaces.contains(iface);
917 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700918 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700919
920 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
921 return true;
922 }
923
924 // no restrictive rules; network is visible
925 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700926 }
927
928 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700929 * Return a filtered {@link NetworkInfo}, potentially marked
930 * {@link DetailedState#BLOCKED} based on
931 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700932 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700933 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
934 NetworkInfo info = tracker.getNetworkInfo();
935 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700936 // network is blocked; clone and override state
937 info = new NetworkInfo(info);
938 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700939 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700940 if (mLockdownTracker != null) {
941 info = mLockdownTracker.augmentNetworkInfo(info);
942 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700943 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700944 }
945
946 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800947 * Return NetworkInfo for the active (i.e., connected) network interface.
948 * It is assumed that at most one network is active at a time. If more
949 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700950 * @return the info for the active network, or {@code null} if none is
951 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800952 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700953 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800954 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700955 enforceAccessPermission();
956 final int uid = Binder.getCallingUid();
957 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800958 }
959
Wink Saville89c87b92013-08-29 08:55:16 -0700960 /**
961 * Find the first Provisioning network.
962 *
963 * @return NetworkInfo or null if none.
964 */
965 private NetworkInfo getProvisioningNetworkInfo() {
966 enforceAccessPermission();
967
968 // Find the first Provisioning Network
969 NetworkInfo provNi = null;
970 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville860f5282013-09-05 12:02:25 -0700971 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -0700972 provNi = ni;
973 break;
974 }
975 }
976 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
977 return provNi;
978 }
979
980 /**
981 * Find the first Provisioning network or the ActiveDefaultNetwork
982 * if there is no Provisioning network
983 *
984 * @return NetworkInfo or null if none.
985 */
986 @Override
987 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
988 enforceAccessPermission();
989
990 NetworkInfo provNi = getProvisioningNetworkInfo();
991 if (provNi == null) {
992 final int uid = Binder.getCallingUid();
993 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
994 }
995 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
996 return provNi;
997 }
998
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700999 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1000 enforceAccessPermission();
1001 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1002 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1003 if (tracker != null) {
1004 return tracker.getNetworkInfo();
1005 }
1006 }
1007 return null;
1008 }
1009
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001010 @Override
1011 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1012 enforceConnectivityInternalPermission();
1013 return getNetworkInfo(mActiveDefaultNetwork, uid);
1014 }
1015
1016 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001017 public NetworkInfo getNetworkInfo(int networkType) {
1018 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001019 final int uid = Binder.getCallingUid();
1020 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001021 }
1022
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001023 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1024 NetworkInfo info = null;
1025 if (isNetworkTypeValid(networkType)) {
1026 final NetworkStateTracker tracker = mNetTrackers[networkType];
1027 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001028 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001029 }
1030 }
1031 return info;
1032 }
1033
1034 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001035 public NetworkInfo[] getAllNetworkInfo() {
1036 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001037 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001038 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001039 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001040 for (NetworkStateTracker tracker : mNetTrackers) {
1041 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001042 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001043 }
1044 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001045 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001046 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001047 }
1048
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001049 @Override
1050 public boolean isNetworkSupported(int networkType) {
1051 enforceAccessPermission();
1052 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1053 }
1054
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001055 /**
1056 * Return LinkProperties for the active (i.e., connected) default
1057 * network interface. It is assumed that at most one default network
1058 * is active at a time. If more than one is active, it is indeterminate
1059 * which will be returned.
1060 * @return the ip properties for the active network, or {@code null} if
1061 * none is active
1062 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001063 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001064 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001065 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001066 }
1067
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001068 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001069 public LinkProperties getLinkProperties(int networkType) {
1070 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001071 if (isNetworkTypeValid(networkType)) {
1072 final NetworkStateTracker tracker = mNetTrackers[networkType];
1073 if (tracker != null) {
1074 return tracker.getLinkProperties();
1075 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001076 }
1077 return null;
1078 }
1079
Jeff Sharkey21062e72011-05-28 20:56:34 -07001080 @Override
1081 public NetworkState[] getAllNetworkState() {
1082 enforceAccessPermission();
1083 final int uid = Binder.getCallingUid();
1084 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001085 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001086 for (NetworkStateTracker tracker : mNetTrackers) {
1087 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001088 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001089 result.add(new NetworkState(
1090 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1091 }
1092 }
1093 }
1094 return result.toArray(new NetworkState[result.size()]);
1095 }
1096
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001097 private NetworkState getNetworkStateUnchecked(int networkType) {
1098 if (isNetworkTypeValid(networkType)) {
1099 final NetworkStateTracker tracker = mNetTrackers[networkType];
1100 if (tracker != null) {
1101 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1102 tracker.getLinkCapabilities());
1103 }
1104 }
1105 return null;
1106 }
1107
1108 @Override
1109 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1110 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001111
1112 final long token = Binder.clearCallingIdentity();
1113 try {
1114 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1115 if (state != null) {
1116 try {
1117 return mPolicyManager.getNetworkQuotaInfo(state);
1118 } catch (RemoteException e) {
1119 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001120 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001121 return null;
1122 } finally {
1123 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001124 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001125 }
1126
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001127 @Override
1128 public boolean isActiveNetworkMetered() {
1129 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001130 final long token = Binder.clearCallingIdentity();
1131 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001132 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001133 } finally {
1134 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001135 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001136 }
1137
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001138 private boolean isNetworkMeteredUnchecked(int networkType) {
1139 final NetworkState state = getNetworkStateUnchecked(networkType);
1140 if (state != null) {
1141 try {
1142 return mPolicyManager.isNetworkMetered(state);
1143 } catch (RemoteException e) {
1144 }
1145 }
1146 return false;
1147 }
1148
The Android Open Source Project28527d22009-03-03 19:31:44 -08001149 public boolean setRadios(boolean turnOn) {
1150 boolean result = true;
1151 enforceChangePermission();
1152 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001153 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001154 }
1155 return result;
1156 }
1157
1158 public boolean setRadio(int netType, boolean turnOn) {
1159 enforceChangePermission();
1160 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1161 return false;
1162 }
1163 NetworkStateTracker tracker = mNetTrackers[netType];
1164 return tracker != null && tracker.setRadio(turnOn);
1165 }
1166
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001167 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1168 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001169 public void interfaceClassDataActivityChanged(String label, boolean active) {
1170 int deviceType = Integer.parseInt(label);
1171 sendDataActivityBroadcast(deviceType, active);
1172 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001173 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001174
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001175 /**
1176 * Used to notice when the calling process dies so we can self-expire
1177 *
1178 * Also used to know if the process has cleaned up after itself when
1179 * our auto-expire timer goes off. The timer has a link to an object.
1180 *
1181 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001182 private class FeatureUser implements IBinder.DeathRecipient {
1183 int mNetworkType;
1184 String mFeature;
1185 IBinder mBinder;
1186 int mPid;
1187 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001188 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001189
1190 FeatureUser(int type, String feature, IBinder binder) {
1191 super();
1192 mNetworkType = type;
1193 mFeature = feature;
1194 mBinder = binder;
1195 mPid = getCallingPid();
1196 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001197 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001198
Robert Greenwalt2034b912009-08-12 16:08:25 -07001199 try {
1200 mBinder.linkToDeath(this, 0);
1201 } catch (RemoteException e) {
1202 binderDied();
1203 }
1204 }
1205
1206 void unlinkDeathRecipient() {
1207 mBinder.unlinkToDeath(this, 0);
1208 }
1209
1210 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001211 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001212 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1213 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001214 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001215 }
1216
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001217 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001218 if (VDBG) {
1219 log("ConnectivityService FeatureUser expire(" +
1220 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1221 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1222 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001223 stopUsingNetworkFeature(this, false);
1224 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001225
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001226 public boolean isSameUser(FeatureUser u) {
1227 if (u == null) return false;
1228
1229 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1230 }
1231
1232 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1233 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1234 TextUtils.equals(mFeature, feature)) {
1235 return true;
1236 }
1237 return false;
1238 }
1239
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001240 public String toString() {
1241 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1242 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1243 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001244 }
1245
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001246 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001247 public int startUsingNetworkFeature(int networkType, String feature,
1248 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001249 long startTime = 0;
1250 if (DBG) {
1251 startTime = SystemClock.elapsedRealtime();
1252 }
Wink Savillea7d56572011-09-21 11:05:43 -07001253 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001254 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1255 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001256 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001257 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001258 try {
1259 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1260 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001261 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001262 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001263
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001264 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001265
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001266 // TODO - move this into individual networktrackers
1267 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001268
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001269 if (mLockdownEnabled) {
1270 // Since carrier APNs usually aren't available from VPN
1271 // endpoint, mark them as unavailable.
1272 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1273 }
1274
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001275 if (mProtectedNetworks.contains(usedNetworkType)) {
1276 enforceConnectivityInternalPermission();
1277 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001278
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001279 // if UID is restricted, don't allow them to bring up metered APNs
1280 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1281 final int uidRules;
1282 synchronized (mRulesLock) {
1283 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1284 }
1285 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001286 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001287 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001288
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001289 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1290 if (network != null) {
1291 Integer currentPid = new Integer(getCallingPid());
1292 if (usedNetworkType != networkType) {
1293 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001294
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001295 if (ni.isAvailable() == false) {
1296 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1297 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001298 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001299 } else {
1300 // else make the attempt anyway - probably giving REQUEST_STARTED below
1301 if (DBG) {
1302 log("special network not available, but try anyway ni=" +
1303 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001304 }
1305 }
1306 }
1307
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001308 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001309
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001310 synchronized(this) {
1311 boolean addToList = true;
1312 if (restoreTimer < 0) {
1313 // In case there is no timer is specified for the feature,
1314 // make sure we don't add duplicate entry with the same request.
1315 for (FeatureUser u : mFeatureUsers) {
1316 if (u.isSameUser(f)) {
1317 // Duplicate user is found. Do not add.
1318 addToList = false;
1319 break;
1320 }
1321 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001322 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001323
1324 if (addToList) mFeatureUsers.add(f);
1325 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1326 // this gets used for per-pid dns when connected
1327 mNetRequestersPids[usedNetworkType].add(currentPid);
1328 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001329 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001330
1331 if (restoreTimer >= 0) {
1332 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1333 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1334 }
1335
1336 if ((ni.isConnectedOrConnecting() == true) &&
1337 !network.isTeardownRequested()) {
1338 if (ni.isConnected() == true) {
1339 final long token = Binder.clearCallingIdentity();
1340 try {
1341 // add the pid-specific dns
1342 handleDnsConfigurationChange(usedNetworkType);
1343 if (VDBG) log("special network already active");
1344 } finally {
1345 Binder.restoreCallingIdentity(token);
1346 }
Wink Saville64e3f782012-07-10 12:37:54 -07001347 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001348 }
1349 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001350 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001351 }
1352
1353 // check if the radio in play can make another contact
1354 // assume if cannot for now
1355
1356 if (DBG) {
1357 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1358 feature);
1359 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001360 if (network.reconnect()) {
Wink Saville89c87b92013-08-29 08:55:16 -07001361 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001362 return PhoneConstants.APN_REQUEST_STARTED;
1363 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07001364 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001365 return PhoneConstants.APN_REQUEST_FAILED;
1366 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001367 } else {
1368 // need to remember this unsupported request so we respond appropriately on stop
1369 synchronized(this) {
1370 mFeatureUsers.add(f);
1371 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1372 // this gets used for per-pid dns when connected
1373 mNetRequestersPids[usedNetworkType].add(currentPid);
1374 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001375 }
Wink Saville89c87b92013-08-29 08:55:16 -07001376 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001377 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001378 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001379 }
Wink Saville89c87b92013-08-29 08:55:16 -07001380 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001381 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001382 } finally {
1383 if (DBG) {
1384 final long execTime = SystemClock.elapsedRealtime() - startTime;
1385 if (execTime > 250) {
1386 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1387 } else {
1388 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1389 }
1390 }
1391 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001392 }
1393
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001394 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001395 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001396 enforceChangePermission();
1397
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001398 int pid = getCallingPid();
1399 int uid = getCallingUid();
1400
1401 FeatureUser u = null;
1402 boolean found = false;
1403
1404 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001405 for (FeatureUser x : mFeatureUsers) {
1406 if (x.isSameUser(pid, uid, networkType, feature)) {
1407 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001408 found = true;
1409 break;
1410 }
1411 }
1412 }
1413 if (found && u != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07001414 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001415 // stop regardless of how many other time this proc had called start
1416 return stopUsingNetworkFeature(u, true);
1417 } else {
1418 // none found!
Wink Saville89c87b92013-08-29 08:55:16 -07001419 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001420 return 1;
1421 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001422 }
1423
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001424 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1425 int networkType = u.mNetworkType;
1426 String feature = u.mFeature;
1427 int pid = u.mPid;
1428 int uid = u.mUid;
1429
1430 NetworkStateTracker tracker = null;
1431 boolean callTeardown = false; // used to carry our decision outside of sync block
1432
Wink Savillea7d56572011-09-21 11:05:43 -07001433 if (VDBG) {
1434 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001435 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001436
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001438 if (DBG) {
1439 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1440 ", net is invalid");
1441 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001442 return -1;
1443 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001444
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001445 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1446 // sync block
1447 synchronized(this) {
1448 // check if this process still has an outstanding start request
1449 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001450 if (VDBG) {
1451 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1452 ", ignoring");
1453 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001454 return 1;
1455 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001456 u.unlinkDeathRecipient();
1457 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1458 // If we care about duplicate requests, check for that here.
1459 //
1460 // This is done to support the extension of a request - the app
1461 // can request we start the network feature again and renew the
1462 // auto-shutoff delay. Normal "stop" calls from the app though
1463 // do not pay attention to duplicate requests - in effect the
1464 // API does not refcount and a single stop will counter multiple starts.
1465 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001466 for (FeatureUser x : mFeatureUsers) {
1467 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001468 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001469 return 1;
1470 }
1471 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001472 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001473
repo syncf5de5572011-07-29 23:55:49 -07001474 // TODO - move to individual network trackers
1475 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1476
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001477 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001478 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001479 if (DBG) {
1480 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1481 " no known tracker for used net type " + usedNetworkType);
1482 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001483 return -1;
1484 }
1485 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001486 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001487 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001488
1489 final long token = Binder.clearCallingIdentity();
1490 try {
1491 reassessPidDns(pid, true);
1492 } finally {
1493 Binder.restoreCallingIdentity(token);
1494 }
Mattias Falkdc919012011-08-23 14:15:13 +02001495 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001496 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001497 if (VDBG) {
1498 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1499 " others still using it");
1500 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001501 return 1;
1502 }
1503 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001504 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001505 if (DBG) {
1506 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1507 " not a known feature - dropping");
1508 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001509 }
1510 }
Wink Savillea7d56572011-09-21 11:05:43 -07001511
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001512 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001513 if (DBG) {
1514 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1515 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001516 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001517 return 1;
1518 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001519 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001520 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001521 }
1522
1523 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001524 * @deprecated use requestRouteToHostAddress instead
1525 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001526 * Ensure that a network route exists to deliver traffic to the specified
1527 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001528 * @param networkType the type of the network over which traffic to the
1529 * specified host is to be routed
1530 * @param hostAddress the IP address of the host to which the route is
1531 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001532 * @return {@code true} on success, {@code false} on failure
1533 */
1534 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001535 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1536
1537 if (inetAddress == null) {
1538 return false;
1539 }
1540
1541 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1542 }
1543
1544 /**
1545 * Ensure that a network route exists to deliver traffic to the specified
1546 * host via the specified network interface.
1547 * @param networkType the type of the network over which traffic to the
1548 * specified host is to be routed
1549 * @param hostAddress the IP address of the host to which the route is
1550 * desired
1551 * @return {@code true} on success, {@code false} on failure
1552 */
1553 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001554 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001555 if (mProtectedNetworks.contains(networkType)) {
1556 enforceConnectivityInternalPermission();
1557 }
1558
The Android Open Source Project28527d22009-03-03 19:31:44 -08001559 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001560 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001561 return false;
1562 }
1563 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter7caa36a2013-11-07 22:08:24 -08001564 DetailedState netState = DetailedState.DISCONNECTED;
1565 if (tracker != null) {
1566 netState = tracker.getNetworkInfo().getDetailedState();
1567 }
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001568
Ken Mixter7caa36a2013-11-07 22:08:24 -08001569 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001570 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001571 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001572 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001573 log("requestRouteToHostAddress on down network "
1574 + "(" + networkType + ") - dropped"
1575 + " tracker=" + tracker
1576 + " netState=" + netState
1577 + " isTeardownRequested="
1578 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001579 }
1580 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001581 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001582 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001583 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001584 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001585 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker78850f32013-07-15 16:34:04 -07001586 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville690cb182013-06-29 21:10:57 -07001587 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1588 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001589 } catch (UnknownHostException e) {
1590 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1591 } finally {
1592 Binder.restoreCallingIdentity(token);
1593 }
Wink Saville690cb182013-06-29 21:10:57 -07001594 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001595 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001596 }
1597
Chad Brubaker78850f32013-07-15 16:34:04 -07001598 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1599 boolean exempt) {
1600 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001601 }
1602
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001603 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001604 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001605 }
1606
Chad Brubaker78850f32013-07-15 16:34:04 -07001607 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1608 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001609 }
1610
1611 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001612 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001613 }
1614
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001615 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001616 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001617 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001618 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001619 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001620 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001621 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001622 if (bestRoute.getGateway().equals(addr)) {
1623 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001624 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001625 } else {
1626 // if we will connect to this through another route, add a direct route
1627 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001628 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001629 }
1630 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001631 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001632 }
1633
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001634 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001635 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001636 if ((lp == null) || (r == null)) {
1637 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001638 return false;
1639 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001640
1641 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001642 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001643 return false;
1644 }
1645
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001646 String ifaceName = r.getInterface();
1647 if(ifaceName == null) {
1648 loge("Error modifying route - no interface name");
1649 return false;
1650 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001651 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001652 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001653 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001654 if (bestRoute.getGateway().equals(r.getGateway())) {
1655 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001656 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001657 } else {
1658 // if we will connect to our gateway through another route, add a direct
1659 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001660 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1661 bestRoute.getGateway(),
1662 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001663 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001664 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001665 }
1666 }
1667 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001668 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001669 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001670 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001671 synchronized (mRoutesLock) {
1672 // only track default table - only one apps can effect
1673 mAddedRoutes.add(r);
1674 mNetd.addRoute(ifaceName, r);
1675 if (exempt) {
1676 LinkAddress dest = r.getDestination();
1677 if (!mExemptAddresses.contains(dest)) {
1678 mNetd.setHostExemption(dest);
1679 mExemptAddresses.add(dest);
1680 }
1681 }
1682 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001683 } else {
1684 mNetd.addSecondaryRoute(ifaceName, r);
1685 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001686 } catch (Exception e) {
1687 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001688 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001689 return false;
1690 }
1691 } else {
1692 // if we remove this one and there are no more like it, then refcount==0 and
1693 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001694 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001695 synchronized (mRoutesLock) {
1696 mAddedRoutes.remove(r);
1697 if (mAddedRoutes.contains(r) == false) {
1698 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1699 try {
1700 mNetd.removeRoute(ifaceName, r);
1701 LinkAddress dest = r.getDestination();
1702 if (mExemptAddresses.contains(dest)) {
1703 mNetd.clearHostExemption(dest);
1704 mExemptAddresses.remove(dest);
1705 }
1706 } catch (Exception e) {
1707 // never crash - catch them all
1708 if (VDBG) loge("Exception trying to remove a route: " + e);
1709 return false;
1710 }
1711 } else {
1712 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001713 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001714 }
1715 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001716 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001717 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001718 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001719 } catch (Exception e) {
1720 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001721 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001722 return false;
1723 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001724 }
1725 }
1726 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001727 }
1728
1729 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001730 * @see ConnectivityManager#getMobileDataEnabled()
1731 */
1732 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001733 // TODO: This detail should probably be in DataConnectionTracker's
1734 // which is where we store the value and maybe make this
1735 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001736 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001737 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1738 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001739 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001740 return retVal;
1741 }
1742
Robert Greenwalt34848c02011-03-25 13:09:25 -07001743 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001744 enforceConnectivityInternalPermission();
1745
Robert Greenwalt34848c02011-03-25 13:09:25 -07001746 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1747 (met ? ENABLED : DISABLED), networkType));
1748 }
1749
1750 private void handleSetDependencyMet(int networkType, boolean met) {
1751 if (mNetTrackers[networkType] != null) {
1752 if (DBG) {
1753 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1754 }
1755 mNetTrackers[networkType].setDependencyMet(met);
1756 }
1757 }
1758
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001759 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1760 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001761 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001762 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001763 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001764 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001765 }
1766
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001767 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001768 // skip update when we've already applied rules
1769 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1770 if (oldRules == uidRules) return;
1771
1772 mUidRules.put(uid, uidRules);
1773 }
1774
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001775 // TODO: notify UID when it has requested targeted updates
1776 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001777
1778 @Override
1779 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001780 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001781 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001782 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001783 }
1784
1785 synchronized (mRulesLock) {
1786 mMeteredIfaces.clear();
1787 for (String iface : meteredIfaces) {
1788 mMeteredIfaces.add(iface);
1789 }
1790 }
1791 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001792
1793 @Override
1794 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1795 // caller is NPMS, since we only register with them
1796 if (LOGD_RULES) {
1797 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1798 }
1799
1800 // kick off connectivity change broadcast for active network, since
1801 // global background policy change is radical.
1802 final int networkType = mActiveDefaultNetwork;
1803 if (isNetworkTypeValid(networkType)) {
1804 final NetworkStateTracker tracker = mNetTrackers[networkType];
1805 if (tracker != null) {
1806 final NetworkInfo info = tracker.getNetworkInfo();
1807 if (info != null && info.isConnected()) {
1808 sendConnectedBroadcast(info);
1809 }
1810 }
1811 }
1812 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001813 };
1814
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001815 /**
1816 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1817 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001818 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001819 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001820 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001821
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001822 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001823 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001824 }
1825
1826 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001827 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001828 if (VDBG) {
1829 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001830 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001831 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1832 }
tk.mun5eee1042012-01-06 10:43:52 +09001833 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1834 if (VDBG) {
1835 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1836 }
1837 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1838 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001839 }
1840
1841 @Override
1842 public void setPolicyDataEnable(int networkType, boolean enabled) {
1843 // only someone like NPMS should only be calling us
1844 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1845
1846 mHandler.sendMessage(mHandler.obtainMessage(
1847 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1848 }
1849
1850 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1851 if (isNetworkTypeValid(networkType)) {
1852 final NetworkStateTracker tracker = mNetTrackers[networkType];
1853 if (tracker != null) {
1854 tracker.setPolicyDataEnable(enabled);
1855 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001856 }
1857 }
1858
The Android Open Source Project28527d22009-03-03 19:31:44 -08001859 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001860 mContext.enforceCallingOrSelfPermission(
1861 android.Manifest.permission.ACCESS_NETWORK_STATE,
1862 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001863 }
1864
1865 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001866 mContext.enforceCallingOrSelfPermission(
1867 android.Manifest.permission.CHANGE_NETWORK_STATE,
1868 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001869 }
1870
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001871 // TODO Make this a special check when it goes public
1872 private void enforceTetherChangePermission() {
1873 mContext.enforceCallingOrSelfPermission(
1874 android.Manifest.permission.CHANGE_NETWORK_STATE,
1875 "ConnectivityService");
1876 }
1877
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001878 private void enforceTetherAccessPermission() {
1879 mContext.enforceCallingOrSelfPermission(
1880 android.Manifest.permission.ACCESS_NETWORK_STATE,
1881 "ConnectivityService");
1882 }
1883
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001884 private void enforceConnectivityInternalPermission() {
1885 mContext.enforceCallingOrSelfPermission(
1886 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1887 "ConnectivityService");
1888 }
1889
Chad Brubaker31de0b62013-07-11 13:29:30 -07001890 private void enforceMarkNetworkSocketPermission() {
1891 //Media server special case
1892 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1893 return;
1894 }
1895 mContext.enforceCallingOrSelfPermission(
1896 android.Manifest.permission.MARK_NETWORK_SOCKET,
1897 "ConnectivityService");
1898 }
1899
The Android Open Source Project28527d22009-03-03 19:31:44 -08001900 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001901 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1902 * network, we ignore it. If it is for the active network, we send out a
1903 * broadcast. But first, we check whether it might be possible to connect
1904 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001905 * @param info the {@code NetworkInfo} for the network
1906 */
1907 private void handleDisconnect(NetworkInfo info) {
1908
Robert Greenwalt2034b912009-08-12 16:08:25 -07001909 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001910
Robert Greenwalt2034b912009-08-12 16:08:25 -07001911 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001912
1913 // Remove idletimer previously setup in {@code handleConnect}
1914 removeDataActivityTracking(prevNetType);
1915
The Android Open Source Project28527d22009-03-03 19:31:44 -08001916 /*
1917 * If the disconnected network is not the active one, then don't report
1918 * this as a loss of connectivity. What probably happened is that we're
1919 * getting the disconnect for a network that we explicitly disabled
1920 * in accordance with network preference policies.
1921 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001922 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001923 List<Integer> pids = mNetRequestersPids[prevNetType];
1924 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001925 // will remove them because the net's no longer connected
1926 // need to do this now as only now do we know the pids and
1927 // can properly null things that are no longer referenced.
1928 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001930 }
1931
The Android Open Source Project28527d22009-03-03 19:31:44 -08001932 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001933 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001934 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001935 if (info.isFailover()) {
1936 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1937 info.setFailover(false);
1938 }
1939 if (info.getReason() != null) {
1940 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1941 }
1942 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001943 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1944 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001945 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001946
Robert Greenwalt34848c02011-03-25 13:09:25 -07001947 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001948 tryFailover(prevNetType);
1949 if (mActiveDefaultNetwork != -1) {
1950 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001951 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1952 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001953 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001954 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1955 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001956 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001957 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001958
1959 // Reset interface if no other connections are using the same interface
1960 boolean doReset = true;
1961 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1962 if (linkProperties != null) {
1963 String oldIface = linkProperties.getInterfaceName();
1964 if (TextUtils.isEmpty(oldIface) == false) {
1965 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1966 if (networkStateTracker == null) continue;
1967 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1968 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1969 LinkProperties l = networkStateTracker.getLinkProperties();
1970 if (l == null) continue;
1971 if (oldIface.equals(l.getInterfaceName())) {
1972 doReset = false;
1973 break;
1974 }
1975 }
1976 }
1977 }
1978 }
1979
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001980 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001981 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001982
Jeff Sharkey971cd162011-08-29 16:02:57 -07001983 final Intent immediateIntent = new Intent(intent);
1984 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1985 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001986 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001987 /*
1988 * If the failover network is already connected, then immediately send
1989 * out a followup broadcast indicating successful failover
1990 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001991 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001992 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1993 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001994 }
1995 }
1996
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001997 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001998 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001999 * If this is a default network, check if other defaults are available.
2000 * Try to reconnect on all available and let them hash it out when
2001 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07002002 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07002003 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002004 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville89c87b92013-08-29 08:55:16 -07002005 if (DBG) {
2006 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2007 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002008 mActiveDefaultNetwork = -1;
2009 }
2010
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002011 // don't signal a reconnect for anything lower or equal priority than our
2012 // current connected default
2013 // TODO - don't filter by priority now - nice optimization but risky
2014// int currentPriority = -1;
2015// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002016// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002017// }
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002018
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002019 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002020 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002021 if (mNetConfigs[checkType] == null) continue;
2022 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002023 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002024
2025// Enabling the isAvailable() optimization caused mobile to not get
2026// selected if it was in the middle of error handling. Specifically
2027// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2028// would not be available and we wouldn't get connected to anything.
2029// So removing the isAvailable() optimization below for now. TODO: This
2030// optimization should work and we need to investigate why it doesn't work.
2031// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2032// complete before it is really complete.
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002033
Wink Saville72a95b92011-01-26 15:43:49 -08002034// if (!mNetTrackers[checkType].isAvailable()) continue;
2035
Robert Greenwalt34848c02011-03-25 13:09:25 -07002036// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002037
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002038 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2039 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2040 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2041 checkInfo.setFailover(true);
2042 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002043 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002044 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002045 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002046 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002047 }
2048
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002049 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002050 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002051 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2052 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002053 }
2054
Wink Saville4f0de1e2011-08-04 15:01:58 -07002055 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002056 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2057 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002058 }
2059
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002060 private void sendInetConditionBroadcast(NetworkInfo info) {
2061 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2062 }
2063
Wink Saville4f0de1e2011-08-04 15:01:58 -07002064 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002065 if (mLockdownTracker != null) {
2066 info = mLockdownTracker.augmentNetworkInfo(info);
2067 }
2068
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002069 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002070 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002071 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002072 if (info.isFailover()) {
2073 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2074 info.setFailover(false);
2075 }
2076 if (info.getReason() != null) {
2077 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2078 }
2079 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002080 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2081 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002082 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002083 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002084 return intent;
2085 }
2086
2087 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2088 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2089 }
2090
2091 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2092 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093 }
2094
Haoyu Baib5da5752012-06-20 14:29:57 -07002095 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2096 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2097 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2098 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002099 final long ident = Binder.clearCallingIdentity();
2100 try {
2101 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2102 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2103 } finally {
2104 Binder.restoreCallingIdentity(ident);
2105 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002106 }
2107
The Android Open Source Project28527d22009-03-03 19:31:44 -08002108 /**
2109 * Called when an attempt to fail over to another network has failed.
2110 * @param info the {@link NetworkInfo} for the failed network
2111 */
2112 private void handleConnectionFailure(NetworkInfo info) {
2113 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002114
Robert Greenwalt2034b912009-08-12 16:08:25 -07002115 String reason = info.getReason();
2116 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002117
Robert Greenwalte981bc52010-10-08 16:35:52 -07002118 String reasonText;
2119 if (reason == null) {
2120 reasonText = ".";
2121 } else {
2122 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002123 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002124 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002125
2126 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002127 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002128 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002129 if (getActiveNetworkInfo() == null) {
2130 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2131 }
2132 if (reason != null) {
2133 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2134 }
2135 if (extraInfo != null) {
2136 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2137 }
2138 if (info.isFailover()) {
2139 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2140 info.setFailover(false);
2141 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002142
Robert Greenwalt34848c02011-03-25 13:09:25 -07002143 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002144 tryFailover(info.getType());
2145 if (mActiveDefaultNetwork != -1) {
2146 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002147 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2148 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002149 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002150 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2151 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002152 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002153
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002154 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002155
2156 final Intent immediateIntent = new Intent(intent);
2157 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2158 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002159 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002160 /*
2161 * If the failover network is already connected, then immediately send
2162 * out a followup broadcast indicating successful failover
2163 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002164 if (mActiveDefaultNetwork != -1) {
2165 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002166 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002167 }
2168
2169 private void sendStickyBroadcast(Intent intent) {
2170 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002171 if (!mSystemReady) {
2172 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002173 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002174 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002175 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002176 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002177 }
2178
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002179 final long ident = Binder.clearCallingIdentity();
2180 try {
2181 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2182 } finally {
2183 Binder.restoreCallingIdentity(ident);
2184 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002185 }
2186 }
2187
Wink Saville4f0de1e2011-08-04 15:01:58 -07002188 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2189 if (delayMs <= 0) {
2190 sendStickyBroadcast(intent);
2191 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002192 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002193 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2194 + intent.getAction());
2195 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002196 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2197 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2198 }
2199 }
2200
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002201 void systemReady() {
Wink Saville89c87b92013-08-29 08:55:16 -07002202 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2203 loadGlobalProxy();
2204
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002205 synchronized(this) {
2206 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002207 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002208 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002209 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002210 }
2211 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002212 // load the global proxy at startup
2213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002214
2215 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2216 // for user to unlock device.
2217 if (!updateLockdownVpn()) {
2218 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2219 mContext.registerReceiver(mUserPresentReceiver, filter);
2220 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002221 }
2222
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002223 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2224 @Override
2225 public void onReceive(Context context, Intent intent) {
2226 // Try creating lockdown tracker, since user present usually means
2227 // unlocked keystore.
2228 if (updateLockdownVpn()) {
2229 mContext.unregisterReceiver(this);
2230 }
2231 }
2232 };
2233
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002234 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville89c87b92013-08-29 08:55:16 -07002235 if (((type != mNetworkPreference)
2236 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2237 || (mNetworkPreference == mActiveDefaultNetwork)) {
2238 return false;
2239 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002240 return true;
2241 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002243 private void handleConnect(NetworkInfo info) {
2244 final int newNetType = info.getType();
2245
2246 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002247
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248 // snapshot isFailover, because sendConnectedBroadcast() resets it
2249 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002250 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002251 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252
Wink Saville89c87b92013-08-29 08:55:16 -07002253 if (VDBG) {
2254 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2255 + " isFailover" + isFailover);
2256 }
2257
Robert Greenwalt2034b912009-08-12 16:08:25 -07002258 // if this is a default net and other default is running
2259 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002260 if (mNetConfigs[newNetType].isDefault()) {
2261 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2262 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002263 // tear down the other
2264 NetworkStateTracker otherNet =
2265 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002266 if (DBG) {
2267 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002268 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002269 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002270 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002271 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002272 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002273 return;
2274 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002275 } else {
2276 // don't accept this one
2277 if (VDBG) {
2278 log("Not broadcasting CONNECT_ACTION " +
2279 "to torn down network " + info.getTypeName());
2280 }
2281 teardown(thisNet);
2282 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002283 }
2284 }
2285 synchronized (ConnectivityService.this) {
2286 // have a new default network, release the transition wakelock in a second
2287 // if it's held. The second pause is to allow apps to reconnect over the
2288 // new network
2289 if (mNetTransitionWakeLock.isHeld()) {
2290 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002291 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002292 mNetTransitionWakeLockSerialNumber, 0),
2293 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002294 }
2295 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002296 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002297 // this will cause us to come up initially as unconnected and switching
2298 // to connected after our normal pause unless somebody reports us as reall
2299 // disconnected
2300 mDefaultInetConditionPublished = 0;
2301 mDefaultConnectionSequence++;
2302 mInetConditionChangeInFlight = false;
2303 // Don't do this - if we never sign in stay, grey
2304 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002305 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002306 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002307 updateNetworkSettings(thisNet);
sy.yun30043282013-09-02 05:24:09 +09002308 updateMtuSizeSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002309 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002310 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002311
2312 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002313 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002314 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002315 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002316 } catch (RemoteException e) {
2317 // ignored; service lives in system_server
2318 }
2319 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002320 }
2321
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002322 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2323 if (DBG) log("Captive portal check " + info);
2324 int type = info.getType();
2325 final NetworkStateTracker thisNet = mNetTrackers[type];
2326 if (mNetConfigs[type].isDefault()) {
2327 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2328 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2329 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002330 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002331 return;
2332 } else {
2333 if (DBG) log("Tear down low priority net " + info.getTypeName());
2334 teardown(thisNet);
2335 return;
2336 }
2337 }
2338 }
2339
Wink Savilleffdadd62013-08-07 16:22:47 -07002340 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002341 thisNet.captivePortalCheckComplete();
2342 }
2343
2344 /** @hide */
Wink Savilleffdadd62013-08-07 16:22:47 -07002345 @Override
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002346 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002347 enforceConnectivityInternalPermission();
Wink Savilleffdadd62013-08-07 16:22:47 -07002348 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002349 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002350 }
2351
Wink Savilleffdadd62013-08-07 16:22:47 -07002352 /** @hide */
2353 @Override
2354 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2355 enforceConnectivityInternalPermission();
2356 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2357 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2358 }
2359
The Android Open Source Project28527d22009-03-03 19:31:44 -08002360 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002361 * Setup data activity tracking for the given network interface.
2362 *
2363 * Every {@code setupDataActivityTracking} should be paired with a
2364 * {@link removeDataActivityTracking} for cleanup.
2365 */
2366 private void setupDataActivityTracking(int type) {
2367 final NetworkStateTracker thisNet = mNetTrackers[type];
2368 final String iface = thisNet.getLinkProperties().getInterfaceName();
2369
2370 final int timeout;
2371
2372 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002373 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2374 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002375 0);
2376 // Canonicalize mobile network type
2377 type = ConnectivityManager.TYPE_MOBILE;
2378 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002379 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2380 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002381 0);
2382 } else {
2383 // do not track any other networks
2384 timeout = 0;
2385 }
2386
2387 if (timeout > 0 && iface != null) {
2388 try {
2389 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2390 } catch (RemoteException e) {
2391 }
2392 }
2393 }
2394
2395 /**
2396 * Remove data activity tracking when network disconnects.
2397 */
2398 private void removeDataActivityTracking(int type) {
2399 final NetworkStateTracker net = mNetTrackers[type];
2400 final String iface = net.getLinkProperties().getInterfaceName();
2401
2402 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2403 ConnectivityManager.TYPE_WIFI == type)) {
2404 try {
2405 // the call fails silently if no idletimer setup for this interface
2406 mNetd.removeIdleTimer(iface);
2407 } catch (RemoteException e) {
2408 }
2409 }
2410 }
2411
2412 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002413 * After a change in the connectivity state of a network. We're mainly
2414 * concerned with making sure that the list of DNS servers is set up
2415 * according to which networks are connected, and ensuring that the
2416 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002417 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002418 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002419 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker78850f32013-07-15 16:34:04 -07002420 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville89c87b92013-08-29 08:55:16 -07002421 if (VDBG) {
2422 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2423 + " resetMask=" + resetMask);
2424 }
Wink Saville051a6642011-07-13 13:44:13 -07002425
The Android Open Source Project28527d22009-03-03 19:31:44 -08002426 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002427 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002428 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002429 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002430 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002431
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002432 LinkProperties curLp = mCurrentLinkProperties[netType];
2433 LinkProperties newLp = null;
2434
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002435 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002436 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002437 if (VDBG) {
2438 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2439 " doReset=" + doReset + " resetMask=" + resetMask +
2440 "\n curLp=" + curLp +
2441 "\n newLp=" + newLp);
2442 }
2443
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002444 if (curLp != null) {
2445 if (curLp.isIdenticalInterfaceName(newLp)) {
2446 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2447 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2448 for (LinkAddress linkAddr : car.removed) {
2449 if (linkAddr.getAddress() instanceof Inet4Address) {
2450 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2451 }
2452 if (linkAddr.getAddress() instanceof Inet6Address) {
2453 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2454 }
Wink Saville051a6642011-07-13 13:44:13 -07002455 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002456 if (DBG) {
2457 log("handleConnectivityChange: addresses changed" +
2458 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2459 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002460 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002461 } else {
2462 if (DBG) {
2463 log("handleConnectivityChange: address are the same reset per doReset" +
2464 " linkProperty[" + netType + "]:" +
2465 " resetMask=" + resetMask);
2466 }
Wink Saville051a6642011-07-13 13:44:13 -07002467 }
2468 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002469 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002470 if (DBG) {
2471 log("handleConnectivityChange: interface not not equivalent reset both" +
2472 " linkProperty[" + netType + "]:" +
2473 " resetMask=" + resetMask);
2474 }
Wink Saville051a6642011-07-13 13:44:13 -07002475 }
Wink Saville051a6642011-07-13 13:44:13 -07002476 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002477 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002478 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002479 }
2480 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002481 if (VDBG) {
2482 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2483 " doReset=" + doReset + " resetMask=" + resetMask +
2484 "\n curLp=" + curLp +
2485 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002486 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002487 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002488 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker78850f32013-07-15 16:34:04 -07002489 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002490
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002491 if (resetMask != 0 || resetDns) {
Wink Saville89c87b92013-08-29 08:55:16 -07002492 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002493 if (curLp != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07002494 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002495 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002496 if (TextUtils.isEmpty(iface) == false) {
2497 if (resetMask != 0) {
2498 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2499 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002500
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002501 // Tell VPN the interface is down. It is a temporary
2502 // but effective fix to make VPN aware of the change.
2503 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002504 synchronized(mVpns) {
2505 for (int i = 0; i < mVpns.size(); i++) {
2506 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2507 }
2508 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002509 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002510 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002511 if (resetDns) {
2512 flushVmDnsCache();
2513 if (VDBG) log("resetting DNS cache for " + iface);
2514 try {
2515 mNetd.flushInterfaceDnsCache(iface);
2516 } catch (Exception e) {
2517 // never crash - catch them all
2518 if (DBG) loge("Exception resetting dns cache: " + e);
2519 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002520 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002521 } else {
2522 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002523 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002524 }
2525 }
2526 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002527
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002528 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002529 NetworkStateTracker tracker = mNetTrackers[netType];
2530 if (mClat.requiresClat(netType, tracker)) {
Wink Saville89c87b92013-08-29 08:55:16 -07002531
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002532 // If the connection was previously using clat, but is not using it now, stop the clat
2533 // daemon. Normally, this happens automatically when the connection disconnects, but if
2534 // the disconnect is not reported, or if the connection's LinkProperties changed for
2535 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2536 // still be running. If it's not running, then stopping it is a no-op.
2537 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2538 mClat.stopClat();
2539 }
2540 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002541 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2542 mClat.startClat(tracker);
2543 } else {
2544 mClat.stopClat();
2545 }
2546 }
2547
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002548 // TODO: Temporary notifying upstread change to Tethering.
2549 // @see bug/4455071
2550 /** Notify TetheringService if interface name has been changed. */
2551 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002552 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002553 if (isTetheringSupported()) {
2554 mTethering.handleTetherIfaceChange();
2555 }
2556 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002557 }
2558
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002559 /**
2560 * Add and remove routes using the old properties (null if not previously connected),
2561 * new properties (null if becoming disconnected). May even be double null, which
2562 * is a noop.
2563 * Uses isLinkDefault to determine if default routes should be set or conversely if
2564 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002565 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002566 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002567 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker78850f32013-07-15 16:34:04 -07002568 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002569 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002570 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2571 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002572 if (curLp != null) {
2573 // check for the delta between the current set and the new
Lorenzo Colitti43553b62013-07-31 23:23:21 +09002574 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002575 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002576 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002577 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002578 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002579 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002580
Robert Greenwalt8d777252011-08-15 12:31:55 -07002581 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2582
Robert Greenwalt98107422011-07-22 11:55:33 -07002583 for (RouteInfo r : routeDiff.removed) {
2584 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002585 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002586 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2587 }
2588 if (isLinkDefault == false) {
2589 // remove from a secondary route table
2590 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002591 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002592 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002593
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002594 if (!isLinkDefault) {
2595 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002596 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002597 // routes changed - remove all old dns entries and add new
2598 if (curLp != null) {
2599 for (InetAddress oldDns : curLp.getDnses()) {
2600 removeRouteToAddress(curLp, oldDns);
2601 }
2602 }
2603 if (newLp != null) {
2604 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002605 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002606 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002607 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002608 } else {
2609 // no change in routes, check for change in dns themselves
2610 for (InetAddress oldDns : dnsDiff.removed) {
2611 removeRouteToAddress(curLp, oldDns);
2612 }
2613 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002614 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002615 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002616 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002617 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002618
2619 for (RouteInfo r : routeDiff.added) {
2620 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002621 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002622 } else {
2623 // add to a secondary route table
Chad Brubaker78850f32013-07-15 16:34:04 -07002624 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002625
2626 // many radios add a default route even when we don't want one.
2627 // remove the default route unless somebody else has asked for it
2628 String ifaceName = newLp.getInterfaceName();
Chad Brubaker78850f32013-07-15 16:34:04 -07002629 synchronized (mRoutesLock) {
2630 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2631 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2632 try {
2633 mNetd.removeRoute(ifaceName, r);
2634 } catch (Exception e) {
2635 // never crash - catch them all
2636 if (DBG) loge("Exception trying to remove a route: " + e);
2637 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002638 }
2639 }
2640 }
2641 }
2642
Robert Greenwalt8d777252011-08-15 12:31:55 -07002643 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002644 }
2645
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002646 /**
sy.yun30043282013-09-02 05:24:09 +09002647 * Reads the network specific MTU size from reources.
2648 * and set it on it's iface.
2649 */
2650 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2651 final String iface = nt.getLinkProperties().getInterfaceName();
2652 final int mtu = nt.getLinkProperties().getMtu();
2653
2654 if (mtu < 68 || mtu > 10000) {
2655 loge("Unexpected mtu value: " + nt);
2656 return;
2657 }
2658
2659 try {
2660 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2661 mNetd.setMtu(iface, mtu);
2662 } catch (Exception e) {
2663 Slog.e(TAG, "exception in setMtu()" + e);
2664 }
2665 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002666
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002667 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002668 * Reads the network specific TCP buffer sizes from SystemProperties
2669 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2670 * wide use
2671 */
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002672 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002673 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002674 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002675
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002676 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002677 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002678
2679 // Setting to default values so we won't be stuck to previous values
2680 key = "net.tcp.buffersize.default";
2681 bufferSizes = SystemProperties.get(key);
2682 }
2683
2684 // Set values in kernel
2685 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002686 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002687 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002688 + "] which comes from [" + key + "]");
2689 }
2690 setBufferSize(bufferSizes);
2691 }
2692 }
2693
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002694 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002695 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2696 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2697 *
2698 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2699 * writeMin, writeInitial, writeMax"
2700 */
2701 private void setBufferSize(String bufferSizes) {
2702 try {
2703 String[] values = bufferSizes.split(",");
2704
2705 if (values.length == 6) {
2706 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002707 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2708 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2709 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2710 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2711 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2712 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002713 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002714 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002715 }
2716 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002717 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002718 }
2719 }
2720
Robert Greenwalt2034b912009-08-12 16:08:25 -07002721 /**
2722 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2723 * on the highest priority active net which this process requested.
2724 * If there aren't any, clear it out
2725 */
Mattias Falkdc919012011-08-23 14:15:13 +02002726 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002727 {
Mattias Falkdc919012011-08-23 14:15:13 +02002728 if (VDBG) log("reassessPidDns for pid " + pid);
2729 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002730 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002731 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002732 continue;
2733 }
2734 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002735 if (nt.getNetworkInfo().isConnected() &&
2736 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002737 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002738 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002739 if (mNetRequestersPids[i].contains(myPid)) {
2740 try {
2741 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2742 } catch (Exception e) {
2743 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002744 }
Mattias Falkdc919012011-08-23 14:15:13 +02002745 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002746 }
2747 }
2748 }
2749 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002750 try {
2751 mNetd.clearDnsInterfaceForPid(pid);
2752 } catch (Exception e) {
2753 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002754 }
2755 }
2756
Mattias Falkdc919012011-08-23 14:15:13 +02002757 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002758 /*
2759 * Tell the VMs to toss their DNS caches
2760 */
2761 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2762 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002763 /*
2764 * Connectivity events can happen before boot has completed ...
2765 */
2766 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002767 final long ident = Binder.clearCallingIdentity();
2768 try {
2769 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2770 } finally {
2771 Binder.restoreCallingIdentity(ident);
2772 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002773 }
2774
Chia-chi Yehcc844502011-07-14 18:01:57 -07002775 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002776 private void updateDnsLocked(String network, String iface,
Chad Brubaker45e721f2013-07-23 17:13:36 -07002777 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002778 int last = 0;
2779 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002780 dnses = new ArrayList();
2781 dnses.add(mDefaultDns);
2782 if (DBG) {
2783 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002784 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002785 }
2786
Mattias Falkdc919012011-08-23 14:15:13 +02002787 try {
2788 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker45e721f2013-07-23 17:13:36 -07002789 if (defaultDns) {
2790 mNetd.setDefaultInterfaceForDns(iface);
2791 }
2792
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002793 for (InetAddress dns : dnses) {
2794 ++last;
2795 String key = "net.dns" + last;
2796 String value = dns.getHostAddress();
2797 SystemProperties.set(key, value);
2798 }
2799 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2800 String key = "net.dns" + i;
2801 SystemProperties.set(key, "");
2802 }
2803 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002804 } catch (Exception e) {
Robert Greenwalt68534c82013-09-24 11:05:57 -07002805 loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002806 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002807 }
2808
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002809 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002810 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002811 NetworkStateTracker nt = mNetTrackers[netType];
2812 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002813 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002814 if (p == null) return;
2815 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002816 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002817 String network = nt.getNetworkInfo().getTypeName();
2818 synchronized (mDnsLock) {
Chad Brubakera8e81122013-07-23 17:44:41 -07002819 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002820 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002821 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002822 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002823 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002824 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002825 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002826 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002827 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002828 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002829 List<Integer> pids = mNetRequestersPids[netType];
2830 for (Integer pid : pids) {
2831 try {
2832 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2833 } catch (Exception e) {
2834 Slog.e(TAG, "exception setting interface for pid: " + e);
2835 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002836 }
2837 }
Mattias Falkdc919012011-08-23 14:15:13 +02002838 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002839 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002840 }
2841
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002842 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002843 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2844 NETWORK_RESTORE_DELAY_PROP_NAME);
2845 if(restoreDefaultNetworkDelayStr != null &&
2846 restoreDefaultNetworkDelayStr.length() != 0) {
2847 try {
2848 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2849 } catch (NumberFormatException e) {
2850 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002851 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002852 // if the system property isn't set, use the value for the apn type
2853 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2854
2855 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2856 (mNetConfigs[networkType] != null)) {
2857 ret = mNetConfigs[networkType].restoreTime;
2858 }
2859 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002860 }
2861
2862 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002863 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2864 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002865 if (mContext.checkCallingOrSelfPermission(
2866 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002867 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002868 pw.println("Permission Denial: can't dump ConnectivityService " +
2869 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2870 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002871 return;
2872 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002873
2874 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002875 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002876 for (int i = 0; i < mNetTrackers.length; i++) {
2877 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002878 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002879 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2880 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002881 if (nst.getNetworkInfo().isConnected()) {
2882 pw.println("Active network: " + nst.getNetworkInfo().
2883 getTypeName());
2884 }
2885 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002886 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002887 pw.println(nst);
2888 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002889 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002890 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002891 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002892
2893 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002894 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002895 for (int net : mPriorityList) {
2896 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002897 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002898 pidString = pidString + pid.toString() + ", ";
2899 }
2900 pw.println(pidString);
2901 }
2902 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002903 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002904
2905 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002906 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002907 for (Object requester : mFeatureUsers) {
2908 pw.println(requester.toString());
2909 }
2910 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002911 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002912
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002913 synchronized (this) {
2914 pw.println("NetworkTranstionWakeLock is currently " +
2915 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2916 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2917 }
2918 pw.println();
2919
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002920 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002921
2922 if (mInetLog != null) {
2923 pw.println();
2924 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002925 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002926 for(int i = 0; i < mInetLog.size(); i++) {
2927 pw.println(mInetLog.get(i));
2928 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002929 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002930 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002931 }
2932
Robert Greenwalt2034b912009-08-12 16:08:25 -07002933 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002934 private class NetworkStateTrackerHandler extends Handler {
2935 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002936 super(looper);
2937 }
2938
The Android Open Source Project28527d22009-03-03 19:31:44 -08002939 @Override
2940 public void handleMessage(Message msg) {
2941 NetworkInfo info;
2942 switch (msg.what) {
Wink Saville89c87b92013-08-29 08:55:16 -07002943 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002944 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002945 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002946
Wink Savillea7d56572011-09-21 11:05:43 -07002947 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville860f5282013-09-05 12:02:25 -07002948 (state == NetworkInfo.State.DISCONNECTED) ||
2949 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002950 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002951 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002952 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002953 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002954
Wink Saville89c87b92013-08-29 08:55:16 -07002955 // Since mobile has the notion of a network/apn that can be used for
2956 // provisioning we need to check every time we're connected as
2957 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2958 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2959 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2960 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2961 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Saville9564f2b2013-07-16 17:16:37 -07002962 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2963 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleab773a72013-09-14 09:04:53 -07002964 && (((state == NetworkInfo.State.CONNECTED)
2965 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2966 || info.isConnectedToProvisioningNetwork())) {
2967 log("ConnectivityChange checkMobileProvisioning for"
2968 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville89c87b92013-08-29 08:55:16 -07002969 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Saville9564f2b2013-07-16 17:16:37 -07002970 }
2971
Jeff Sharkeybde32692012-11-09 15:57:02 -08002972 EventLogTags.writeConnectivityStateChanged(
2973 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002974
2975 if (info.getDetailedState() ==
2976 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002977 handleConnectionFailure(info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002978 } else if (info.getDetailedState() ==
2979 DetailedState.CAPTIVE_PORTAL_CHECK) {
2980 handleCaptivePortalTrackerCheck(info);
Wink Saville860f5282013-09-05 12:02:25 -07002981 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002982 /**
2983 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2984 * for now its an in between network, its a network that
2985 * is actually a default network but we don't want it to be
2986 * announced as such to keep background applications from
2987 * trying to use it. It turns out that some still try so we
2988 * take the additional step of clearing any default routes
2989 * to the link that may have incorrectly setup by the lower
2990 * levels.
2991 */
2992 LinkProperties lp = getLinkProperties(info.getType());
2993 if (DBG) {
2994 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2995 }
2996
2997 // Clear any default routes setup by the radio so
2998 // any activity by applications trying to use this
2999 // connection will fail until the provisioning network
3000 // is enabled.
3001 for (RouteInfo r : lp.getRoutes()) {
3002 removeRoute(lp, r, TO_DEFAULT_TABLE);
3003 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08003004 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003005 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003006 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003007 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003008 // the logic here is, handle SUSPENDED the same as
3009 // DISCONNECTED. The only difference being we are
3010 // broadcasting an intent with NetworkInfo that's
3011 // suspended. This allows the applications an
3012 // opportunity to handle DISCONNECTED and SUSPENDED
3013 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003014 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003015 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003016 handleConnect(info);
3017 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003018 if (mLockdownTracker != null) {
3019 mLockdownTracker.onNetworkInfoChanged(info);
3020 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003021 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003022 }
3023 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003024 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003025 // TODO: Temporary allowing network configuration
3026 // change not resetting sockets.
3027 // @see bug/4455071
3028 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003029 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003030 }
3031 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003032 info = (NetworkInfo) msg.obj;
Wink Saville89c87b92013-08-29 08:55:16 -07003033 int type = info.getType();
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003034 updateNetworkSettings(mNetTrackers[type]);
3035 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003036 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003037 }
3038 }
3039 }
3040
3041 private class InternalHandler extends Handler {
3042 public InternalHandler(Looper looper) {
3043 super(looper);
3044 }
3045
3046 @Override
3047 public void handleMessage(Message msg) {
3048 NetworkInfo info;
3049 switch (msg.what) {
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003050 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003051 String causedBy = null;
3052 synchronized (ConnectivityService.this) {
3053 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3054 mNetTransitionWakeLock.isHeld()) {
3055 mNetTransitionWakeLock.release();
3056 causedBy = mNetTransitionWakeLockCausedBy;
3057 }
3058 }
3059 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003060 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003061 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003062 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003063 }
3064 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003065 FeatureUser u = (FeatureUser)msg.obj;
3066 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003067 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003068 }
3069 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003070 int netType = msg.arg1;
3071 int condition = msg.arg2;
3072 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003073 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003074 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003075 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003076 int netType = msg.arg1;
3077 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00003078 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003079 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003080 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003081 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003082 int preference = msg.arg1;
3083 handleSetNetworkPreference(preference);
3084 break;
3085 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003086 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003087 boolean enabled = (msg.arg1 == ENABLED);
3088 handleSetMobileData(enabled);
3089 break;
3090 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003091 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003092 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003093 break;
3094 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003095 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003096 boolean met = (msg.arg1 == ENABLED);
3097 handleSetDependencyMet(msg.arg2, met);
3098 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003099 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003100 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003101 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003102 sendStickyBroadcast(intent);
3103 break;
3104 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003105 case EVENT_SET_POLICY_DATA_ENABLE: {
3106 final int networkType = msg.arg1;
3107 final boolean enabled = msg.arg2 == ENABLED;
3108 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003109 break;
3110 }
3111 case EVENT_VPN_STATE_CHANGED: {
3112 if (mLockdownTracker != null) {
3113 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3114 }
3115 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003116 }
Wink Saville690cb182013-06-29 21:10:57 -07003117 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3118 int tag = mEnableFailFastMobileDataTag.get();
3119 if (msg.arg1 == tag) {
3120 MobileDataStateTracker mobileDst =
3121 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3122 if (mobileDst != null) {
3123 mobileDst.setEnableFailFastMobileData(msg.arg2);
3124 }
3125 } else {
3126 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3127 + " != tag:" + tag);
3128 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003129 break;
Wink Saville690cb182013-06-29 21:10:57 -07003130 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003131 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07003132 handleNetworkSamplingTimeout();
3133 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003134 }
Jason Monk445cea82013-10-10 14:02:51 -04003135 case EVENT_PROXY_HAS_CHANGED: {
3136 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3137 break;
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003138 }
3139 }
3140 }
3141 }
3142
3143 // javadoc from interface
3144 public int tether(String iface) {
3145 enforceTetherChangePermission();
3146
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003147 if (isTetheringSupported()) {
3148 return mTethering.tether(iface);
3149 } else {
3150 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3151 }
3152 }
3153
3154 // javadoc from interface
3155 public int untether(String iface) {
3156 enforceTetherChangePermission();
3157
3158 if (isTetheringSupported()) {
3159 return mTethering.untether(iface);
3160 } else {
3161 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3162 }
3163 }
3164
3165 // javadoc from interface
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003166 public int getLastTetherError(String iface) {
3167 enforceTetherAccessPermission();
Danica Chang96567052010-08-11 14:54:43 -07003168
3169 if (isTetheringSupported()) {
3170 return mTethering.getLastTetherError(iface);
3171 } else {
3172 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3173 }
3174 }
3175
3176 // TODO - proper iface API for selection by property, inspection, etc
Mike Lockwooded4a1742011-07-19 13:04:47 -07003177 public String[] getTetherableUsbRegexs() {
3178 enforceTetherAccessPermission();
3179 if (isTetheringSupported()) {
3180 return mTethering.getTetherableUsbRegexs();
3181 } else {
3182 return new String[0];
3183 }
3184 }
3185
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003186 public String[] getTetherableWifiRegexs() {
3187 enforceTetherAccessPermission();
3188 if (isTetheringSupported()) {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003189 return mTethering.getTetherableWifiRegexs();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003190 } else {
3191 return new String[0];
3192 }
3193 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003194
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003195 public String[] getTetherableBluetoothRegexs() {
3196 enforceTetherAccessPermission();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003197 if (isTetheringSupported()) {
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003198 return mTethering.getTetherableBluetoothRegexs();
3199 } else {
3200 return new String[0];
3201 }
3202 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003203
3204 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08003205 enforceTetherChangePermission();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003206 if (isTetheringSupported()) {
3207 return mTethering.setUsbTethering(enable);
3208 } else {
3209 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3210 }
3211 }
3212
3213 // TODO - move iface listing, queries, etc to new module
3214 // javadoc from interface
3215 public String[] getTetherableIfaces() {
3216 enforceTetherAccessPermission();
3217 return mTethering.getTetherableIfaces();
3218 }
3219
3220 public String[] getTetheredIfaces() {
3221 enforceTetherAccessPermission();
3222 return mTethering.getTetheredIfaces();
3223 }
3224
3225 public String[] getTetheringErroredIfaces() {
3226 enforceTetherAccessPermission();
3227 return mTethering.getErroredIfaces();
3228 }
3229
3230 // if ro.tether.denied = true we default to no tethering
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003231 // gservices could set the secure setting to 1 though to enable it on a build where it
3232 // had previously been turned off.
3233 public boolean isTetheringSupported() {
3234 enforceTetherAccessPermission();
3235 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003236 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3237 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003238 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3239 mTethering.getTetherableWifiRegexs().length != 0 ||
3240 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3241 mTethering.getUpstreamIfaceTypes().length != 0);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003242 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003243
3244 // An API NetworkStateTrackers can call when they lose their network.
3245 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3246 // whichever happens first. The timer is started by the first caller and not
3247 // restarted by subsequent callers.
3248 public void requestNetworkTransitionWakelock(String forWhom) {
3249 enforceConnectivityInternalPermission();
3250 synchronized (this) {
3251 if (mNetTransitionWakeLock.isHeld()) return;
3252 mNetTransitionWakeLockSerialNumber++;
3253 mNetTransitionWakeLock.acquire();
3254 mNetTransitionWakeLockCausedBy = forWhom;
3255 }
3256 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003257 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003258 mNetTransitionWakeLockSerialNumber, 0),
3259 mNetTransitionWakeLockTimeout);
3260 return;
3261 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003262
Robert Greenwalt986c7412010-09-08 15:24:47 -07003263 // 100 percent is full good, 0 is full bad.
3264 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003265 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003266 mContext.enforceCallingOrSelfPermission(
3267 android.Manifest.permission.STATUS_BAR,
3268 "ConnectivityService");
3269
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003270 if (DBG) {
3271 int pid = getCallingPid();
3272 int uid = getCallingUid();
3273 String s = pid + "(" + uid + ") reports inet is " +
3274 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3275 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3276 mInetLog.add(s);
3277 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3278 mInetLog.remove(0);
3279 }
3280 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003281 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003282 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3283 }
3284
3285 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003286 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003287 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003288 return;
3289 }
3290 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003291 if (DBG) log("handleInetConditionChange: net=" + netType +
3292 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003293 return;
3294 }
Wink Savillea7d56572011-09-21 11:05:43 -07003295 if (VDBG) {
3296 log("handleInetConditionChange: net=" +
3297 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003298 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003299 }
Wink Saville3e866722013-01-31 00:30:13 +00003300 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003301 int delay;
3302 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003303 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003304 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003305 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003306 delay = Settings.Global.getInt(mContext.getContentResolver(),
3307 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003308 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003309 delay = Settings.Global.getInt(mContext.getContentResolver(),
3310 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003311 }
3312 mInetConditionChangeInFlight = true;
3313 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003314 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003315 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003316 // we've set the new condition, when this hold ends that will get picked up
3317 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003318 }
3319 }
3320
Wink Saville3e866722013-01-31 00:30:13 +00003321 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003322 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003323 log("handleInetConditionHoldEnd: net=" + netType +
3324 ", condition=" + mDefaultInetCondition +
3325 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003326 }
3327 mInetConditionChangeInFlight = false;
3328
3329 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003330 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003331 return;
3332 }
3333 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003334 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003335 return;
3336 }
Wink Saville3e866722013-01-31 00:30:13 +00003337 // TODO: Figure out why this optimization sometimes causes a
3338 // change in mDefaultInetCondition to be missed and the
3339 // UI to not be updated.
3340 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3341 // if (DBG) log("no change in condition - aborting");
3342 // return;
3343 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003344 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3345 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003346 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003347 return;
3348 }
Wink Saville3e866722013-01-31 00:30:13 +00003349 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003350 sendInetConditionBroadcast(networkInfo);
3351 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003352 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003353
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003354 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003355 // this information is already available as a world read/writable jvm property
3356 // so this API change wouldn't have a benifit. It also breaks the passing
3357 // of proxy info to all the JVMs.
3358 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003359 synchronized (mProxyLock) {
Jason Monk43324ee2013-07-03 17:04:33 -04003360 ProxyProperties ret = mGlobalProxy;
3361 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3362 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003363 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003364 }
3365
3366 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003367 enforceConnectivityInternalPermission();
Jason Monk43324ee2013-07-03 17:04:33 -04003368
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003369 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003370 if (proxyProperties == mGlobalProxy) return;
3371 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3372 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3373
3374 String host = "";
3375 int port = 0;
3376 String exclList = "";
Jason Monk43324ee2013-07-03 17:04:33 -04003377 String pacFileUrl = "";
3378 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3379 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi6bc5eda2013-11-11 13:52:58 -08003380 if (!proxyProperties.isValid()) {
3381 if (DBG)
3382 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3383 return;
3384 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003385 mGlobalProxy = new ProxyProperties(proxyProperties);
3386 host = mGlobalProxy.getHost();
3387 port = mGlobalProxy.getPort();
3388 exclList = mGlobalProxy.getExclusionList();
Jason Monk43324ee2013-07-03 17:04:33 -04003389 if (proxyProperties.getPacFileUrl() != null) {
3390 pacFileUrl = proxyProperties.getPacFileUrl();
3391 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003392 } else {
3393 mGlobalProxy = null;
3394 }
3395 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003396 final long token = Binder.clearCallingIdentity();
3397 try {
3398 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3399 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3400 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3401 exclList);
Jason Monk43324ee2013-07-03 17:04:33 -04003402 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003403 } finally {
3404 Binder.restoreCallingIdentity(token);
3405 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003406 }
3407
3408 if (mGlobalProxy == null) {
3409 proxyProperties = mDefaultProxy;
3410 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003411 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003412 }
3413
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003414 private void loadGlobalProxy() {
3415 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003416 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3417 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3418 String exclList = Settings.Global.getString(res,
3419 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk43324ee2013-07-03 17:04:33 -04003420 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3421 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3422 ProxyProperties proxyProperties;
3423 if (!TextUtils.isEmpty(pacFileUrl)) {
3424 proxyProperties = new ProxyProperties(pacFileUrl);
3425 } else {
3426 proxyProperties = new ProxyProperties(host, port, exclList);
3427 }
Raj Mamadgi6bc5eda2013-11-11 13:52:58 -08003428 if (!proxyProperties.isValid()) {
3429 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3430 return;
3431 }
3432
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003433 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003434 mGlobalProxy = proxyProperties;
3435 }
3436 }
3437 }
3438
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003439 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003440 // this information is already available as a world read/writable jvm property
3441 // so this API change wouldn't have a benifit. It also breaks the passing
3442 // of proxy info to all the JVMs.
3443 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003444 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003445 return mGlobalProxy;
3446 }
3447 }
3448
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003449 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04003450 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3451 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003452 proxy = null;
3453 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003454 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003455 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003456 if (mDefaultProxy == proxy) return; // catches repeated nulls
Raj Mamadgi6bc5eda2013-11-11 13:52:58 -08003457 if (!proxy.isValid()) {
3458 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3459 return;
3460 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003461 mDefaultProxy = proxy;
3462
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003463 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003464 if (!mDefaultProxyDisabled) {
3465 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003466 }
3467 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003468 }
3469
3470 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003471 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3472 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003473 if (!TextUtils.isEmpty(proxy)) {
3474 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003475 if (data.length == 0) {
3476 return;
3477 }
3478
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003479 String proxyHost = data[0];
3480 int proxyPort = 8080;
3481 if (data.length > 1) {
3482 try {
3483 proxyPort = Integer.parseInt(data[1]);
3484 } catch (NumberFormatException e) {
3485 return;
3486 }
3487 }
3488 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3489 setGlobalProxy(p);
3490 }
3491 }
3492
3493 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003494 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monkaf9ded02013-08-23 19:21:25 -04003495 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003496 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003497 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003498 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3499 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003500 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003501 final long ident = Binder.clearCallingIdentity();
3502 try {
3503 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3504 } finally {
3505 Binder.restoreCallingIdentity(ident);
3506 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003507 }
3508
3509 private static class SettingsObserver extends ContentObserver {
3510 private int mWhat;
3511 private Handler mHandler;
3512 SettingsObserver(Handler handler, int what) {
3513 super(handler);
3514 mHandler = handler;
3515 mWhat = what;
3516 }
3517
3518 void observe(Context context) {
3519 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003520 resolver.registerContentObserver(Settings.Global.getUriFor(
3521 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003522 }
3523
3524 @Override
3525 public void onChange(boolean selfChange) {
3526 mHandler.obtainMessage(mWhat).sendToTarget();
3527 }
3528 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003529
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003530 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003531 Slog.d(TAG, s);
3532 }
3533
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003534 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003535 Slog.e(TAG, s);
3536 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003537
repo syncf5de5572011-07-29 23:55:49 -07003538 int convertFeatureToNetworkType(int networkType, String feature) {
3539 int usedNetworkType = networkType;
3540
3541 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3542 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3543 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3544 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3545 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3546 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3547 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3548 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3549 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3550 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3551 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3552 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3553 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3554 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3555 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3556 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3557 } else {
3558 Slog.e(TAG, "Can't match any mobile netTracker!");
3559 }
3560 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3561 if (TextUtils.equals(feature, "p2p")) {
3562 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3563 } else {
3564 Slog.e(TAG, "Can't match any wifi netTracker!");
3565 }
3566 } else {
3567 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003568 }
repo syncf5de5572011-07-29 23:55:49 -07003569 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003570 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003571
3572 private static <T> T checkNotNull(T value, String message) {
3573 if (value == null) {
3574 throw new NullPointerException(message);
3575 }
3576 return value;
3577 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003578
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003579 /**
3580 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003581 * VpnBuilder and not available in ConnectivityManager. Permissions
3582 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003583 * @hide
3584 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003585 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003586 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003587 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003588 try {
3589 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003590 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003591 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003592 synchronized(mVpns) {
3593 mVpns.get(user).protect(socket,
3594 mNetTrackers[type].getLinkProperties().getInterfaceName());
3595 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003596 return true;
3597 }
3598 } catch (Exception e) {
3599 // ignore
3600 } finally {
3601 try {
3602 socket.close();
3603 } catch (Exception e) {
3604 // ignore
3605 }
3606 }
3607 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003608 }
3609
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003610 /**
3611 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003612 * and not available in ConnectivityManager. Permissions are checked
3613 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003614 * @hide
3615 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003616 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003617 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003618 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003619 int user = UserHandle.getUserId(Binder.getCallingUid());
3620 synchronized(mVpns) {
3621 return mVpns.get(user).prepare(oldPackage, newPackage);
3622 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003623 }
3624
Chad Brubaker31de0b62013-07-11 13:29:30 -07003625 @Override
3626 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3627 enforceMarkNetworkSocketPermission();
3628 final long token = Binder.clearCallingIdentity();
3629 try {
3630 int mark = mNetd.getMarkForUid(uid);
3631 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3632 if (mark == -1) {
3633 mark = 0;
3634 }
3635 NetworkUtils.markSocket(socket.getFd(), mark);
3636 } catch (RemoteException e) {
3637 } finally {
3638 Binder.restoreCallingIdentity(token);
3639 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003640 }
3641
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003642 /**
3643 * Configure a TUN interface and return its file descriptor. Parameters
3644 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003645 * and not available in ConnectivityManager. Permissions are checked in
3646 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003647 * @hide
3648 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003649 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003650 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003651 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003652 int user = UserHandle.getUserId(Binder.getCallingUid());
3653 synchronized(mVpns) {
3654 return mVpns.get(user).establish(config);
3655 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003656 }
3657
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003658 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003659 * Start legacy VPN, controlling native daemons as needed. Creates a
3660 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003661 */
3662 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003663 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003664 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003665 final LinkProperties egress = getActiveLinkProperties();
3666 if (egress == null) {
3667 throw new IllegalStateException("Missing active network connection");
3668 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003669 int user = UserHandle.getUserId(Binder.getCallingUid());
3670 synchronized(mVpns) {
3671 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3672 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003673 }
3674
3675 /**
3676 * Return the information of the ongoing legacy VPN. This method is used
3677 * by VpnSettings and not available in ConnectivityManager. Permissions
3678 * are checked in Vpn class.
3679 * @hide
3680 */
3681 @Override
3682 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003683 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003684 int user = UserHandle.getUserId(Binder.getCallingUid());
3685 synchronized(mVpns) {
3686 return mVpns.get(user).getLegacyVpnInfo();
3687 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003688 }
3689
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003690 /**
Chad Brubaker7dcfa2a2013-07-16 18:59:12 -07003691 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3692 * not available in ConnectivityManager.
3693 * Permissions are checked in Vpn class.
3694 * @hide
3695 */
3696 @Override
3697 public VpnConfig getVpnConfig() {
3698 int user = UserHandle.getUserId(Binder.getCallingUid());
3699 synchronized(mVpns) {
3700 return mVpns.get(user).getVpnConfig();
3701 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003702 }
3703
3704 /**
3705 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3706 * through NetworkStateTracker since it works differently. For example, it
3707 * needs to override DNS servers but never takes the default routes. It
3708 * relies on another data network, and it could keep existing connections
3709 * alive after reconnecting, switching between networks, or even resuming
3710 * from deep sleep. Calls from applications should be done synchronously
3711 * to avoid race conditions. As these are all hidden APIs, refactoring can
3712 * be done whenever a better abstraction is developed.
3713 */
3714 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003715 private VpnCallback() {
3716 }
3717
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003718 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003719 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003720 }
3721
Chad Brubakerccae0d32013-06-14 11:16:51 -07003722 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003723 if (dnsServers == null) {
3724 restore();
3725 return;
3726 }
3727
3728 // Convert DNS servers into addresses.
3729 List<InetAddress> addresses = new ArrayList<InetAddress>();
3730 for (String address : dnsServers) {
3731 // Double check the addresses and remove invalid ones.
3732 try {
3733 addresses.add(InetAddress.parseNumericAddress(address));
3734 } catch (Exception e) {
3735 // ignore
3736 }
3737 }
3738 if (addresses.isEmpty()) {
3739 restore();
3740 return;
3741 }
3742
3743 // Concatenate search domains into a string.
3744 StringBuilder buffer = new StringBuilder();
3745 if (searchDomains != null) {
3746 for (String domain : searchDomains) {
3747 buffer.append(domain).append(' ');
3748 }
3749 }
3750 String domains = buffer.toString().trim();
3751
3752 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003753 synchronized (mDnsLock) {
Chad Brubaker45e721f2013-07-23 17:13:36 -07003754 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003755 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003756
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003757 // Temporarily disable the default proxy (not global).
3758 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003759 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003760 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003761 sendProxyBroadcast(null);
3762 }
3763 }
3764
3765 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003766 }
3767
Chia-chi Yehcc844502011-07-14 18:01:57 -07003768 public void restore() {
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003769 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003770 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003771 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003772 sendProxyBroadcast(mDefaultProxy);
3773 }
3774 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003775 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003776
3777 public void protect(ParcelFileDescriptor socket) {
3778 try {
3779 final int mark = mNetd.getMarkForProtect();
3780 NetworkUtils.markSocket(socket.getFd(), mark);
3781 } catch (RemoteException e) {
3782 }
3783 }
3784
3785 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3786 for (RouteInfo route : routes) {
3787 try {
3788 mNetd.setMarkedForwardingRoute(interfaze, route);
3789 } catch (RemoteException e) {
3790 }
3791 }
3792 }
3793
3794 public void setMarkedForwarding(String interfaze) {
3795 try {
3796 mNetd.setMarkedForwarding(interfaze);
3797 } catch (RemoteException e) {
3798 }
3799 }
3800
3801 public void clearMarkedForwarding(String interfaze) {
3802 try {
3803 mNetd.clearMarkedForwarding(interfaze);
3804 } catch (RemoteException e) {
3805 }
3806 }
3807
Robert Greenwalt68534c82013-09-24 11:05:57 -07003808 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003809 int uidStart = uid * UserHandle.PER_USER_RANGE;
3810 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003811 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003812 }
3813
Robert Greenwalt68534c82013-09-24 11:05:57 -07003814 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003815 int uidStart = uid * UserHandle.PER_USER_RANGE;
3816 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003817 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003818 }
3819
Robert Greenwalt68534c82013-09-24 11:05:57 -07003820 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3821 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003822 try {
3823 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003824 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003825 } catch (RemoteException e) {
3826 }
3827
3828 }
3829
Robert Greenwalt68534c82013-09-24 11:05:57 -07003830 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3831 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003832 try {
3833 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003834 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003835 } catch (RemoteException e) {
3836 }
3837
3838 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003839 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003840
3841 @Override
3842 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003843 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3844 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3845 return false;
3846 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003847
3848 // Tear down existing lockdown if profile was removed
3849 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3850 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003851 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003852 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3853 return false;
3854 }
3855
3856 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3857 final VpnProfile profile = VpnProfile.decode(
3858 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerccae0d32013-06-14 11:16:51 -07003859 int user = UserHandle.getUserId(Binder.getCallingUid());
3860 synchronized(mVpns) {
3861 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3862 profile));
3863 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003864 } else {
3865 setLockdownTracker(null);
3866 }
3867
3868 return true;
3869 }
3870
3871 /**
3872 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3873 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3874 */
3875 private void setLockdownTracker(LockdownVpnTracker tracker) {
3876 // Shutdown any existing tracker
3877 final LockdownVpnTracker existing = mLockdownTracker;
3878 mLockdownTracker = null;
3879 if (existing != null) {
3880 existing.shutdown();
3881 }
3882
3883 try {
3884 if (tracker != null) {
3885 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003886 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003887 mLockdownTracker = tracker;
3888 mLockdownTracker.init();
3889 } else {
3890 mNetd.setFirewallEnabled(false);
3891 }
3892 } catch (RemoteException e) {
3893 // ignored; NMS lives inside system_server
3894 }
3895 }
3896
3897 private void throwIfLockdownEnabled() {
3898 if (mLockdownEnabled) {
3899 throw new IllegalStateException("Unavailable in lockdown mode");
3900 }
3901 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003902
3903 public void supplyMessenger(int networkType, Messenger messenger) {
3904 enforceConnectivityInternalPermission();
3905
3906 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3907 mNetTrackers[networkType].supplyMessenger(messenger);
3908 }
3909 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003910
3911 public int findConnectionTypeForIface(String iface) {
3912 enforceConnectivityInternalPermission();
3913
3914 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3915 for (NetworkStateTracker tracker : mNetTrackers) {
3916 if (tracker != null) {
3917 LinkProperties lp = tracker.getLinkProperties();
3918 if (lp != null && iface.equals(lp.getInterfaceName())) {
3919 return tracker.getNetworkInfo().getType();
3920 }
3921 }
3922 }
3923 return ConnectivityManager.TYPE_NONE;
3924 }
Wink Saville690cb182013-06-29 21:10:57 -07003925
3926 /**
3927 * Have mobile data fail fast if enabled.
3928 *
3929 * @param enabled DctConstants.ENABLED/DISABLED
3930 */
3931 private void setEnableFailFastMobileData(int enabled) {
3932 int tag;
3933
3934 if (enabled == DctConstants.ENABLED) {
3935 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3936 } else {
3937 tag = mEnableFailFastMobileDataTag.get();
3938 }
3939 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3940 enabled));
3941 }
3942
Wink Savillebc588402013-08-16 17:17:28 -07003943 private boolean isMobileDataStateTrackerReady() {
3944 MobileDataStateTracker mdst =
Wink Saville89c87b92013-08-29 08:55:16 -07003945 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savillebc588402013-08-16 17:17:28 -07003946 return (mdst != null) && (mdst.isReady());
3947 }
3948
Wink Saville89c87b92013-08-29 08:55:16 -07003949 /**
3950 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3951 */
3952
3953 /**
3954 * No connection was possible to the network.
Wink Savillea3041492013-09-06 09:53:08 -07003955 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003956 */
Wink Savillea3041492013-09-06 09:53:08 -07003957 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville89c87b92013-08-29 08:55:16 -07003958
3959 /**
3960 * A connection was made to the internet, all is well.
Wink Savillea3041492013-09-06 09:53:08 -07003961 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003962 */
Wink Savillea3041492013-09-06 09:53:08 -07003963 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville89c87b92013-08-29 08:55:16 -07003964
3965 /**
3966 * A connection was made but no dns server was available to resolve a name to address.
Wink Savillea3041492013-09-06 09:53:08 -07003967 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003968 */
Wink Savillea3041492013-09-06 09:53:08 -07003969 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville89c87b92013-08-29 08:55:16 -07003970
3971 /**
3972 * A connection was made but could not open a TCP connection.
Wink Savillea3041492013-09-06 09:53:08 -07003973 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003974 */
Wink Savillea3041492013-09-06 09:53:08 -07003975 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3976
3977 /**
3978 * A connection was made but there was a redirection, we appear to be in walled garden.
3979 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3980 */
3981 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville89c87b92013-08-29 08:55:16 -07003982
3983 /**
3984 * The mobile network is a provisioning network.
Wink Savillea3041492013-09-06 09:53:08 -07003985 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville89c87b92013-08-29 08:55:16 -07003986 */
Wink Savillea3041492013-09-06 09:53:08 -07003987 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville89c87b92013-08-29 08:55:16 -07003988
Wink Savillea3041492013-09-06 09:53:08 -07003989 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville89c87b92013-08-29 08:55:16 -07003990
Wink Saville690cb182013-06-29 21:10:57 -07003991 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07003992 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3993 int timeOutMs = -1;
3994 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3995 enforceConnectivityInternalPermission();
Wink Savillefdb84862013-07-02 10:55:14 -07003996
Wink Saville690cb182013-06-29 21:10:57 -07003997 final long token = Binder.clearCallingIdentity();
3998 try {
Wink Saville89c87b92013-08-29 08:55:16 -07003999 timeOutMs = suggestedTimeOutMs;
4000 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4001 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4002 }
4003
4004 // Check that mobile networks are supported
4005 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4006 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4007 if (DBG) log("checkMobileProvisioning: X no mobile network");
4008 return timeOutMs;
4009 }
4010
4011 // If we're already checking don't do it again
4012 // TODO: Add a queue of results...
4013 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4014 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4015 return timeOutMs;
4016 }
4017
Wink Savillea65f4732013-10-03 08:34:46 -07004018 // Start off with mobile notification off
4019 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004020
Wink Saville690cb182013-06-29 21:10:57 -07004021 CheckMp checkMp = new CheckMp(mContext, this);
4022 CheckMp.CallBack cb = new CheckMp.CallBack() {
4023 @Override
4024 void onComplete(Integer result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004025 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004026 NetworkInfo ni =
4027 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4028 switch(result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004029 case CMP_RESULT_CODE_CONNECTABLE:
Wink Savillea3041492013-09-06 09:53:08 -07004030 case CMP_RESULT_CODE_NO_CONNECTION:
4031 case CMP_RESULT_CODE_NO_DNS:
4032 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville89c87b92013-08-29 08:55:16 -07004033 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville690cb182013-06-29 21:10:57 -07004034 break;
4035 }
Wink Saville89c87b92013-08-29 08:55:16 -07004036 case CMP_RESULT_CODE_REDIRECTED: {
4037 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004038 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004039 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004040 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004041 }
4042 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004043 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004044 setProvNotificationVisible(true,
4045 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004046 url);
Wink Saville690cb182013-06-29 21:10:57 -07004047 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004048 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004049 }
4050 break;
4051 }
Wink Savillea3041492013-09-06 09:53:08 -07004052 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004053 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004054 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004055 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004056 setProvNotificationVisible(true,
4057 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004058 url);
Wink Saville690cb182013-06-29 21:10:57 -07004059 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004060 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004061 }
4062 break;
4063 }
4064 default: {
4065 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4066 break;
4067 }
4068 }
Wink Saville89c87b92013-08-29 08:55:16 -07004069 mIsCheckingMobileProvisioning.set(false);
Wink Saville690cb182013-06-29 21:10:57 -07004070 }
4071 };
4072 CheckMp.Params params =
4073 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville89c87b92013-08-29 08:55:16 -07004074 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville690cb182013-06-29 21:10:57 -07004075 checkMp.execute(params);
4076 } finally {
4077 Binder.restoreCallingIdentity(token);
Wink Saville89c87b92013-08-29 08:55:16 -07004078 if (DBG) log("checkMobileProvisioning: X");
Wink Saville690cb182013-06-29 21:10:57 -07004079 }
4080 return timeOutMs;
4081 }
4082
4083 static class CheckMp extends
4084 AsyncTask<CheckMp.Params, Void, Integer> {
4085 private static final String CHECKMP_TAG = "CheckMp";
4086 public static final int MAX_TIMEOUT_MS = 60000;
4087 private static final int SOCKET_TIMEOUT_MS = 5000;
4088 private Context mContext;
4089 private ConnectivityService mCs;
4090 private TelephonyManager mTm;
4091 private Params mParams;
4092
4093 /**
4094 * Parameters for AsyncTask.execute
4095 */
4096 static class Params {
4097 private String mUrl;
4098 private long mTimeOutMs;
4099 private CallBack mCb;
4100
4101 Params(String url, long timeOutMs, CallBack cb) {
4102 mUrl = url;
4103 mTimeOutMs = timeOutMs;
4104 mCb = cb;
4105 }
4106
4107 @Override
4108 public String toString() {
4109 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4110 }
4111 }
4112
4113 /**
4114 * The call back object passed in Params. onComplete will be called
4115 * on the main thread.
4116 */
4117 abstract static class CallBack {
4118 // Called on the main thread.
4119 abstract void onComplete(Integer result);
4120 }
4121
4122 public CheckMp(Context context, ConnectivityService cs) {
4123 mContext = context;
4124 mCs = cs;
4125
4126 // Setup access to TelephonyService we'll be using.
4127 mTm = (TelephonyManager) mContext.getSystemService(
4128 Context.TELEPHONY_SERVICE);
4129 }
4130
4131 /**
4132 * Get the default url to use for the test.
4133 */
4134 public String getDefaultUrl() {
4135 // See http://go/clientsdns for usage approval
4136 String server = Settings.Global.getString(mContext.getContentResolver(),
4137 Settings.Global.CAPTIVE_PORTAL_SERVER);
4138 if (server == null) {
4139 server = "clients3.google.com";
4140 }
4141 return "http://" + server + "/generate_204";
4142 }
4143
4144 /**
4145 * Detect if its possible to connect to the http url. DNS based detection techniques
4146 * do not work at all hotspots. The best way to check is to perform a request to
4147 * a known address that fetches the data we expect.
4148 */
4149 private synchronized Integer isMobileOk(Params params) {
Wink Saville89c87b92013-08-29 08:55:16 -07004150 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004151 Uri orgUri = Uri.parse(params.mUrl);
4152 Random rand = new Random();
4153 mParams = params;
4154
Wink Saville37e73122013-08-13 12:41:06 -07004155 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004156 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville39856712013-09-13 12:40:11 -07004157 log("isMobileOk: X not mobile capable result=" + result);
4158 return result;
4159 }
4160
4161 // See if we've already determined we've got a provisioning connection,
4162 // if so we don't need to do anything active.
4163 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4164 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4165 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4166 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4167
4168 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4169 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4170 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4171 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4172
4173 if (isDefaultProvisioning || isHipriProvisioning) {
4174 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4175 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville37e73122013-08-13 12:41:06 -07004176 return result;
4177 }
Wink Saville690cb182013-06-29 21:10:57 -07004178
Wink Saville690cb182013-06-29 21:10:57 -07004179 try {
Wink Saville690cb182013-06-29 21:10:57 -07004180 // Continue trying to connect until time has run out
4181 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville4a165bb2013-08-07 11:02:57 -07004182
Wink Savillebc588402013-08-16 17:17:28 -07004183 if (!mCs.isMobileDataStateTrackerReady()) {
4184 // Wait for MobileDataStateTracker to be ready.
4185 if (DBG) log("isMobileOk: mdst is not ready");
4186 while(SystemClock.elapsedRealtime() < endTime) {
4187 if (mCs.isMobileDataStateTrackerReady()) {
4188 // Enable fail fast as we'll do retries here and use a
4189 // hipri connection so the default connection stays active.
4190 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4191 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4192 break;
4193 }
4194 sleep(1);
4195 }
4196 }
4197
4198 log("isMobileOk: start hipri url=" + params.mUrl);
4199
Wink Saville4a165bb2013-08-07 11:02:57 -07004200 // First wait until we can start using hipri
4201 Binder binder = new Binder();
4202 while(SystemClock.elapsedRealtime() < endTime) {
4203 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4204 Phone.FEATURE_ENABLE_HIPRI, binder);
4205 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4206 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4207 log("isMobileOk: hipri started");
4208 break;
4209 }
4210 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville89c87b92013-08-29 08:55:16 -07004211 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville4a165bb2013-08-07 11:02:57 -07004212 sleep(1);
4213 }
4214
4215 // Continue trying to connect until time has run out
Wink Saville690cb182013-06-29 21:10:57 -07004216 while(SystemClock.elapsedRealtime() < endTime) {
4217 try {
4218 // Wait for hipri to connect.
4219 // TODO: Don't poll and handle situation where hipri fails
4220 // because default is retrying. See b/9569540
4221 NetworkInfo.State state = mCs
4222 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4223 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville89c87b92013-08-29 08:55:16 -07004224 if (true/*VDBG*/) {
Wink Saville27f92732013-07-31 15:49:04 -07004225 log("isMobileOk: not connected ni=" +
Wink Saville690cb182013-06-29 21:10:57 -07004226 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville27f92732013-07-31 15:49:04 -07004227 }
Wink Saville690cb182013-06-29 21:10:57 -07004228 sleep(1);
Wink Saville89c87b92013-08-29 08:55:16 -07004229 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004230 continue;
4231 }
4232
Wink Saville89c87b92013-08-29 08:55:16 -07004233 // Hipri has started check if this is a provisioning url
4234 MobileDataStateTracker mdst = (MobileDataStateTracker)
4235 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4236 if (mdst.isProvisioningNetwork()) {
Wink Savillea3041492013-09-06 09:53:08 -07004237 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville39856712013-09-13 12:40:11 -07004238 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville89c87b92013-08-29 08:55:16 -07004239 return result;
4240 } else {
4241 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4242 }
4243
Wink Saville690cb182013-06-29 21:10:57 -07004244 // Get of the addresses associated with the url host. We need to use the
4245 // address otherwise HttpURLConnection object will use the name to get
4246 // the addresses and is will try every address but that will bypass the
4247 // route to host we setup and the connection could succeed as the default
4248 // interface might be connected to the internet via wifi or other interface.
4249 InetAddress[] addresses;
4250 try {
4251 addresses = InetAddress.getAllByName(orgUri.getHost());
4252 } catch (UnknownHostException e) {
Wink Saville89c87b92013-08-29 08:55:16 -07004253 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville39856712013-09-13 12:40:11 -07004254 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004255 return result;
4256 }
4257 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4258
4259 // Get the type of addresses supported by this link
4260 LinkProperties lp = mCs.getLinkProperties(
4261 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti662b96c2013-08-08 11:00:12 +09004262 boolean linkHasIpv4 = lp.hasIPv4Address();
4263 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville690cb182013-06-29 21:10:57 -07004264 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4265 + " linkHasIpv6=" + linkHasIpv6);
4266
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004267 final ArrayList<InetAddress> validAddresses =
4268 new ArrayList<InetAddress>(addresses.length);
Wink Saville690cb182013-06-29 21:10:57 -07004269
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004270 for (InetAddress addr : addresses) {
4271 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4272 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4273 validAddresses.add(addr);
Wink Saville690cb182013-06-29 21:10:57 -07004274 }
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004275 }
4276
4277 if (validAddresses.size() == 0) {
4278 return CMP_RESULT_CODE_NO_CONNECTION;
4279 }
4280
4281 int addrTried = 0;
4282 while (true) {
4283 // Loop through at most 3 valid addresses or until
4284 // we run out of time
4285 if (addrTried++ >= 3) {
4286 log("too many loops tried - giving up");
4287 break;
4288 }
4289 if (SystemClock.elapsedRealtime() >= endTime) {
4290 log("spend too much time - giving up");
4291 break;
4292 }
4293
4294 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4295 validAddresses.size()));
Wink Saville690cb182013-06-29 21:10:57 -07004296
4297 // Make a route to host so we check the specific interface.
4298 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4299 hostAddr.getAddress())) {
4300 // Wait a short time to be sure the route is established ??
4301 log("isMobileOk:"
4302 + " wait to establish route to hostAddr=" + hostAddr);
4303 sleep(3);
4304 } else {
4305 log("isMobileOk:"
4306 + " could not establish route to hostAddr=" + hostAddr);
4307 continue;
4308 }
4309
4310 // Rewrite the url to have numeric address to use the specific route.
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004311 // Add a pointless random query param to fool proxies into not caching.
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004312 URL newUrl = new URL(orgUri.getScheme(),
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004313 hostAddr.getHostAddress(),
4314 orgUri.getPath() + "?q=" + rand.nextInt(Integer.MAX_VALUE));
Wink Saville690cb182013-06-29 21:10:57 -07004315 log("isMobileOk: newUrl=" + newUrl);
4316
4317 HttpURLConnection urlConn = null;
4318 try {
4319 // Open the connection set the request header and get the response
4320 urlConn = (HttpURLConnection) newUrl.openConnection(
4321 java.net.Proxy.NO_PROXY);
4322 urlConn.setInstanceFollowRedirects(false);
4323 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4324 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4325 urlConn.setUseCaches(false);
4326 urlConn.setAllowUserInteraction(false);
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004327 // Set the "Connection" to "Close" as by default "Keep-Alive"
4328 // is used which is useless in this case.
Wink Saville690cb182013-06-29 21:10:57 -07004329 urlConn.setRequestProperty("Connection", "close");
4330 int responseCode = urlConn.getResponseCode();
Wink Savillea3041492013-09-06 09:53:08 -07004331
4332 // For debug display the headers
4333 Map<String, List<String>> headers = urlConn.getHeaderFields();
4334 log("isMobileOk: headers=" + headers);
4335
4336 // Close the connection
Wink Saville690cb182013-06-29 21:10:57 -07004337 urlConn.disconnect();
4338 urlConn = null;
Wink Savillea3041492013-09-06 09:53:08 -07004339
4340 if (responseCode == 204) {
4341 // Return
Wink Savillea3041492013-09-06 09:53:08 -07004342 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville39856712013-09-13 12:40:11 -07004343 log("isMobileOk: X expected responseCode=" + responseCode
4344 + " result=" + result);
Wink Savillea3041492013-09-06 09:53:08 -07004345 return result;
4346 } else {
4347 // Retry to be sure this was redirected, we've gotten
4348 // occasions where a server returned 200 even though
4349 // the device didn't have a "warm" sim.
4350 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004351 // TODO - it would be nice in the single-address case to do
4352 // another DNS resolve here, but flushing the cache is a bit
4353 // heavy-handed.
Wink Savillea3041492013-09-06 09:53:08 -07004354 result = CMP_RESULT_CODE_REDIRECTED;
4355 }
Wink Saville690cb182013-06-29 21:10:57 -07004356 } catch (Exception e) {
4357 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Savillea3041492013-09-06 09:53:08 -07004358 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004359 if (urlConn != null) {
4360 urlConn.disconnect();
4361 urlConn = null;
4362 }
4363 }
4364 }
Wink Saville39856712013-09-13 12:40:11 -07004365 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004366 return result;
4367 } catch (Exception e) {
4368 log("isMobileOk: Exception e=" + e);
4369 continue;
4370 }
4371 }
4372 log("isMobileOk: timed out");
4373 } finally {
4374 log("isMobileOk: F stop hipri");
4375 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4376 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4377 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville89c87b92013-08-29 08:55:16 -07004378
4379 // Wait for hipri to disconnect.
4380 long endTime = SystemClock.elapsedRealtime() + 5000;
4381
4382 while(SystemClock.elapsedRealtime() < endTime) {
4383 NetworkInfo.State state = mCs
4384 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4385 if (state != NetworkInfo.State.DISCONNECTED) {
4386 if (VDBG) {
4387 log("isMobileOk: connected ni=" +
4388 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4389 }
4390 sleep(1);
4391 continue;
4392 }
4393 }
4394
Wink Saville690cb182013-06-29 21:10:57 -07004395 log("isMobileOk: X result=" + result);
4396 }
4397 return result;
4398 }
4399
4400 @Override
4401 protected Integer doInBackground(Params... params) {
4402 return isMobileOk(params[0]);
4403 }
4404
4405 @Override
4406 protected void onPostExecute(Integer result) {
4407 log("onPostExecute: result=" + result);
4408 if ((mParams != null) && (mParams.mCb != null)) {
4409 mParams.mCb.onComplete(result);
4410 }
4411 }
4412
4413 private String inetAddressesToString(InetAddress[] addresses) {
4414 StringBuffer sb = new StringBuffer();
4415 boolean firstTime = true;
4416 for(InetAddress addr : addresses) {
4417 if (firstTime) {
4418 firstTime = false;
4419 } else {
4420 sb.append(",");
4421 }
4422 sb.append(addr);
4423 }
4424 return sb.toString();
4425 }
4426
4427 private void printNetworkInfo() {
4428 boolean hasIccCard = mTm.hasIccCard();
4429 int simState = mTm.getSimState();
4430 log("hasIccCard=" + hasIccCard
4431 + " simState=" + simState);
4432 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4433 if (ni != null) {
4434 log("ni.length=" + ni.length);
4435 for (NetworkInfo netInfo: ni) {
4436 log("netInfo=" + netInfo.toString());
4437 }
4438 } else {
4439 log("no network info ni=null");
4440 }
4441 }
4442
4443 /**
4444 * Sleep for a few seconds then return.
4445 * @param seconds
4446 */
4447 private static void sleep(int seconds) {
4448 try {
4449 Thread.sleep(seconds * 1000);
4450 } catch (InterruptedException e) {
4451 e.printStackTrace();
4452 }
4453 }
4454
Wink Saville690cb182013-06-29 21:10:57 -07004455 private void log(String s) {
4456 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4457 }
4458 }
4459
Wink Saville89c87b92013-08-29 08:55:16 -07004460 // TODO: Move to ConnectivityManager and make public?
4461 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4462 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville690cb182013-06-29 21:10:57 -07004463
Wink Saville89c87b92013-08-29 08:55:16 -07004464 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4465 @Override
4466 public void onReceive(Context context, Intent intent) {
4467 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4468 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4469 }
4470 }
4471 };
4472
4473 private void handleMobileProvisioningAction(String url) {
4474 // Notication mark notification as not visible
Wink Savillea65f4732013-10-03 08:34:46 -07004475 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004476
4477 // If provisioning network handle as a special case,
4478 // otherwise launch browser with the intent directly.
4479 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville860f5282013-09-05 12:02:25 -07004480 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07004481 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4482 MobileDataStateTracker mdst = (MobileDataStateTracker)
4483 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4484 mdst.enableMobileProvisioning(url);
4485 } else {
4486 if (DBG) log("handleMobileProvisioningAction: on default network");
4487 Intent newIntent =
4488 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4489 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4490 Intent.FLAG_ACTIVITY_NEW_TASK);
4491 try {
4492 mContext.startActivity(newIntent);
4493 } catch (ActivityNotFoundException e) {
4494 loge("handleMobileProvisioningAction: startActivity failed" + e);
4495 }
4496 }
4497 }
4498
4499 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4500 private volatile boolean mIsNotificationVisible = false;
4501
4502 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4503 String url) {
4504 if (DBG) {
4505 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4506 + " extraInfo=" + extraInfo + " url=" + url);
4507 }
Wink Saville690cb182013-06-29 21:10:57 -07004508
4509 Resources r = Resources.getSystem();
4510 NotificationManager notificationManager = (NotificationManager) mContext
4511 .getSystemService(Context.NOTIFICATION_SERVICE);
4512
4513 if (visible) {
4514 CharSequence title;
4515 CharSequence details;
4516 int icon;
Wink Saville89c87b92013-08-29 08:55:16 -07004517 Intent intent;
4518 Notification notification = new Notification();
4519 switch (networkType) {
Wink Saville690cb182013-06-29 21:10:57 -07004520 case ConnectivityManager.TYPE_WIFI:
Wink Saville690cb182013-06-29 21:10:57 -07004521 title = r.getString(R.string.wifi_available_sign_in, 0);
4522 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004523 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004524 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004525 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4526 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4527 Intent.FLAG_ACTIVITY_NEW_TASK);
4528 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004529 break;
4530 case ConnectivityManager.TYPE_MOBILE:
4531 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville690cb182013-06-29 21:10:57 -07004532 title = r.getString(R.string.network_available_sign_in, 0);
4533 // TODO: Change this to pull from NetworkInfo once a printable
4534 // name has been added to it
4535 details = mTelephonyManager.getNetworkOperatorName();
4536 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004537 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4538 intent.putExtra("EXTRA_URL", url);
4539 intent.setFlags(0);
4540 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004541 break;
4542 default:
Wink Saville690cb182013-06-29 21:10:57 -07004543 title = r.getString(R.string.network_available_sign_in, 0);
4544 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004545 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004546 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004547 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4548 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4549 Intent.FLAG_ACTIVITY_NEW_TASK);
4550 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004551 break;
4552 }
4553
Wink Saville690cb182013-06-29 21:10:57 -07004554 notification.when = 0;
4555 notification.icon = icon;
4556 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville690cb182013-06-29 21:10:57 -07004557 notification.tickerText = title;
4558 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4559
Wink Saville89c87b92013-08-29 08:55:16 -07004560 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004561 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville89c87b92013-08-29 08:55:16 -07004562 } catch (NullPointerException npe) {
4563 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4564 npe.printStackTrace();
4565 }
Wink Saville690cb182013-06-29 21:10:57 -07004566 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004567 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004568 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville89c87b92013-08-29 08:55:16 -07004569 } catch (NullPointerException npe) {
4570 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4571 npe.printStackTrace();
4572 }
Wink Saville690cb182013-06-29 21:10:57 -07004573 }
Wink Saville89c87b92013-08-29 08:55:16 -07004574 mIsNotificationVisible = visible;
Wink Saville690cb182013-06-29 21:10:57 -07004575 }
4576
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004577 /** Location to an updatable file listing carrier provisioning urls.
4578 * An example:
4579 *
4580 * <?xml version="1.0" encoding="utf-8"?>
4581 * <provisioningUrls>
4582 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4583 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4584 * </provisioningUrls>
4585 */
4586 private static final String PROVISIONING_URL_PATH =
4587 "/data/misc/radio/provisioning_urls.xml";
4588 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004589
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004590 /** XML tag for root element. */
4591 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4592 /** XML tag for individual url */
4593 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4594 /** XML tag for redirected url */
4595 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4596 /** XML attribute for mcc */
4597 private static final String ATTR_MCC = "mcc";
4598 /** XML attribute for mnc */
4599 private static final String ATTR_MNC = "mnc";
4600
4601 private static final int REDIRECTED_PROVISIONING = 1;
4602 private static final int PROVISIONING = 2;
4603
4604 private String getProvisioningUrlBaseFromFile(int type) {
4605 FileReader fileReader = null;
4606 XmlPullParser parser = null;
4607 Configuration config = mContext.getResources().getConfiguration();
4608 String tagType;
4609
4610 switch (type) {
4611 case PROVISIONING:
4612 tagType = TAG_PROVISIONING_URL;
4613 break;
4614 case REDIRECTED_PROVISIONING:
4615 tagType = TAG_REDIRECTED_URL;
4616 break;
4617 default:
4618 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4619 type);
4620 }
4621
4622 try {
4623 fileReader = new FileReader(mProvisioningUrlFile);
4624 parser = Xml.newPullParser();
4625 parser.setInput(fileReader);
4626 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4627
4628 while (true) {
4629 XmlUtils.nextElement(parser);
4630
4631 String element = parser.getName();
4632 if (element == null) break;
4633
4634 if (element.equals(tagType)) {
4635 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4636 try {
4637 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4638 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4639 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4640 parser.next();
4641 if (parser.getEventType() == XmlPullParser.TEXT) {
4642 return parser.getText();
4643 }
4644 }
4645 }
4646 } catch (NumberFormatException e) {
4647 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4648 }
4649 }
4650 }
4651 return null;
4652 } catch (FileNotFoundException e) {
4653 loge("Carrier Provisioning Urls file not found");
4654 } catch (XmlPullParserException e) {
4655 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4656 } catch (IOException e) {
4657 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4658 } finally {
4659 if (fileReader != null) {
4660 try {
4661 fileReader.close();
4662 } catch (IOException e) {}
4663 }
4664 }
4665 return null;
4666 }
4667
Wink Savillef714b7f2013-07-20 20:31:59 -07004668 @Override
4669 public String getMobileRedirectedProvisioningUrl() {
4670 enforceConnectivityInternalPermission();
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004671 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4672 if (TextUtils.isEmpty(url)) {
4673 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4674 }
4675 return url;
4676 }
4677
Wink Savillef714b7f2013-07-20 20:31:59 -07004678 @Override
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004679 public String getMobileProvisioningUrl() {
4680 enforceConnectivityInternalPermission();
4681 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4682 if (TextUtils.isEmpty(url)) {
4683 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillef714b7f2013-07-20 20:31:59 -07004684 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004685 } else {
Wink Savillef714b7f2013-07-20 20:31:59 -07004686 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004687 }
Wink Savilledfabd992013-07-10 23:00:07 -07004688 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004689 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004690 String phoneNumber = mTelephonyManager.getLine1Number();
4691 if (TextUtils.isEmpty(phoneNumber)) {
4692 phoneNumber = "0000000000";
4693 }
Wink Saville690cb182013-06-29 21:10:57 -07004694 url = String.format(url,
4695 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4696 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004697 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004698 }
4699
Wink Saville690cb182013-06-29 21:10:57 -07004700 return url;
4701 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004702
Wink Saville89c87b92013-08-29 08:55:16 -07004703 @Override
4704 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4705 String extraInfo, String url) {
4706 enforceConnectivityInternalPermission();
4707 setProvNotificationVisible(visible, networkType, extraInfo, url);
4708 }
Wink Saville3ade4872013-08-29 14:57:08 -07004709
Yuhao Zheng15019892013-09-09 17:00:04 -07004710 @Override
4711 public void setAirplaneMode(boolean enable) {
4712 enforceConnectivityInternalPermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07004713 final long ident = Binder.clearCallingIdentity();
4714 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07004715 final ContentResolver cr = mContext.getContentResolver();
4716 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4717 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4718 intent.putExtra("state", enable);
Yuhao Zheng15019892013-09-09 17:00:04 -07004719 mContext.sendBroadcast(intent);
4720 } finally {
4721 Binder.restoreCallingIdentity(ident);
4722 }
4723 }
4724
Chad Brubakerccae0d32013-06-14 11:16:51 -07004725 private void onUserStart(int userId) {
4726 synchronized(mVpns) {
4727 Vpn userVpn = mVpns.get(userId);
4728 if (userVpn != null) {
4729 loge("Starting user already has a VPN");
4730 return;
4731 }
4732 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4733 mVpns.put(userId, userVpn);
4734 userVpn.startMonitoring(mContext, mTrackerHandler);
4735 }
4736 }
4737
4738 private void onUserStop(int userId) {
4739 synchronized(mVpns) {
4740 Vpn userVpn = mVpns.get(userId);
4741 if (userVpn == null) {
4742 loge("Stopping user has no VPN");
4743 return;
4744 }
4745 mVpns.delete(userId);
4746 }
4747 }
4748
4749 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4750 @Override
4751 public void onReceive(Context context, Intent intent) {
4752 final String action = intent.getAction();
4753 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4754 if (userId == UserHandle.USER_NULL) return;
4755
4756 if (Intent.ACTION_USER_STARTING.equals(action)) {
4757 onUserStart(userId);
4758 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4759 onUserStop(userId);
4760 }
4761 }
4762 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004763
4764 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004765 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004766 enforceAccessPermission();
4767 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004768 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004769 } else {
4770 return null;
4771 }
4772 }
4773
4774 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004775 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004776 enforceAccessPermission();
4777 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004778 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004779 } else {
4780 return null;
4781 }
4782 }
4783
4784 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004785 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004786 enforceAccessPermission();
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004787 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004788 for (NetworkStateTracker tracker : mNetTrackers) {
4789 if (tracker != null) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004790 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004791 if (li != null) {
4792 result.add(li);
4793 }
4794 }
4795 }
4796
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004797 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004798 }
4799
4800 /* Infrastructure for network sampling */
4801
4802 private void handleNetworkSamplingTimeout() {
4803
4804 log("Sampling interval elapsed, updating statistics ..");
4805
4806 // initialize list of interfaces ..
4807 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4808 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4809 for (NetworkStateTracker tracker : mNetTrackers) {
4810 if (tracker != null) {
4811 String ifaceName = tracker.getNetworkInterfaceName();
4812 if (ifaceName != null) {
4813 mapIfaceToSample.put(ifaceName, null);
4814 }
4815 }
4816 }
4817
4818 // Read samples for all interfaces
4819 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4820
4821 // process samples for all networks
4822 for (NetworkStateTracker tracker : mNetTrackers) {
4823 if (tracker != null) {
4824 String ifaceName = tracker.getNetworkInterfaceName();
4825 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4826 if (ss != null) {
4827 // end the previous sampling cycle
4828 tracker.stopSampling(ss);
4829 // start a new sampling cycle ..
4830 tracker.startSampling(ss);
4831 }
4832 }
4833 }
4834
4835 log("Done.");
4836
4837 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4838 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4839 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4840
4841 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4842
4843 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4844 }
4845
4846 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4847 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4848 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4849 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004850}