blob: d42ae3a945dbceb32b111049e350388fd12b1f02 [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;
Wink Saville8fe05f12013-10-31 06:35:22 -070080import android.os.Build;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040081import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070083import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070084import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070085import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080086import android.os.Looper;
87import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070088import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070089import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070090import android.os.PowerManager;
Jeff Sharkey5663b6e2012-09-06 17:54:29 -070091import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070092import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070094import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095import android.os.SystemProperties;
Dianne Hackbornbc55bd12012-08-29 18:32:08 -070096import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080097import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070098import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -070099import android.security.KeyStore;
Wink Saville690cb182013-06-29 21:10:57 -0700100import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700101import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubakerccae0d32013-06-14 11:16:51 -0700103import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700104import android.util.SparseIntArray;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700105import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106
Wink Saville690cb182013-06-29 21:10:57 -0700107import com.android.internal.R;
Jason Monk43324ee2013-07-03 17:04:33 -0400108import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700110import com.android.internal.net.VpnConfig;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700111import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-06-29 21:10:57 -0700112import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700113import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700114import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700115import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700116import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700117import com.android.server.am.BatteryStatsService;
John Spurlock4ba7e412013-06-24 14:20:23 -0400118import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900119import com.android.server.connectivity.Nat464Xlat;
Jason Monk43324ee2013-07-03 17:04:33 -0400120import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800121import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700122import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700123import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700124import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700125import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700126import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700127
tk.mun093f55c2011-10-13 22:51:57 +0900128import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700129
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700130import org.xmlpull.v1.XmlPullParser;
131import org.xmlpull.v1.XmlPullParserException;
132
133import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134import java.io.FileDescriptor;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700135import java.io.FileNotFoundException;
136import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700137import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800138import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900139import java.lang.reflect.Constructor;
Wink Saville690cb182013-06-29 21:10:57 -0700140import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700141import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700142import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700143import java.net.InetAddress;
Wink Saville690cb182013-06-29 21:10:57 -0700144import java.net.URL;
Wink Saville8fe05f12013-10-31 06:35:22 -0700145import java.net.URLConnection;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700146import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700147import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700148import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700149import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700150import java.util.GregorianCalendar;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700152import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153import java.util.List;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700154import java.util.Map;
Wink Saville690cb182013-06-29 21:10:57 -0700155import java.util.Random;
Wink Saville89c87b92013-08-29 08:55:16 -0700156import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville690cb182013-06-29 21:10:57 -0700157import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158
Wink Saville8fe05f12013-10-31 06:35:22 -0700159import javax.net.ssl.HostnameVerifier;
160import javax.net.ssl.HttpsURLConnection;
161import javax.net.ssl.SSLSession;
162
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163/**
164 * @hide
165 */
166public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700167 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800168
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700169 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700170 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800171
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700172 private static final boolean LOGD_RULES = false;
173
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700174 // TODO: create better separation between radio types and network types
175
Robert Greenwalt2034b912009-08-12 16:08:25 -0700176 // how long to wait before switching back to a radio's default network
177 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
178 // system property that can override the above value
179 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
180 "android.telephony.apn-restore";
181
Wink Saville690cb182013-06-29 21:10:57 -0700182 // Default value if FAIL_FAST_TIME_MS is not set
183 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
184 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
185 private static final String FAIL_FAST_TIME_MS =
186 "persist.radio.fail_fast_time_ms";
187
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700188 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
189 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
190
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700191 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700192
193 private PendingIntent mSampleIntervalElapsedIntent;
194
195 // Set network sampling interval at 12 minutes, this way, even if the timers get
196 // aggregated, it will fire at around 15 minutes, which should allow us to
197 // aggregate this timer with other timers (specially the socket keep alive timers)
198 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
199
200 // start network sampling a minute after booting ...
201 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
202
203 AlarmManager mAlarmManager;
204
Robert Greenwaltbd492212011-05-06 17:10:53 -0700205 // used in recursive route setting to add gateways for the host for which
206 // a host route was requested.
207 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
208
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800209 private Tethering mTethering;
210
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700211 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700212
Chad Brubakerccae0d32013-06-14 11:16:51 -0700213 @GuardedBy("mVpns")
214 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700215 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700216
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700217 private boolean mLockdownEnabled;
218 private LockdownVpnTracker mLockdownTracker;
219
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900220 private Nat464Xlat mClat;
221
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700222 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
223 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700224 /** Currently active network rules by UID. */
225 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700226 /** Set of ifaces that are costly. */
227 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700228
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 /**
230 * Sometimes we want to refer to the individual network state
231 * trackers separately, and sometimes we just want to treat them
232 * abstractly.
233 */
234 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235
Irfan Sheriffba8388b2012-08-16 12:49:23 -0700236 /* Handles captive portal check on a network */
237 private CaptivePortalTracker mCaptivePortalTracker;
238
Robert Greenwalt2034b912009-08-12 16:08:25 -0700239 /**
Wink Saville051a6642011-07-13 13:44:13 -0700240 * The link properties that define the current links
241 */
242 private LinkProperties mCurrentLinkProperties[];
243
244 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245 * A per Net list of the PID's that requested access to the net
246 * used both as a refcount and for per-PID DNS selection
247 */
Mattias Falkdc919012011-08-23 14:15:13 +0200248 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700249
Robert Greenwalt2034b912009-08-12 16:08:25 -0700250 // priority order of the nettrackers
251 // (excluding dynamically set mNetworkPreference)
252 // TODO - move mNetworkTypePreference into this
253 private int[] mPriorityList;
254
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 private Context mContext;
256 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700257 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700258 // 0 is full bad, 100 is full good
Wink Saville3e866722013-01-31 00:30:13 +0000259 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700260 private int mDefaultInetConditionPublished = 0;
261 private boolean mInetConditionChangeInFlight = false;
262 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800263
Chia-chi Yehcc844502011-07-14 18:01:57 -0700264 private Object mDnsLock = new Object();
Robert Greenwaltd44340d2013-02-11 15:25:10 -0800265 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266
267 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700268 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800269
Robert Greenwalt355205c2011-05-10 15:05:02 -0700270 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700271 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700272
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700273 private static final int ENABLED = 1;
274 private static final int DISABLED = 0;
275
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700276 private static final boolean ADD = true;
277 private static final boolean REMOVE = false;
278
279 private static final boolean TO_DEFAULT_TABLE = true;
280 private static final boolean TO_SECONDARY_TABLE = false;
281
Chad Brubaker78850f32013-07-15 16:34:04 -0700282 private static final boolean EXEMPT = true;
283 private static final boolean UNEXEMPT = false;
284
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700285 /**
286 * used internally as a delayed event to make us switch back to the
287 * default network
288 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700289 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700290
291 /**
292 * used internally to change our mobile data enabled flag
293 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700294 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700295
296 /**
297 * used internally to change our network preference setting
298 * arg1 = networkType to prefer
299 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700300 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700301
302 /**
303 * used internally to synchronize inet condition reports
304 * arg1 = networkType
305 * arg2 = condition (0 bad, 100 good)
306 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700307 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700308
309 /**
310 * used internally to mark the end of inet condition hold periods
311 * arg1 = networkType
312 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700313 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700314
315 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700316 * used internally to set enable/disable cellular data
317 * arg1 = ENBALED or DISABLED
318 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700319 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700320
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700321 /**
322 * used internally to clear a wakelock when transitioning
323 * from one net to another
324 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700325 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700326
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700327 /**
328 * used internally to reload global proxy settings
329 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700330 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700331
Robert Greenwalt34848c02011-03-25 13:09:25 -0700332 /**
333 * used internally to set external dependency met/unmet
334 * arg1 = ENABLED (met) or DISABLED (unmet)
335 * arg2 = NetworkType
336 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700337 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700338
Chia-chi Yehcc844502011-07-14 18:01:57 -0700339 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700340 * used internally to send a sticky broadcast delayed.
341 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700342 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700343
Jeff Sharkey805662d2011-08-19 02:24:24 -0700344 /**
345 * Used internally to
346 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
347 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700348 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700349
Chad Brubakera8e81122013-07-23 17:44:41 -0700350 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700351
Wink Saville690cb182013-06-29 21:10:57 -0700352 /**
353 * Used internally to disable fail fast of mobile data
354 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700355 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville690cb182013-06-29 21:10:57 -0700356
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700357 /**
358 * user internally to indicate that data sampling interval is up
359 */
360 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
361
Jason Monk445cea82013-10-10 14:02:51 -0400362 /**
363 * PAC manager has received new port.
364 */
365 private static final int EVENT_PROXY_HAS_CHANGED = 16;
366
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700367 /** Handler used for internal events. */
368 private InternalHandler mHandler;
369 /** Handler used for incoming {@link NetworkStateTracker} events. */
370 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700371
372 // list of DeathRecipients used to make sure features are turned off when
373 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500374 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700375
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400376 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800377 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400378
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700379 private PowerManager.WakeLock mNetTransitionWakeLock;
380 private String mNetTransitionWakeLockCausedBy = "";
381 private int mNetTransitionWakeLockSerialNumber;
382 private int mNetTransitionWakeLockTimeout;
383
Robert Greenwalt94daa182010-09-01 11:34:05 -0700384 private InetAddress mDefaultDns;
385
Chad Brubaker78850f32013-07-15 16:34:04 -0700386 // Lock for protecting access to mAddedRoutes and mExemptAddresses
387 private final Object mRoutesLock = new Object();
388
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700389 // this collection is used to refcount the added routes - if there are none left
390 // it's time to remove the route from the route table
Chad Brubaker78850f32013-07-15 16:34:04 -0700391 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700392 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
393
Chad Brubaker78850f32013-07-15 16:34:04 -0700394 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
395 // used to handle cleanup of exempt rules
396 @GuardedBy("mRoutesLock")
397 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
398
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700399 // used in DBG mode to track inet condition reports
400 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
401 private ArrayList mInetLog;
402
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700403 // track the current default http proxy - tell the world if we get a new one (real change)
404 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltda77cb12013-04-05 17:14:19 -0700405 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700406 private boolean mDefaultProxyDisabled = false;
407
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700408 // track the global proxy.
409 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700410
Jason Monk43324ee2013-07-03 17:04:33 -0400411 private PacManager mPacManager = null;
412
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700413 private SettingsObserver mSettingsObserver;
414
Robert Greenwalt34848c02011-03-25 13:09:25 -0700415 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700416 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700417
Robert Greenwalt12c44552009-12-07 11:33:18 -0800418 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700419 public int mSimultaneity;
420 public int mType;
421 public RadioAttributes(String init) {
422 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700423 mType = Integer.parseInt(fragments[0]);
424 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700425 }
426 }
427 RadioAttributes[] mRadioAttributes;
428
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700429 // the set of network types that can only be enabled by system/sig apps
430 List mProtectedNetworks;
431
John Spurlock4ba7e412013-06-24 14:20:23 -0400432 private DataConnectionStats mDataConnectionStats;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700433
Wink Saville690cb182013-06-29 21:10:57 -0700434 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
435
436 TelephonyManager mTelephonyManager;
John Spurlock4ba7e412013-06-24 14:20:23 -0400437
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700438 public ConnectivityService(Context context, INetworkManagementService netd,
439 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700440 // Currently, omitting a NetworkFactory will create one internally
441 // TODO: create here when we have cleaner WiMAX support
442 this(context, netd, statsService, policyManager, null);
443 }
444
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700445 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700446 INetworkStatsService statsService, INetworkPolicyManager policyManager,
447 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800448 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800449
Wink Saville775aad62010-09-02 19:23:52 -0700450 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
451 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700452 mHandler = new InternalHandler(handlerThread.getLooper());
453 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700454
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700455 if (netFactory == null) {
456 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
457 }
458
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800459 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800460 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
461 String id = Settings.Secure.getString(context.getContentResolver(),
462 Settings.Secure.ANDROID_ID);
463 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700464 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800465 SystemProperties.set("net.hostname", name);
466 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800467 }
468
Robert Greenwalt94daa182010-09-01 11:34:05 -0700469 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700470 String dns = Settings.Global.getString(context.getContentResolver(),
471 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700472 if (dns == null || dns.length() == 0) {
473 dns = context.getResources().getString(
474 com.android.internal.R.string.config_default_dns_server);
475 }
476 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800477 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
478 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800479 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700480 }
481
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700482 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700483 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700484 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700485 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700486 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700487
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700488 try {
489 mPolicyManager.registerListener(mPolicyListener);
490 } catch (RemoteException e) {
491 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700492 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700493 }
494
495 final PowerManager powerManager = (PowerManager) context.getSystemService(
496 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700497 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
498 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
499 com.android.internal.R.integer.config_networkTransitionTimeout);
500
Robert Greenwalt2034b912009-08-12 16:08:25 -0700501 mNetTrackers = new NetworkStateTracker[
502 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700503 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700504
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700506 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700507
Robert Greenwalt2034b912009-08-12 16:08:25 -0700508 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700509 String[] raStrings = context.getResources().getStringArray(
510 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 for (String raString : raStrings) {
512 RadioAttributes r = new RadioAttributes(raString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700513 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700514 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800515 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700516 continue;
517 }
518 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800519 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700520 r.mType);
521 continue;
522 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700523 mRadioAttributes[r.mType] = r;
524 }
525
Wink Saville23ee8db2013-04-23 14:26:51 -0700526 // TODO: What is the "correct" way to do determine if this is a wifi only device?
527 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
528 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700529 String[] naStrings = context.getResources().getStringArray(
530 com.android.internal.R.array.networkAttributes);
531 for (String naString : naStrings) {
532 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700533 NetworkConfig n = new NetworkConfig(naString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700534 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700535 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800536 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700537 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700538 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700539 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700540 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
541 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
542 n.type);
543 continue;
544 }
Wink Savillef2a62832011-04-07 14:23:45 -0700545 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800546 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700547 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700548 continue;
549 }
Wink Savillef2a62832011-04-07 14:23:45 -0700550 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800551 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700552 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700553 continue;
554 }
Wink Savillef2a62832011-04-07 14:23:45 -0700555 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700556 mNetworksDefined++;
557 } catch(Exception e) {
558 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 }
560 }
Wink Saville70dbdcc2013-07-29 15:00:57 -0700561 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700563 mProtectedNetworks = new ArrayList<Integer>();
564 int[] protectedNetworks = context.getResources().getIntArray(
565 com.android.internal.R.array.config_protectedNetworks);
566 for (int p : protectedNetworks) {
567 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
568 mProtectedNetworks.add(p);
569 } else {
570 if (DBG) loge("Ignoring protectedNetwork " + p);
571 }
572 }
573
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700574 // high priority first
575 mPriorityList = new int[mNetworksDefined];
576 {
577 int insertionPoint = mNetworksDefined-1;
578 int currentLowest = 0;
579 int nextLowest = 0;
580 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700581 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700582 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700583 if (na.priority < currentLowest) continue;
584 if (na.priority > currentLowest) {
585 if (na.priority < nextLowest || nextLowest == 0) {
586 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700587 }
588 continue;
589 }
Wink Savillef2a62832011-04-07 14:23:45 -0700590 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700591 }
592 currentLowest = nextLowest;
593 nextLowest = 0;
594 }
595 }
596
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800597 // Update mNetworkPreference according to user mannually first then overlay config.xml
598 mNetworkPreference = getPersistedNetworkPreference();
599 if (mNetworkPreference == -1) {
600 for (int n : mPriorityList) {
601 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
602 mNetworkPreference = n;
603 break;
604 }
605 }
606 if (mNetworkPreference == -1) {
607 throw new IllegalStateException(
608 "You should set at least one default Network in config.xml!");
609 }
610 }
611
Mattias Falkdc919012011-08-23 14:15:13 +0200612 mNetRequestersPids =
613 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700614 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200615 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700616 }
617
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500618 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700619
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700620 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
621 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700622
623 // Create and start trackers for hard-coded networks
624 for (int targetNetworkType : mPriorityList) {
625 final NetworkConfig config = mNetConfigs[targetNetworkType];
626 final NetworkStateTracker tracker;
627 try {
628 tracker = netFactory.createTracker(targetNetworkType, config);
629 mNetTrackers[targetNetworkType] = tracker;
630 } catch (IllegalArgumentException e) {
631 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
632 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700633 continue;
634 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700635
636 tracker.startMonitoring(context, mTrackerHandler);
637 if (config.isDefault()) {
638 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800639 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700640 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800641
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700642 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800643
Robert Greenwalt00eb17f2013-07-19 14:30:49 -0700644 //set up the listener for user state for creating user VPNs
Chad Brubakerccae0d32013-06-14 11:16:51 -0700645 IntentFilter intentFilter = new IntentFilter();
646 intentFilter.addAction(Intent.ACTION_USER_STARTING);
647 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
648 mContext.registerReceiverAsUser(
649 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900650 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
651
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700652 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700653 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700654 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900655 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700656 } catch (RemoteException e) {
657 loge("Error registering observer :" + e);
658 }
659
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700660 if (DBG) {
661 mInetLog = new ArrayList();
662 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700663
664 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
665 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800666
John Spurlock4ba7e412013-06-24 14:20:23 -0400667 mDataConnectionStats = new DataConnectionStats(mContext);
668 mDataConnectionStats.startMonitoring();
Jason Monk43324ee2013-07-03 17:04:33 -0400669
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700670 // start network sampling ..
671 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
672 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700673 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700674
675 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
676 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
677
678 IntentFilter filter = new IntentFilter();
679 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
680 mContext.registerReceiver(
681 new BroadcastReceiver() {
682 @Override
683 public void onReceive(Context context, Intent intent) {
684 String action = intent.getAction();
685 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
686 mHandler.sendMessage(mHandler.obtainMessage
687 (EVENT_SAMPLE_INTERVAL_ELAPSED));
688 }
689 }
690 },
691 new IntentFilter(filter));
692
Jason Monk445cea82013-10-10 14:02:51 -0400693 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville3ade4872013-08-29 14:57:08 -0700694
695 filter = new IntentFilter();
Wink Saville89c87b92013-08-29 08:55:16 -0700696 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
697 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800698 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700699
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700700 /**
701 * Factory that creates {@link NetworkStateTracker} instances using given
702 * {@link NetworkConfig}.
703 */
704 public interface NetworkFactory {
705 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
706 }
707
708 private static class DefaultNetworkFactory implements NetworkFactory {
709 private final Context mContext;
710 private final Handler mTrackerHandler;
711
712 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
713 mContext = context;
714 mTrackerHandler = trackerHandler;
715 }
716
717 @Override
718 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
719 switch (config.radio) {
720 case TYPE_WIFI:
721 return new WifiStateTracker(targetNetworkType, config.name);
722 case TYPE_MOBILE:
723 return new MobileDataStateTracker(targetNetworkType, config.name);
724 case TYPE_DUMMY:
725 return new DummyDataStateTracker(targetNetworkType, config.name);
726 case TYPE_BLUETOOTH:
727 return BluetoothTetheringDataTracker.getInstance();
728 case TYPE_WIMAX:
729 return makeWimaxStateTracker(mContext, mTrackerHandler);
730 case TYPE_ETHERNET:
731 return EthernetDataTracker.getInstance();
732 default:
733 throw new IllegalArgumentException(
734 "Trying to create a NetworkStateTracker for an unknown radio type: "
735 + config.radio);
736 }
737 }
738 }
739
740 /**
741 * Loads external WiMAX library and registers as system service, returning a
742 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
743 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
744 */
745 private static NetworkStateTracker makeWimaxStateTracker(
746 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700747 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900748 DexClassLoader wimaxClassLoader;
749 Class wimaxStateTrackerClass = null;
750 Class wimaxServiceClass = null;
751 Class wimaxManagerClass;
752 String wimaxJarLocation;
753 String wimaxLibLocation;
754 String wimaxManagerClassName;
755 String wimaxServiceClassName;
756 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800757
tk.mun093f55c2011-10-13 22:51:57 +0900758 NetworkStateTracker wimaxStateTracker = null;
759
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700760 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900761 com.android.internal.R.bool.config_wimaxEnabled);
762
763 if (isWimaxEnabled) {
764 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700765 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900766 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700767 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900768 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700769 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900770 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700771 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900772 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700773 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900774 com.android.internal.R.string.config_wimaxStateTrackerClassname);
775
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800776 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900777 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700778 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900779 wimaxLibLocation, ClassLoader.getSystemClassLoader());
780
781 try {
782 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
783 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
784 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
785 } catch (ClassNotFoundException ex) {
786 loge("Exception finding Wimax classes: " + ex.toString());
787 return null;
788 }
789 } catch(Resources.NotFoundException ex) {
790 loge("Wimax Resources does not exist!!! ");
791 return null;
792 }
793
794 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800795 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900796
797 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
798 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700799 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
800 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900801
802 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
803 (new Class[] {Context.class, wimaxStateTrackerClass});
804 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700805 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900806 wmxSrvConst.setAccessible(false);
807
808 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
809
810 } catch(Exception ex) {
811 loge("Exception creating Wimax classes: " + ex.toString());
812 return null;
813 }
814 } else {
815 loge("Wimax is not enabled or not added to the network attributes!!! ");
816 return null;
817 }
818
819 return wimaxStateTracker;
820 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700821
The Android Open Source Project28527d22009-03-03 19:31:44 -0800822 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700823 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800824 * @param preference the new preference
825 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700826 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800827 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700828
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700829 mHandler.sendMessage(
830 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800831 }
832
833 public int getNetworkPreference() {
834 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700835 int preference;
836 synchronized(this) {
837 preference = mNetworkPreference;
838 }
839 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800840 }
841
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700842 private void handleSetNetworkPreference(int preference) {
843 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700844 mNetConfigs[preference] != null &&
845 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700846 if (mNetworkPreference != preference) {
847 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700848 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700849 synchronized(this) {
850 mNetworkPreference = preference;
851 }
852 enforcePreference();
853 }
854 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800855 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700856
Wink Saville4f0de1e2011-08-04 15:01:58 -0700857 private int getConnectivityChangeDelay() {
858 final ContentResolver cr = mContext.getContentResolver();
859
860 /** Check system properties for the default value then use secure settings value, if any. */
861 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700862 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
863 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
864 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700865 defaultDelay);
866 }
867
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868 private int getPersistedNetworkPreference() {
869 final ContentResolver cr = mContext.getContentResolver();
870
Jeff Brown87272712012-09-25 15:03:20 -0700871 final int networkPrefSetting = Settings.Global
872 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800873
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800874 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800875 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700876
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700878 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800879 * In this method, we only tear down a non-preferred network. Establishing
880 * a connection to the preferred network is taken care of when we handle
881 * the disconnect event from the non-preferred network
882 * (see {@link #handleDisconnect(NetworkInfo)}).
883 */
884 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700885 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800886 return;
887
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888 if (!mNetTrackers[mNetworkPreference].isAvailable())
889 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800890
Robert Greenwalt2034b912009-08-12 16:08:25 -0700891 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700892 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700893 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700894 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800895 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700896 " in enforcePreference");
897 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700898 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800899 }
900 }
901 }
902
903 private boolean teardown(NetworkStateTracker netTracker) {
904 if (netTracker.teardown()) {
905 netTracker.setTeardownRequested(true);
906 return true;
907 } else {
908 return false;
909 }
910 }
911
912 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700913 * Check if UID should be blocked from using the network represented by the
914 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700915 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700916 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
917 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700918
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700919 final boolean networkCostly;
920 final int uidRules;
921 synchronized (mRulesLock) {
922 networkCostly = mMeteredIfaces.contains(iface);
923 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700924 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700925
926 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
927 return true;
928 }
929
930 // no restrictive rules; network is visible
931 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700932 }
933
934 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700935 * Return a filtered {@link NetworkInfo}, potentially marked
936 * {@link DetailedState#BLOCKED} based on
937 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700938 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700939 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
940 NetworkInfo info = tracker.getNetworkInfo();
941 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700942 // network is blocked; clone and override state
943 info = new NetworkInfo(info);
944 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700945 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700946 if (mLockdownTracker != null) {
947 info = mLockdownTracker.augmentNetworkInfo(info);
948 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700949 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700950 }
951
952 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800953 * Return NetworkInfo for the active (i.e., connected) network interface.
954 * It is assumed that at most one network is active at a time. If more
955 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700956 * @return the info for the active network, or {@code null} if none is
957 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800958 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700959 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800960 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700961 enforceAccessPermission();
962 final int uid = Binder.getCallingUid();
963 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800964 }
965
Wink Saville89c87b92013-08-29 08:55:16 -0700966 /**
967 * Find the first Provisioning network.
968 *
969 * @return NetworkInfo or null if none.
970 */
971 private NetworkInfo getProvisioningNetworkInfo() {
972 enforceAccessPermission();
973
974 // Find the first Provisioning Network
975 NetworkInfo provNi = null;
976 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville860f5282013-09-05 12:02:25 -0700977 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -0700978 provNi = ni;
979 break;
980 }
981 }
982 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
983 return provNi;
984 }
985
986 /**
987 * Find the first Provisioning network or the ActiveDefaultNetwork
988 * if there is no Provisioning network
989 *
990 * @return NetworkInfo or null if none.
991 */
992 @Override
993 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
994 enforceAccessPermission();
995
996 NetworkInfo provNi = getProvisioningNetworkInfo();
997 if (provNi == null) {
998 final int uid = Binder.getCallingUid();
999 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1000 }
1001 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1002 return provNi;
1003 }
1004
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001005 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1006 enforceAccessPermission();
1007 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1008 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1009 if (tracker != null) {
1010 return tracker.getNetworkInfo();
1011 }
1012 }
1013 return null;
1014 }
1015
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001016 @Override
1017 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1018 enforceConnectivityInternalPermission();
1019 return getNetworkInfo(mActiveDefaultNetwork, uid);
1020 }
1021
1022 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001023 public NetworkInfo getNetworkInfo(int networkType) {
1024 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001025 final int uid = Binder.getCallingUid();
1026 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 }
1028
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001029 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1030 NetworkInfo info = null;
1031 if (isNetworkTypeValid(networkType)) {
1032 final NetworkStateTracker tracker = mNetTrackers[networkType];
1033 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001034 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001035 }
1036 }
1037 return info;
1038 }
1039
1040 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001041 public NetworkInfo[] getAllNetworkInfo() {
1042 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001043 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001044 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001045 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001046 for (NetworkStateTracker tracker : mNetTrackers) {
1047 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001048 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001049 }
1050 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001051 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001052 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001053 }
1054
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001055 @Override
1056 public boolean isNetworkSupported(int networkType) {
1057 enforceAccessPermission();
1058 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1059 }
1060
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001061 /**
1062 * Return LinkProperties for the active (i.e., connected) default
1063 * network interface. It is assumed that at most one default network
1064 * is active at a time. If more than one is active, it is indeterminate
1065 * which will be returned.
1066 * @return the ip properties for the active network, or {@code null} if
1067 * none is active
1068 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001069 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001070 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001071 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001072 }
1073
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001074 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001075 public LinkProperties getLinkProperties(int networkType) {
1076 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001077 if (isNetworkTypeValid(networkType)) {
1078 final NetworkStateTracker tracker = mNetTrackers[networkType];
1079 if (tracker != null) {
1080 return tracker.getLinkProperties();
1081 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001082 }
1083 return null;
1084 }
1085
Jeff Sharkey21062e72011-05-28 20:56:34 -07001086 @Override
1087 public NetworkState[] getAllNetworkState() {
1088 enforceAccessPermission();
1089 final int uid = Binder.getCallingUid();
1090 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001091 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001092 for (NetworkStateTracker tracker : mNetTrackers) {
1093 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001094 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001095 result.add(new NetworkState(
1096 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1097 }
1098 }
1099 }
1100 return result.toArray(new NetworkState[result.size()]);
1101 }
1102
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001103 private NetworkState getNetworkStateUnchecked(int networkType) {
1104 if (isNetworkTypeValid(networkType)) {
1105 final NetworkStateTracker tracker = mNetTrackers[networkType];
1106 if (tracker != null) {
1107 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1108 tracker.getLinkCapabilities());
1109 }
1110 }
1111 return null;
1112 }
1113
1114 @Override
1115 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1116 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001117
1118 final long token = Binder.clearCallingIdentity();
1119 try {
1120 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1121 if (state != null) {
1122 try {
1123 return mPolicyManager.getNetworkQuotaInfo(state);
1124 } catch (RemoteException e) {
1125 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001126 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001127 return null;
1128 } finally {
1129 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001130 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001131 }
1132
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001133 @Override
1134 public boolean isActiveNetworkMetered() {
1135 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001136 final long token = Binder.clearCallingIdentity();
1137 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001138 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001139 } finally {
1140 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001141 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001142 }
1143
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001144 private boolean isNetworkMeteredUnchecked(int networkType) {
1145 final NetworkState state = getNetworkStateUnchecked(networkType);
1146 if (state != null) {
1147 try {
1148 return mPolicyManager.isNetworkMetered(state);
1149 } catch (RemoteException e) {
1150 }
1151 }
1152 return false;
1153 }
1154
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 public boolean setRadios(boolean turnOn) {
1156 boolean result = true;
1157 enforceChangePermission();
1158 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001159 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001160 }
1161 return result;
1162 }
1163
1164 public boolean setRadio(int netType, boolean turnOn) {
1165 enforceChangePermission();
1166 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1167 return false;
1168 }
1169 NetworkStateTracker tracker = mNetTrackers[netType];
1170 return tracker != null && tracker.setRadio(turnOn);
1171 }
1172
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001173 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1174 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001175 public void interfaceClassDataActivityChanged(String label, boolean active) {
1176 int deviceType = Integer.parseInt(label);
1177 sendDataActivityBroadcast(deviceType, active);
1178 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001179 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001180
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001181 /**
1182 * Used to notice when the calling process dies so we can self-expire
1183 *
1184 * Also used to know if the process has cleaned up after itself when
1185 * our auto-expire timer goes off. The timer has a link to an object.
1186 *
1187 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001188 private class FeatureUser implements IBinder.DeathRecipient {
1189 int mNetworkType;
1190 String mFeature;
1191 IBinder mBinder;
1192 int mPid;
1193 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001194 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195
1196 FeatureUser(int type, String feature, IBinder binder) {
1197 super();
1198 mNetworkType = type;
1199 mFeature = feature;
1200 mBinder = binder;
1201 mPid = getCallingPid();
1202 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001203 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001204
Robert Greenwalt2034b912009-08-12 16:08:25 -07001205 try {
1206 mBinder.linkToDeath(this, 0);
1207 } catch (RemoteException e) {
1208 binderDied();
1209 }
1210 }
1211
1212 void unlinkDeathRecipient() {
1213 mBinder.unlinkToDeath(this, 0);
1214 }
1215
1216 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001217 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001218 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1219 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001220 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001221 }
1222
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001223 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001224 if (VDBG) {
1225 log("ConnectivityService FeatureUser expire(" +
1226 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1227 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1228 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001229 stopUsingNetworkFeature(this, false);
1230 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001231
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001232 public boolean isSameUser(FeatureUser u) {
1233 if (u == null) return false;
1234
1235 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1236 }
1237
1238 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1239 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1240 TextUtils.equals(mFeature, feature)) {
1241 return true;
1242 }
1243 return false;
1244 }
1245
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001246 public String toString() {
1247 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1248 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1249 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001250 }
1251
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001252 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001253 public int startUsingNetworkFeature(int networkType, String feature,
1254 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001255 long startTime = 0;
1256 if (DBG) {
1257 startTime = SystemClock.elapsedRealtime();
1258 }
Wink Savillea7d56572011-09-21 11:05:43 -07001259 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001260 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1261 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001262 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001263 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001264 try {
1265 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1266 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001267 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001268 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001269
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001270 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001271
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001272 // TODO - move this into individual networktrackers
1273 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001274
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001275 if (mLockdownEnabled) {
1276 // Since carrier APNs usually aren't available from VPN
1277 // endpoint, mark them as unavailable.
1278 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1279 }
1280
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001281 if (mProtectedNetworks.contains(usedNetworkType)) {
1282 enforceConnectivityInternalPermission();
1283 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001284
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001285 // if UID is restricted, don't allow them to bring up metered APNs
1286 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1287 final int uidRules;
1288 synchronized (mRulesLock) {
1289 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1290 }
1291 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001292 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001293 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001294
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001295 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1296 if (network != null) {
1297 Integer currentPid = new Integer(getCallingPid());
1298 if (usedNetworkType != networkType) {
1299 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001300
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001301 if (ni.isAvailable() == false) {
1302 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1303 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001304 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001305 } else {
1306 // else make the attempt anyway - probably giving REQUEST_STARTED below
1307 if (DBG) {
1308 log("special network not available, but try anyway ni=" +
1309 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001310 }
1311 }
1312 }
1313
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001314 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001315
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001316 synchronized(this) {
1317 boolean addToList = true;
1318 if (restoreTimer < 0) {
1319 // In case there is no timer is specified for the feature,
1320 // make sure we don't add duplicate entry with the same request.
1321 for (FeatureUser u : mFeatureUsers) {
1322 if (u.isSameUser(f)) {
1323 // Duplicate user is found. Do not add.
1324 addToList = false;
1325 break;
1326 }
1327 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001328 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001329
1330 if (addToList) mFeatureUsers.add(f);
1331 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1332 // this gets used for per-pid dns when connected
1333 mNetRequestersPids[usedNetworkType].add(currentPid);
1334 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001335 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001336
1337 if (restoreTimer >= 0) {
1338 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1339 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1340 }
1341
1342 if ((ni.isConnectedOrConnecting() == true) &&
1343 !network.isTeardownRequested()) {
1344 if (ni.isConnected() == true) {
1345 final long token = Binder.clearCallingIdentity();
1346 try {
1347 // add the pid-specific dns
1348 handleDnsConfigurationChange(usedNetworkType);
1349 if (VDBG) log("special network already active");
1350 } finally {
1351 Binder.restoreCallingIdentity(token);
1352 }
Wink Saville64e3f782012-07-10 12:37:54 -07001353 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001354 }
1355 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001356 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001357 }
1358
1359 // check if the radio in play can make another contact
1360 // assume if cannot for now
1361
1362 if (DBG) {
1363 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1364 feature);
1365 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001366 if (network.reconnect()) {
Wink Saville89c87b92013-08-29 08:55:16 -07001367 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001368 return PhoneConstants.APN_REQUEST_STARTED;
1369 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07001370 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001371 return PhoneConstants.APN_REQUEST_FAILED;
1372 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001373 } else {
1374 // need to remember this unsupported request so we respond appropriately on stop
1375 synchronized(this) {
1376 mFeatureUsers.add(f);
1377 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1378 // this gets used for per-pid dns when connected
1379 mNetRequestersPids[usedNetworkType].add(currentPid);
1380 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001381 }
Wink Saville89c87b92013-08-29 08:55:16 -07001382 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001383 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001384 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001385 }
Wink Saville89c87b92013-08-29 08:55:16 -07001386 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001387 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001388 } finally {
1389 if (DBG) {
1390 final long execTime = SystemClock.elapsedRealtime() - startTime;
1391 if (execTime > 250) {
1392 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1393 } else {
1394 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1395 }
1396 }
1397 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001398 }
1399
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001400 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001401 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001402 enforceChangePermission();
1403
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001404 int pid = getCallingPid();
1405 int uid = getCallingUid();
1406
1407 FeatureUser u = null;
1408 boolean found = false;
1409
1410 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001411 for (FeatureUser x : mFeatureUsers) {
1412 if (x.isSameUser(pid, uid, networkType, feature)) {
1413 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001414 found = true;
1415 break;
1416 }
1417 }
1418 }
1419 if (found && u != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07001420 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001421 // stop regardless of how many other time this proc had called start
1422 return stopUsingNetworkFeature(u, true);
1423 } else {
1424 // none found!
Wink Saville89c87b92013-08-29 08:55:16 -07001425 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001426 return 1;
1427 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001428 }
1429
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001430 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1431 int networkType = u.mNetworkType;
1432 String feature = u.mFeature;
1433 int pid = u.mPid;
1434 int uid = u.mUid;
1435
1436 NetworkStateTracker tracker = null;
1437 boolean callTeardown = false; // used to carry our decision outside of sync block
1438
Wink Savillea7d56572011-09-21 11:05:43 -07001439 if (VDBG) {
1440 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001441 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001442
The Android Open Source Project28527d22009-03-03 19:31:44 -08001443 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001444 if (DBG) {
1445 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1446 ", net is invalid");
1447 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001448 return -1;
1449 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001450
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001451 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1452 // sync block
1453 synchronized(this) {
1454 // check if this process still has an outstanding start request
1455 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001456 if (VDBG) {
1457 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1458 ", ignoring");
1459 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001460 return 1;
1461 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001462 u.unlinkDeathRecipient();
1463 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1464 // If we care about duplicate requests, check for that here.
1465 //
1466 // This is done to support the extension of a request - the app
1467 // can request we start the network feature again and renew the
1468 // auto-shutoff delay. Normal "stop" calls from the app though
1469 // do not pay attention to duplicate requests - in effect the
1470 // API does not refcount and a single stop will counter multiple starts.
1471 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001472 for (FeatureUser x : mFeatureUsers) {
1473 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001474 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001475 return 1;
1476 }
1477 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001478 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001479
repo syncf5de5572011-07-29 23:55:49 -07001480 // TODO - move to individual network trackers
1481 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1482
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001483 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001484 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001485 if (DBG) {
1486 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1487 " no known tracker for used net type " + usedNetworkType);
1488 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001489 return -1;
1490 }
1491 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001492 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001493 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001494
1495 final long token = Binder.clearCallingIdentity();
1496 try {
1497 reassessPidDns(pid, true);
1498 } finally {
1499 Binder.restoreCallingIdentity(token);
1500 }
Mattias Falkdc919012011-08-23 14:15:13 +02001501 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001502 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001503 if (VDBG) {
1504 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1505 " others still using it");
1506 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001507 return 1;
1508 }
1509 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001510 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001511 if (DBG) {
1512 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1513 " not a known feature - dropping");
1514 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001515 }
1516 }
Wink Savillea7d56572011-09-21 11:05:43 -07001517
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001518 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001519 if (DBG) {
1520 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1521 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001522 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001523 return 1;
1524 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001525 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001526 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527 }
1528
1529 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001530 * @deprecated use requestRouteToHostAddress instead
1531 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001532 * Ensure that a network route exists to deliver traffic to the specified
1533 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001534 * @param networkType the type of the network over which traffic to the
1535 * specified host is to be routed
1536 * @param hostAddress the IP address of the host to which the route is
1537 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 * @return {@code true} on success, {@code false} on failure
1539 */
1540 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001541 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1542
1543 if (inetAddress == null) {
1544 return false;
1545 }
1546
1547 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1548 }
1549
1550 /**
1551 * Ensure that a network route exists to deliver traffic to the specified
1552 * host via the specified network interface.
1553 * @param networkType the type of the network over which traffic to the
1554 * specified host is to be routed
1555 * @param hostAddress the IP address of the host to which the route is
1556 * desired
1557 * @return {@code true} on success, {@code false} on failure
1558 */
1559 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001560 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001561 if (mProtectedNetworks.contains(networkType)) {
1562 enforceConnectivityInternalPermission();
1563 }
1564
The Android Open Source Project28527d22009-03-03 19:31:44 -08001565 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001566 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 return false;
1568 }
1569 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter7caa36a2013-11-07 22:08:24 -08001570 DetailedState netState = DetailedState.DISCONNECTED;
1571 if (tracker != null) {
1572 netState = tracker.getNetworkInfo().getDetailedState();
1573 }
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001574
Ken Mixter7caa36a2013-11-07 22:08:24 -08001575 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001576 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001577 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001578 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001579 log("requestRouteToHostAddress on down network "
1580 + "(" + networkType + ") - dropped"
1581 + " tracker=" + tracker
1582 + " netState=" + netState
1583 + " isTeardownRequested="
1584 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001585 }
1586 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001587 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001588 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001589 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001590 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001591 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker78850f32013-07-15 16:34:04 -07001592 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville690cb182013-06-29 21:10:57 -07001593 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1594 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001595 } catch (UnknownHostException e) {
1596 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1597 } finally {
1598 Binder.restoreCallingIdentity(token);
1599 }
Wink Saville690cb182013-06-29 21:10:57 -07001600 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001601 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001602 }
1603
Chad Brubaker78850f32013-07-15 16:34:04 -07001604 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1605 boolean exempt) {
1606 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001607 }
1608
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001609 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001610 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001611 }
1612
Chad Brubaker78850f32013-07-15 16:34:04 -07001613 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1614 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001615 }
1616
1617 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001618 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001619 }
1620
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001621 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001622 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001623 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001624 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001625 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001626 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001627 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001628 if (bestRoute.getGateway().equals(addr)) {
1629 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001630 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001631 } else {
1632 // if we will connect to this through another route, add a direct route
1633 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001634 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001635 }
1636 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001637 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001638 }
1639
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001640 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001641 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001642 if ((lp == null) || (r == null)) {
1643 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001644 return false;
1645 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001646
1647 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001648 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001649 return false;
1650 }
1651
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001652 String ifaceName = r.getInterface();
1653 if(ifaceName == null) {
1654 loge("Error modifying route - no interface name");
1655 return false;
1656 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001657 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001658 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001659 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001660 if (bestRoute.getGateway().equals(r.getGateway())) {
1661 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001662 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001663 } else {
1664 // if we will connect to our gateway through another route, add a direct
1665 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001666 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1667 bestRoute.getGateway(),
1668 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001669 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001670 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001671 }
1672 }
1673 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001674 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001675 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001676 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001677 synchronized (mRoutesLock) {
1678 // only track default table - only one apps can effect
1679 mAddedRoutes.add(r);
1680 mNetd.addRoute(ifaceName, r);
1681 if (exempt) {
1682 LinkAddress dest = r.getDestination();
1683 if (!mExemptAddresses.contains(dest)) {
1684 mNetd.setHostExemption(dest);
1685 mExemptAddresses.add(dest);
1686 }
1687 }
1688 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001689 } else {
1690 mNetd.addSecondaryRoute(ifaceName, r);
1691 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001692 } catch (Exception e) {
1693 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001694 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001695 return false;
1696 }
1697 } else {
1698 // if we remove this one and there are no more like it, then refcount==0 and
1699 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001700 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001701 synchronized (mRoutesLock) {
1702 mAddedRoutes.remove(r);
1703 if (mAddedRoutes.contains(r) == false) {
1704 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1705 try {
1706 mNetd.removeRoute(ifaceName, r);
1707 LinkAddress dest = r.getDestination();
1708 if (mExemptAddresses.contains(dest)) {
1709 mNetd.clearHostExemption(dest);
1710 mExemptAddresses.remove(dest);
1711 }
1712 } catch (Exception e) {
1713 // never crash - catch them all
1714 if (VDBG) loge("Exception trying to remove a route: " + e);
1715 return false;
1716 }
1717 } else {
1718 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001719 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001720 }
1721 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001722 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001723 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001724 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001725 } catch (Exception e) {
1726 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001727 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001728 return false;
1729 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001730 }
1731 }
1732 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001733 }
1734
1735 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001736 * @see ConnectivityManager#getMobileDataEnabled()
1737 */
1738 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001739 // TODO: This detail should probably be in DataConnectionTracker's
1740 // which is where we store the value and maybe make this
1741 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001742 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001743 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1744 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001745 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001746 return retVal;
1747 }
1748
Robert Greenwalt34848c02011-03-25 13:09:25 -07001749 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001750 enforceConnectivityInternalPermission();
1751
Robert Greenwalt34848c02011-03-25 13:09:25 -07001752 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1753 (met ? ENABLED : DISABLED), networkType));
1754 }
1755
1756 private void handleSetDependencyMet(int networkType, boolean met) {
1757 if (mNetTrackers[networkType] != null) {
1758 if (DBG) {
1759 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1760 }
1761 mNetTrackers[networkType].setDependencyMet(met);
1762 }
1763 }
1764
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001765 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1766 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001767 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001768 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001770 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001771 }
1772
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001773 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001774 // skip update when we've already applied rules
1775 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1776 if (oldRules == uidRules) return;
1777
1778 mUidRules.put(uid, uidRules);
1779 }
1780
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001781 // TODO: notify UID when it has requested targeted updates
1782 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001783
1784 @Override
1785 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001786 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001787 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001788 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001789 }
1790
1791 synchronized (mRulesLock) {
1792 mMeteredIfaces.clear();
1793 for (String iface : meteredIfaces) {
1794 mMeteredIfaces.add(iface);
1795 }
1796 }
1797 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001798
1799 @Override
1800 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1801 // caller is NPMS, since we only register with them
1802 if (LOGD_RULES) {
1803 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1804 }
1805
1806 // kick off connectivity change broadcast for active network, since
1807 // global background policy change is radical.
1808 final int networkType = mActiveDefaultNetwork;
1809 if (isNetworkTypeValid(networkType)) {
1810 final NetworkStateTracker tracker = mNetTrackers[networkType];
1811 if (tracker != null) {
1812 final NetworkInfo info = tracker.getNetworkInfo();
1813 if (info != null && info.isConnected()) {
1814 sendConnectedBroadcast(info);
1815 }
1816 }
1817 }
1818 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001819 };
1820
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001821 /**
1822 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1823 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001824 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001825 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001826 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001827
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001828 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001829 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001830 }
1831
1832 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001833 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001834 if (VDBG) {
1835 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001836 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001837 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1838 }
tk.mun5eee1042012-01-06 10:43:52 +09001839 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1840 if (VDBG) {
1841 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1842 }
1843 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1844 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001845 }
1846
1847 @Override
1848 public void setPolicyDataEnable(int networkType, boolean enabled) {
1849 // only someone like NPMS should only be calling us
1850 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1851
1852 mHandler.sendMessage(mHandler.obtainMessage(
1853 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1854 }
1855
1856 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1857 if (isNetworkTypeValid(networkType)) {
1858 final NetworkStateTracker tracker = mNetTrackers[networkType];
1859 if (tracker != null) {
1860 tracker.setPolicyDataEnable(enabled);
1861 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001862 }
1863 }
1864
The Android Open Source Project28527d22009-03-03 19:31:44 -08001865 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001866 mContext.enforceCallingOrSelfPermission(
1867 android.Manifest.permission.ACCESS_NETWORK_STATE,
1868 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001869 }
1870
1871 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001872 mContext.enforceCallingOrSelfPermission(
1873 android.Manifest.permission.CHANGE_NETWORK_STATE,
1874 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001875 }
1876
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001877 // TODO Make this a special check when it goes public
1878 private void enforceTetherChangePermission() {
1879 mContext.enforceCallingOrSelfPermission(
1880 android.Manifest.permission.CHANGE_NETWORK_STATE,
1881 "ConnectivityService");
1882 }
1883
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001884 private void enforceTetherAccessPermission() {
1885 mContext.enforceCallingOrSelfPermission(
1886 android.Manifest.permission.ACCESS_NETWORK_STATE,
1887 "ConnectivityService");
1888 }
1889
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001890 private void enforceConnectivityInternalPermission() {
1891 mContext.enforceCallingOrSelfPermission(
1892 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1893 "ConnectivityService");
1894 }
1895
Chad Brubaker31de0b62013-07-11 13:29:30 -07001896 private void enforceMarkNetworkSocketPermission() {
1897 //Media server special case
1898 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1899 return;
1900 }
1901 mContext.enforceCallingOrSelfPermission(
1902 android.Manifest.permission.MARK_NETWORK_SOCKET,
1903 "ConnectivityService");
1904 }
1905
The Android Open Source Project28527d22009-03-03 19:31:44 -08001906 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001907 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1908 * network, we ignore it. If it is for the active network, we send out a
1909 * broadcast. But first, we check whether it might be possible to connect
1910 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001911 * @param info the {@code NetworkInfo} for the network
1912 */
1913 private void handleDisconnect(NetworkInfo info) {
1914
Robert Greenwalt2034b912009-08-12 16:08:25 -07001915 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001916
Robert Greenwalt2034b912009-08-12 16:08:25 -07001917 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001918
1919 // Remove idletimer previously setup in {@code handleConnect}
1920 removeDataActivityTracking(prevNetType);
1921
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 /*
1923 * If the disconnected network is not the active one, then don't report
1924 * this as a loss of connectivity. What probably happened is that we're
1925 * getting the disconnect for a network that we explicitly disabled
1926 * in accordance with network preference policies.
1927 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001928 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001929 List<Integer> pids = mNetRequestersPids[prevNetType];
1930 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001931 // will remove them because the net's no longer connected
1932 // need to do this now as only now do we know the pids and
1933 // can properly null things that are no longer referenced.
1934 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001935 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001936 }
1937
The Android Open Source Project28527d22009-03-03 19:31:44 -08001938 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001939 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001940 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001941 if (info.isFailover()) {
1942 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1943 info.setFailover(false);
1944 }
1945 if (info.getReason() != null) {
1946 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1947 }
1948 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001949 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1950 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001951 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001952
Robert Greenwalt34848c02011-03-25 13:09:25 -07001953 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001954 tryFailover(prevNetType);
1955 if (mActiveDefaultNetwork != -1) {
1956 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001957 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1958 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001959 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001960 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1961 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001962 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001963 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001964
1965 // Reset interface if no other connections are using the same interface
1966 boolean doReset = true;
1967 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1968 if (linkProperties != null) {
1969 String oldIface = linkProperties.getInterfaceName();
1970 if (TextUtils.isEmpty(oldIface) == false) {
1971 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1972 if (networkStateTracker == null) continue;
1973 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1974 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1975 LinkProperties l = networkStateTracker.getLinkProperties();
1976 if (l == null) continue;
1977 if (oldIface.equals(l.getInterfaceName())) {
1978 doReset = false;
1979 break;
1980 }
1981 }
1982 }
1983 }
1984 }
1985
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001986 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001987 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001988
Jeff Sharkey971cd162011-08-29 16:02:57 -07001989 final Intent immediateIntent = new Intent(intent);
1990 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1991 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001992 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001993 /*
1994 * If the failover network is already connected, then immediately send
1995 * out a followup broadcast indicating successful failover
1996 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001997 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001998 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1999 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002000 }
2001 }
2002
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002003 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002004 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08002005 * If this is a default network, check if other defaults are available.
2006 * Try to reconnect on all available and let them hash it out when
2007 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07002008 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07002009 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002010 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville89c87b92013-08-29 08:55:16 -07002011 if (DBG) {
2012 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2013 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002014 mActiveDefaultNetwork = -1;
2015 }
2016
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002017 // don't signal a reconnect for anything lower or equal priority than our
2018 // current connected default
2019 // TODO - don't filter by priority now - nice optimization but risky
2020// int currentPriority = -1;
2021// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002022// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002023// }
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002024
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002025 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002026 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002027 if (mNetConfigs[checkType] == null) continue;
2028 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002029 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002030
2031// Enabling the isAvailable() optimization caused mobile to not get
2032// selected if it was in the middle of error handling. Specifically
2033// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2034// would not be available and we wouldn't get connected to anything.
2035// So removing the isAvailable() optimization below for now. TODO: This
2036// optimization should work and we need to investigate why it doesn't work.
2037// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2038// complete before it is really complete.
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002039
Wink Saville72a95b92011-01-26 15:43:49 -08002040// if (!mNetTrackers[checkType].isAvailable()) continue;
2041
Robert Greenwalt34848c02011-03-25 13:09:25 -07002042// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002043
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002044 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2045 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2046 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2047 checkInfo.setFailover(true);
2048 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002049 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002050 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002051 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002052 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002053 }
2054
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002055 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002056 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002057 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2058 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002059 }
2060
Wink Saville4f0de1e2011-08-04 15:01:58 -07002061 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002062 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2063 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002064 }
2065
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002066 private void sendInetConditionBroadcast(NetworkInfo info) {
2067 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2068 }
2069
Wink Saville4f0de1e2011-08-04 15:01:58 -07002070 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002071 if (mLockdownTracker != null) {
2072 info = mLockdownTracker.augmentNetworkInfo(info);
2073 }
2074
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002075 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002076 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002077 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 if (info.isFailover()) {
2079 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2080 info.setFailover(false);
2081 }
2082 if (info.getReason() != null) {
2083 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2084 }
2085 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002086 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2087 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002089 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002090 return intent;
2091 }
2092
2093 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2094 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2095 }
2096
2097 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2098 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002099 }
2100
Haoyu Baib5da5752012-06-20 14:29:57 -07002101 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2102 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2103 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2104 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002105 final long ident = Binder.clearCallingIdentity();
2106 try {
2107 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2108 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002112 }
2113
The Android Open Source Project28527d22009-03-03 19:31:44 -08002114 /**
2115 * Called when an attempt to fail over to another network has failed.
2116 * @param info the {@link NetworkInfo} for the failed network
2117 */
2118 private void handleConnectionFailure(NetworkInfo info) {
2119 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002120
Robert Greenwalt2034b912009-08-12 16:08:25 -07002121 String reason = info.getReason();
2122 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002123
Robert Greenwalte981bc52010-10-08 16:35:52 -07002124 String reasonText;
2125 if (reason == null) {
2126 reasonText = ".";
2127 } else {
2128 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002129 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002130 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002131
2132 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002133 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002134 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002135 if (getActiveNetworkInfo() == null) {
2136 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2137 }
2138 if (reason != null) {
2139 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2140 }
2141 if (extraInfo != null) {
2142 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2143 }
2144 if (info.isFailover()) {
2145 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2146 info.setFailover(false);
2147 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002148
Robert Greenwalt34848c02011-03-25 13:09:25 -07002149 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002150 tryFailover(info.getType());
2151 if (mActiveDefaultNetwork != -1) {
2152 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002153 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2154 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002155 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002156 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2157 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002158 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002159
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002160 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002161
2162 final Intent immediateIntent = new Intent(intent);
2163 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2164 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002165 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002166 /*
2167 * If the failover network is already connected, then immediately send
2168 * out a followup broadcast indicating successful failover
2169 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002170 if (mActiveDefaultNetwork != -1) {
2171 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002172 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002173 }
2174
2175 private void sendStickyBroadcast(Intent intent) {
2176 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002177 if (!mSystemReady) {
2178 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002179 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002180 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002181 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002182 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002183 }
2184
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002185 final long ident = Binder.clearCallingIdentity();
2186 try {
2187 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2188 } finally {
2189 Binder.restoreCallingIdentity(ident);
2190 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002191 }
2192 }
2193
Wink Saville4f0de1e2011-08-04 15:01:58 -07002194 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2195 if (delayMs <= 0) {
2196 sendStickyBroadcast(intent);
2197 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002198 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002199 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2200 + intent.getAction());
2201 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002202 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2203 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2204 }
2205 }
2206
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002207 void systemReady() {
Wink Saville89c87b92013-08-29 08:55:16 -07002208 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2209 loadGlobalProxy();
2210
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002211 synchronized(this) {
2212 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002213 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002214 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002215 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002216 }
2217 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002218 // load the global proxy at startup
2219 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002220
2221 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2222 // for user to unlock device.
2223 if (!updateLockdownVpn()) {
2224 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2225 mContext.registerReceiver(mUserPresentReceiver, filter);
2226 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002227 }
2228
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002229 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2230 @Override
2231 public void onReceive(Context context, Intent intent) {
2232 // Try creating lockdown tracker, since user present usually means
2233 // unlocked keystore.
2234 if (updateLockdownVpn()) {
2235 mContext.unregisterReceiver(this);
2236 }
2237 }
2238 };
2239
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002240 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville89c87b92013-08-29 08:55:16 -07002241 if (((type != mNetworkPreference)
2242 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2243 || (mNetworkPreference == mActiveDefaultNetwork)) {
2244 return false;
2245 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002246 return true;
2247 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002249 private void handleConnect(NetworkInfo info) {
2250 final int newNetType = info.getType();
2251
2252 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002253
The Android Open Source Project28527d22009-03-03 19:31:44 -08002254 // snapshot isFailover, because sendConnectedBroadcast() resets it
2255 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002256 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002257 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002258
Wink Saville89c87b92013-08-29 08:55:16 -07002259 if (VDBG) {
2260 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2261 + " isFailover" + isFailover);
2262 }
2263
Robert Greenwalt2034b912009-08-12 16:08:25 -07002264 // if this is a default net and other default is running
2265 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002266 if (mNetConfigs[newNetType].isDefault()) {
2267 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2268 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002269 // tear down the other
2270 NetworkStateTracker otherNet =
2271 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002272 if (DBG) {
2273 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002274 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002275 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002276 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002277 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002278 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002279 return;
2280 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002281 } else {
2282 // don't accept this one
2283 if (VDBG) {
2284 log("Not broadcasting CONNECT_ACTION " +
2285 "to torn down network " + info.getTypeName());
2286 }
2287 teardown(thisNet);
2288 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002289 }
2290 }
2291 synchronized (ConnectivityService.this) {
2292 // have a new default network, release the transition wakelock in a second
2293 // if it's held. The second pause is to allow apps to reconnect over the
2294 // new network
2295 if (mNetTransitionWakeLock.isHeld()) {
2296 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002297 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002298 mNetTransitionWakeLockSerialNumber, 0),
2299 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002300 }
2301 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002302 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002303 // this will cause us to come up initially as unconnected and switching
2304 // to connected after our normal pause unless somebody reports us as reall
2305 // disconnected
2306 mDefaultInetConditionPublished = 0;
2307 mDefaultConnectionSequence++;
2308 mInetConditionChangeInFlight = false;
2309 // Don't do this - if we never sign in stay, grey
2310 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002311 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002312 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002313 updateNetworkSettings(thisNet);
sy.yun30043282013-09-02 05:24:09 +09002314 updateMtuSizeSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002315 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002316 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002317
2318 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002319 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002320 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002321 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002322 } catch (RemoteException e) {
2323 // ignored; service lives in system_server
2324 }
2325 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002326 }
2327
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002328 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2329 if (DBG) log("Captive portal check " + info);
2330 int type = info.getType();
2331 final NetworkStateTracker thisNet = mNetTrackers[type];
2332 if (mNetConfigs[type].isDefault()) {
2333 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2334 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2335 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002336 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002337 return;
2338 } else {
2339 if (DBG) log("Tear down low priority net " + info.getTypeName());
2340 teardown(thisNet);
2341 return;
2342 }
2343 }
2344 }
2345
Wink Savilleffdadd62013-08-07 16:22:47 -07002346 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002347 thisNet.captivePortalCheckComplete();
2348 }
2349
2350 /** @hide */
Wink Savilleffdadd62013-08-07 16:22:47 -07002351 @Override
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002352 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002353 enforceConnectivityInternalPermission();
Wink Savilleffdadd62013-08-07 16:22:47 -07002354 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002355 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002356 }
2357
Wink Savilleffdadd62013-08-07 16:22:47 -07002358 /** @hide */
2359 @Override
2360 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2361 enforceConnectivityInternalPermission();
2362 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2363 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2364 }
2365
The Android Open Source Project28527d22009-03-03 19:31:44 -08002366 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002367 * Setup data activity tracking for the given network interface.
2368 *
2369 * Every {@code setupDataActivityTracking} should be paired with a
2370 * {@link removeDataActivityTracking} for cleanup.
2371 */
2372 private void setupDataActivityTracking(int type) {
2373 final NetworkStateTracker thisNet = mNetTrackers[type];
2374 final String iface = thisNet.getLinkProperties().getInterfaceName();
2375
2376 final int timeout;
2377
2378 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002379 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2380 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002381 0);
2382 // Canonicalize mobile network type
2383 type = ConnectivityManager.TYPE_MOBILE;
2384 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002385 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2386 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002387 0);
2388 } else {
2389 // do not track any other networks
2390 timeout = 0;
2391 }
2392
2393 if (timeout > 0 && iface != null) {
2394 try {
2395 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2396 } catch (RemoteException e) {
2397 }
2398 }
2399 }
2400
2401 /**
2402 * Remove data activity tracking when network disconnects.
2403 */
2404 private void removeDataActivityTracking(int type) {
2405 final NetworkStateTracker net = mNetTrackers[type];
2406 final String iface = net.getLinkProperties().getInterfaceName();
2407
2408 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2409 ConnectivityManager.TYPE_WIFI == type)) {
2410 try {
2411 // the call fails silently if no idletimer setup for this interface
2412 mNetd.removeIdleTimer(iface);
2413 } catch (RemoteException e) {
2414 }
2415 }
2416 }
2417
2418 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002419 * After a change in the connectivity state of a network. We're mainly
2420 * concerned with making sure that the list of DNS servers is set up
2421 * according to which networks are connected, and ensuring that the
2422 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002423 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002424 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002425 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker78850f32013-07-15 16:34:04 -07002426 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville89c87b92013-08-29 08:55:16 -07002427 if (VDBG) {
2428 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2429 + " resetMask=" + resetMask);
2430 }
Wink Saville051a6642011-07-13 13:44:13 -07002431
The Android Open Source Project28527d22009-03-03 19:31:44 -08002432 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002433 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002434 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002435 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002436 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002437
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002438 LinkProperties curLp = mCurrentLinkProperties[netType];
2439 LinkProperties newLp = null;
2440
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002441 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002442 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002443 if (VDBG) {
2444 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2445 " doReset=" + doReset + " resetMask=" + resetMask +
2446 "\n curLp=" + curLp +
2447 "\n newLp=" + newLp);
2448 }
2449
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002450 if (curLp != null) {
2451 if (curLp.isIdenticalInterfaceName(newLp)) {
2452 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2453 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2454 for (LinkAddress linkAddr : car.removed) {
2455 if (linkAddr.getAddress() instanceof Inet4Address) {
2456 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2457 }
2458 if (linkAddr.getAddress() instanceof Inet6Address) {
2459 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2460 }
Wink Saville051a6642011-07-13 13:44:13 -07002461 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002462 if (DBG) {
2463 log("handleConnectivityChange: addresses changed" +
2464 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2465 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002466 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002467 } else {
2468 if (DBG) {
2469 log("handleConnectivityChange: address are the same reset per doReset" +
2470 " linkProperty[" + netType + "]:" +
2471 " resetMask=" + resetMask);
2472 }
Wink Saville051a6642011-07-13 13:44:13 -07002473 }
2474 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002475 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002476 if (DBG) {
2477 log("handleConnectivityChange: interface not not equivalent reset both" +
2478 " linkProperty[" + netType + "]:" +
2479 " resetMask=" + resetMask);
2480 }
Wink Saville051a6642011-07-13 13:44:13 -07002481 }
Wink Saville051a6642011-07-13 13:44:13 -07002482 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002483 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002484 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002485 }
2486 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002487 if (VDBG) {
2488 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2489 " doReset=" + doReset + " resetMask=" + resetMask +
2490 "\n curLp=" + curLp +
2491 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002492 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002493 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002494 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker78850f32013-07-15 16:34:04 -07002495 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002496
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002497 if (resetMask != 0 || resetDns) {
Wink Saville89c87b92013-08-29 08:55:16 -07002498 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002499 if (curLp != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07002500 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002501 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002502 if (TextUtils.isEmpty(iface) == false) {
2503 if (resetMask != 0) {
2504 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2505 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002506
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002507 // Tell VPN the interface is down. It is a temporary
2508 // but effective fix to make VPN aware of the change.
2509 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002510 synchronized(mVpns) {
2511 for (int i = 0; i < mVpns.size(); i++) {
2512 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2513 }
2514 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002515 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002516 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002517 if (resetDns) {
2518 flushVmDnsCache();
2519 if (VDBG) log("resetting DNS cache for " + iface);
2520 try {
2521 mNetd.flushInterfaceDnsCache(iface);
2522 } catch (Exception e) {
2523 // never crash - catch them all
2524 if (DBG) loge("Exception resetting dns cache: " + e);
2525 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002526 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002527 } else {
2528 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002529 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002530 }
2531 }
2532 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002533
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002534 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002535 NetworkStateTracker tracker = mNetTrackers[netType];
2536 if (mClat.requiresClat(netType, tracker)) {
Wink Saville89c87b92013-08-29 08:55:16 -07002537
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002538 // If the connection was previously using clat, but is not using it now, stop the clat
2539 // daemon. Normally, this happens automatically when the connection disconnects, but if
2540 // the disconnect is not reported, or if the connection's LinkProperties changed for
2541 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2542 // still be running. If it's not running, then stopping it is a no-op.
2543 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2544 mClat.stopClat();
2545 }
2546 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002547 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2548 mClat.startClat(tracker);
2549 } else {
2550 mClat.stopClat();
2551 }
2552 }
2553
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002554 // TODO: Temporary notifying upstread change to Tethering.
2555 // @see bug/4455071
2556 /** Notify TetheringService if interface name has been changed. */
2557 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002558 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002559 if (isTetheringSupported()) {
2560 mTethering.handleTetherIfaceChange();
2561 }
2562 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002563 }
2564
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002565 /**
2566 * Add and remove routes using the old properties (null if not previously connected),
2567 * new properties (null if becoming disconnected). May even be double null, which
2568 * is a noop.
2569 * Uses isLinkDefault to determine if default routes should be set or conversely if
2570 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002571 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002572 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002573 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker78850f32013-07-15 16:34:04 -07002574 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002575 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002576 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2577 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002578 if (curLp != null) {
2579 // check for the delta between the current set and the new
Lorenzo Colitti43553b62013-07-31 23:23:21 +09002580 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002581 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002582 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002583 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002584 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002585 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002586
Robert Greenwalt8d777252011-08-15 12:31:55 -07002587 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2588
Robert Greenwalt98107422011-07-22 11:55:33 -07002589 for (RouteInfo r : routeDiff.removed) {
2590 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002591 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002592 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2593 }
2594 if (isLinkDefault == false) {
2595 // remove from a secondary route table
2596 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002597 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002598 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002599
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002600 if (!isLinkDefault) {
2601 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002602 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002603 // routes changed - remove all old dns entries and add new
2604 if (curLp != null) {
2605 for (InetAddress oldDns : curLp.getDnses()) {
2606 removeRouteToAddress(curLp, oldDns);
2607 }
2608 }
2609 if (newLp != null) {
2610 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002611 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002612 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002613 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002614 } else {
2615 // no change in routes, check for change in dns themselves
2616 for (InetAddress oldDns : dnsDiff.removed) {
2617 removeRouteToAddress(curLp, oldDns);
2618 }
2619 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002620 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002621 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002622 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002623 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002624
2625 for (RouteInfo r : routeDiff.added) {
2626 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002627 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002628 } else {
2629 // add to a secondary route table
Chad Brubaker78850f32013-07-15 16:34:04 -07002630 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002631
2632 // many radios add a default route even when we don't want one.
2633 // remove the default route unless somebody else has asked for it
2634 String ifaceName = newLp.getInterfaceName();
Chad Brubaker78850f32013-07-15 16:34:04 -07002635 synchronized (mRoutesLock) {
2636 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2637 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2638 try {
2639 mNetd.removeRoute(ifaceName, r);
2640 } catch (Exception e) {
2641 // never crash - catch them all
2642 if (DBG) loge("Exception trying to remove a route: " + e);
2643 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002644 }
2645 }
2646 }
2647 }
2648
Robert Greenwalt8d777252011-08-15 12:31:55 -07002649 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002650 }
2651
sy.yun30043282013-09-02 05:24:09 +09002652 /**
2653 * Reads the network specific MTU size from reources.
2654 * and set it on it's iface.
2655 */
2656 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2657 final String iface = nt.getLinkProperties().getInterfaceName();
2658 final int mtu = nt.getLinkProperties().getMtu();
2659
2660 if (mtu < 68 || mtu > 10000) {
2661 loge("Unexpected mtu value: " + nt);
2662 return;
2663 }
2664
2665 try {
2666 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2667 mNetd.setMtu(iface, mtu);
2668 } catch (Exception e) {
2669 Slog.e(TAG, "exception in setMtu()" + e);
2670 }
2671 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002672
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002673 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002674 * Reads the network specific TCP buffer sizes from SystemProperties
2675 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2676 * wide use
2677 */
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002678 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002679 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002680 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002681
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002682 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002683 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002684
2685 // Setting to default values so we won't be stuck to previous values
2686 key = "net.tcp.buffersize.default";
2687 bufferSizes = SystemProperties.get(key);
2688 }
2689
2690 // Set values in kernel
2691 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002692 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002693 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002694 + "] which comes from [" + key + "]");
2695 }
2696 setBufferSize(bufferSizes);
2697 }
2698 }
2699
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002700 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002701 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2702 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2703 *
2704 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2705 * writeMin, writeInitial, writeMax"
2706 */
2707 private void setBufferSize(String bufferSizes) {
2708 try {
2709 String[] values = bufferSizes.split(",");
2710
2711 if (values.length == 6) {
2712 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002713 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2714 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2715 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2716 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2717 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2718 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002719 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002720 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002721 }
2722 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002723 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002724 }
2725 }
2726
Robert Greenwalt2034b912009-08-12 16:08:25 -07002727 /**
2728 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2729 * on the highest priority active net which this process requested.
2730 * If there aren't any, clear it out
2731 */
Mattias Falkdc919012011-08-23 14:15:13 +02002732 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002733 {
Mattias Falkdc919012011-08-23 14:15:13 +02002734 if (VDBG) log("reassessPidDns for pid " + pid);
2735 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002736 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002737 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002738 continue;
2739 }
2740 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002741 if (nt.getNetworkInfo().isConnected() &&
2742 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002743 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002744 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002745 if (mNetRequestersPids[i].contains(myPid)) {
2746 try {
2747 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2748 } catch (Exception e) {
2749 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002750 }
Mattias Falkdc919012011-08-23 14:15:13 +02002751 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002752 }
2753 }
2754 }
2755 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002756 try {
2757 mNetd.clearDnsInterfaceForPid(pid);
2758 } catch (Exception e) {
2759 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002760 }
2761 }
2762
Mattias Falkdc919012011-08-23 14:15:13 +02002763 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002764 /*
2765 * Tell the VMs to toss their DNS caches
2766 */
2767 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2768 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002769 /*
2770 * Connectivity events can happen before boot has completed ...
2771 */
2772 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002773 final long ident = Binder.clearCallingIdentity();
2774 try {
2775 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2776 } finally {
2777 Binder.restoreCallingIdentity(ident);
2778 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002779 }
2780
Chia-chi Yehcc844502011-07-14 18:01:57 -07002781 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002782 private void updateDnsLocked(String network, String iface,
Chad Brubaker45e721f2013-07-23 17:13:36 -07002783 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002784 int last = 0;
2785 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002786 dnses = new ArrayList();
2787 dnses.add(mDefaultDns);
2788 if (DBG) {
2789 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002790 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002791 }
2792
Mattias Falkdc919012011-08-23 14:15:13 +02002793 try {
2794 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker45e721f2013-07-23 17:13:36 -07002795 if (defaultDns) {
2796 mNetd.setDefaultInterfaceForDns(iface);
2797 }
2798
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002799 for (InetAddress dns : dnses) {
2800 ++last;
2801 String key = "net.dns" + last;
2802 String value = dns.getHostAddress();
2803 SystemProperties.set(key, value);
2804 }
2805 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2806 String key = "net.dns" + i;
2807 SystemProperties.set(key, "");
2808 }
2809 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002810 } catch (Exception e) {
Robert Greenwalt68534c82013-09-24 11:05:57 -07002811 loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002812 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002813 }
2814
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002815 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002816 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002817 NetworkStateTracker nt = mNetTrackers[netType];
2818 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002819 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002820 if (p == null) return;
2821 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002822 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002823 String network = nt.getNetworkInfo().getTypeName();
2824 synchronized (mDnsLock) {
Chad Brubakera8e81122013-07-23 17:44:41 -07002825 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002826 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002827 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002828 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002829 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002830 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002831 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002832 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002833 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002834 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002835 List<Integer> pids = mNetRequestersPids[netType];
2836 for (Integer pid : pids) {
2837 try {
2838 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2839 } catch (Exception e) {
2840 Slog.e(TAG, "exception setting interface for pid: " + e);
2841 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002842 }
2843 }
Mattias Falkdc919012011-08-23 14:15:13 +02002844 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002845 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002846 }
2847
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002848 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002849 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2850 NETWORK_RESTORE_DELAY_PROP_NAME);
2851 if(restoreDefaultNetworkDelayStr != null &&
2852 restoreDefaultNetworkDelayStr.length() != 0) {
2853 try {
2854 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2855 } catch (NumberFormatException e) {
2856 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002857 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002858 // if the system property isn't set, use the value for the apn type
2859 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2860
2861 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2862 (mNetConfigs[networkType] != null)) {
2863 ret = mNetConfigs[networkType].restoreTime;
2864 }
2865 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002866 }
2867
2868 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002869 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2870 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002871 if (mContext.checkCallingOrSelfPermission(
2872 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002873 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002874 pw.println("Permission Denial: can't dump ConnectivityService " +
2875 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2876 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002877 return;
2878 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002879
2880 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002881 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002882 for (int i = 0; i < mNetTrackers.length; i++) {
2883 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002884 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002885 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2886 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002887 if (nst.getNetworkInfo().isConnected()) {
2888 pw.println("Active network: " + nst.getNetworkInfo().
2889 getTypeName());
2890 }
2891 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002892 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002893 pw.println(nst);
2894 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002895 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002896 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002897 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002898
2899 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002900 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002901 for (int net : mPriorityList) {
2902 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002903 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002904 pidString = pidString + pid.toString() + ", ";
2905 }
2906 pw.println(pidString);
2907 }
2908 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002909 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002910
2911 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002912 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002913 for (Object requester : mFeatureUsers) {
2914 pw.println(requester.toString());
2915 }
2916 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002917 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002918
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002919 synchronized (this) {
2920 pw.println("NetworkTranstionWakeLock is currently " +
2921 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2922 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2923 }
2924 pw.println();
2925
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002926 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002927
2928 if (mInetLog != null) {
2929 pw.println();
2930 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002931 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002932 for(int i = 0; i < mInetLog.size(); i++) {
2933 pw.println(mInetLog.get(i));
2934 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002935 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002936 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002937 }
2938
Robert Greenwalt2034b912009-08-12 16:08:25 -07002939 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002940 private class NetworkStateTrackerHandler extends Handler {
2941 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002942 super(looper);
2943 }
2944
The Android Open Source Project28527d22009-03-03 19:31:44 -08002945 @Override
2946 public void handleMessage(Message msg) {
2947 NetworkInfo info;
2948 switch (msg.what) {
Wink Saville89c87b92013-08-29 08:55:16 -07002949 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002950 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002951 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002952
Wink Savillea7d56572011-09-21 11:05:43 -07002953 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville860f5282013-09-05 12:02:25 -07002954 (state == NetworkInfo.State.DISCONNECTED) ||
2955 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002956 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002957 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002958 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002959 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002960
Wink Saville89c87b92013-08-29 08:55:16 -07002961 // Since mobile has the notion of a network/apn that can be used for
2962 // provisioning we need to check every time we're connected as
2963 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2964 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2965 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2966 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2967 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Saville9564f2b2013-07-16 17:16:37 -07002968 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2969 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleab773a72013-09-14 09:04:53 -07002970 && (((state == NetworkInfo.State.CONNECTED)
2971 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2972 || info.isConnectedToProvisioningNetwork())) {
2973 log("ConnectivityChange checkMobileProvisioning for"
2974 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville89c87b92013-08-29 08:55:16 -07002975 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Saville9564f2b2013-07-16 17:16:37 -07002976 }
2977
Jeff Sharkeybde32692012-11-09 15:57:02 -08002978 EventLogTags.writeConnectivityStateChanged(
2979 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002980
2981 if (info.getDetailedState() ==
2982 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002983 handleConnectionFailure(info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002984 } else if (info.getDetailedState() ==
2985 DetailedState.CAPTIVE_PORTAL_CHECK) {
2986 handleCaptivePortalTrackerCheck(info);
Wink Saville860f5282013-09-05 12:02:25 -07002987 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002988 /**
2989 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2990 * for now its an in between network, its a network that
2991 * is actually a default network but we don't want it to be
2992 * announced as such to keep background applications from
2993 * trying to use it. It turns out that some still try so we
2994 * take the additional step of clearing any default routes
2995 * to the link that may have incorrectly setup by the lower
2996 * levels.
2997 */
2998 LinkProperties lp = getLinkProperties(info.getType());
2999 if (DBG) {
3000 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3001 }
3002
3003 // Clear any default routes setup by the radio so
3004 // any activity by applications trying to use this
3005 // connection will fail until the provisioning network
3006 // is enabled.
3007 for (RouteInfo r : lp.getRoutes()) {
3008 removeRoute(lp, r, TO_DEFAULT_TABLE);
3009 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08003010 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003011 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003012 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003013 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003014 // the logic here is, handle SUSPENDED the same as
3015 // DISCONNECTED. The only difference being we are
3016 // broadcasting an intent with NetworkInfo that's
3017 // suspended. This allows the applications an
3018 // opportunity to handle DISCONNECTED and SUSPENDED
3019 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003020 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003021 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003022 handleConnect(info);
3023 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003024 if (mLockdownTracker != null) {
3025 mLockdownTracker.onNetworkInfoChanged(info);
3026 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003027 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003028 }
3029 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003030 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003031 // TODO: Temporary allowing network configuration
3032 // change not resetting sockets.
3033 // @see bug/4455071
3034 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003035 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003036 }
3037 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003038 info = (NetworkInfo) msg.obj;
Wink Saville89c87b92013-08-29 08:55:16 -07003039 int type = info.getType();
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003040 updateNetworkSettings(mNetTrackers[type]);
3041 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003042 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003043 }
3044 }
3045 }
3046
3047 private class InternalHandler extends Handler {
3048 public InternalHandler(Looper looper) {
3049 super(looper);
3050 }
3051
3052 @Override
3053 public void handleMessage(Message msg) {
3054 NetworkInfo info;
3055 switch (msg.what) {
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003056 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003057 String causedBy = null;
3058 synchronized (ConnectivityService.this) {
3059 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3060 mNetTransitionWakeLock.isHeld()) {
3061 mNetTransitionWakeLock.release();
3062 causedBy = mNetTransitionWakeLockCausedBy;
3063 }
3064 }
3065 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003066 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003067 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003068 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003069 }
3070 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003071 FeatureUser u = (FeatureUser)msg.obj;
3072 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003073 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003074 }
3075 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003076 int netType = msg.arg1;
3077 int condition = msg.arg2;
3078 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003079 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003080 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003081 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003082 int netType = msg.arg1;
3083 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00003084 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003085 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003086 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003087 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003088 int preference = msg.arg1;
3089 handleSetNetworkPreference(preference);
3090 break;
3091 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003092 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003093 boolean enabled = (msg.arg1 == ENABLED);
3094 handleSetMobileData(enabled);
3095 break;
3096 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003097 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003098 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003099 break;
3100 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003101 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003102 boolean met = (msg.arg1 == ENABLED);
3103 handleSetDependencyMet(msg.arg2, met);
3104 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003105 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003106 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003107 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003108 sendStickyBroadcast(intent);
3109 break;
3110 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003111 case EVENT_SET_POLICY_DATA_ENABLE: {
3112 final int networkType = msg.arg1;
3113 final boolean enabled = msg.arg2 == ENABLED;
3114 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003115 break;
3116 }
3117 case EVENT_VPN_STATE_CHANGED: {
3118 if (mLockdownTracker != null) {
3119 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3120 }
3121 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003122 }
Wink Saville690cb182013-06-29 21:10:57 -07003123 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3124 int tag = mEnableFailFastMobileDataTag.get();
3125 if (msg.arg1 == tag) {
3126 MobileDataStateTracker mobileDst =
3127 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3128 if (mobileDst != null) {
3129 mobileDst.setEnableFailFastMobileData(msg.arg2);
3130 }
3131 } else {
3132 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3133 + " != tag:" + tag);
3134 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003135 break;
Wink Saville690cb182013-06-29 21:10:57 -07003136 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003137 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07003138 handleNetworkSamplingTimeout();
3139 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003140 }
Jason Monk445cea82013-10-10 14:02:51 -04003141 case EVENT_PROXY_HAS_CHANGED: {
3142 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3143 break;
3144 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003145 }
3146 }
3147 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003148
3149 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003150 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003151 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003152
3153 if (isTetheringSupported()) {
3154 return mTethering.tether(iface);
3155 } else {
3156 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3157 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003158 }
3159
3160 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003161 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003162 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003163
3164 if (isTetheringSupported()) {
3165 return mTethering.untether(iface);
3166 } else {
3167 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3168 }
3169 }
3170
3171 // javadoc from interface
3172 public int getLastTetherError(String iface) {
3173 enforceTetherAccessPermission();
3174
3175 if (isTetheringSupported()) {
3176 return mTethering.getLastTetherError(iface);
3177 } else {
3178 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3179 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003180 }
3181
3182 // TODO - proper iface API for selection by property, inspection, etc
3183 public String[] getTetherableUsbRegexs() {
3184 enforceTetherAccessPermission();
3185 if (isTetheringSupported()) {
3186 return mTethering.getTetherableUsbRegexs();
3187 } else {
3188 return new String[0];
3189 }
3190 }
3191
3192 public String[] getTetherableWifiRegexs() {
3193 enforceTetherAccessPermission();
3194 if (isTetheringSupported()) {
3195 return mTethering.getTetherableWifiRegexs();
3196 } else {
3197 return new String[0];
3198 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003199 }
3200
Danica Chang96567052010-08-11 14:54:43 -07003201 public String[] getTetherableBluetoothRegexs() {
3202 enforceTetherAccessPermission();
3203 if (isTetheringSupported()) {
3204 return mTethering.getTetherableBluetoothRegexs();
3205 } else {
3206 return new String[0];
3207 }
3208 }
3209
Mike Lockwooded4a1742011-07-19 13:04:47 -07003210 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08003211 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003212 if (isTetheringSupported()) {
3213 return mTethering.setUsbTethering(enable);
3214 } else {
3215 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3216 }
3217 }
3218
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003219 // TODO - move iface listing, queries, etc to new module
3220 // javadoc from interface
3221 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003222 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003223 return mTethering.getTetherableIfaces();
3224 }
3225
3226 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003227 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003228 return mTethering.getTetheredIfaces();
3229 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003230
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003231 public String[] getTetheringErroredIfaces() {
3232 enforceTetherAccessPermission();
3233 return mTethering.getErroredIfaces();
3234 }
3235
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003236 // if ro.tether.denied = true we default to no tethering
3237 // gservices could set the secure setting to 1 though to enable it on a build where it
3238 // had previously been turned off.
3239 public boolean isTetheringSupported() {
3240 enforceTetherAccessPermission();
3241 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003242 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3243 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003244 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3245 mTethering.getTetherableWifiRegexs().length != 0 ||
3246 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3247 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003248 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003249
3250 // An API NetworkStateTrackers can call when they lose their network.
3251 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3252 // whichever happens first. The timer is started by the first caller and not
3253 // restarted by subsequent callers.
3254 public void requestNetworkTransitionWakelock(String forWhom) {
3255 enforceConnectivityInternalPermission();
3256 synchronized (this) {
3257 if (mNetTransitionWakeLock.isHeld()) return;
3258 mNetTransitionWakeLockSerialNumber++;
3259 mNetTransitionWakeLock.acquire();
3260 mNetTransitionWakeLockCausedBy = forWhom;
3261 }
3262 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003263 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003264 mNetTransitionWakeLockSerialNumber, 0),
3265 mNetTransitionWakeLockTimeout);
3266 return;
3267 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003268
Robert Greenwalt986c7412010-09-08 15:24:47 -07003269 // 100 percent is full good, 0 is full bad.
3270 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003271 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003272 mContext.enforceCallingOrSelfPermission(
3273 android.Manifest.permission.STATUS_BAR,
3274 "ConnectivityService");
3275
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003276 if (DBG) {
3277 int pid = getCallingPid();
3278 int uid = getCallingUid();
3279 String s = pid + "(" + uid + ") reports inet is " +
3280 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3281 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3282 mInetLog.add(s);
3283 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3284 mInetLog.remove(0);
3285 }
3286 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003287 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003288 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3289 }
3290
3291 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003292 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003293 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003294 return;
3295 }
3296 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003297 if (DBG) log("handleInetConditionChange: net=" + netType +
3298 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003299 return;
3300 }
Wink Savillea7d56572011-09-21 11:05:43 -07003301 if (VDBG) {
3302 log("handleInetConditionChange: net=" +
3303 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003304 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003305 }
Wink Saville3e866722013-01-31 00:30:13 +00003306 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003307 int delay;
3308 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003309 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003310 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003311 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003312 delay = Settings.Global.getInt(mContext.getContentResolver(),
3313 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003314 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003315 delay = Settings.Global.getInt(mContext.getContentResolver(),
3316 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003317 }
3318 mInetConditionChangeInFlight = true;
3319 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003320 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003321 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003322 // we've set the new condition, when this hold ends that will get picked up
3323 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003324 }
3325 }
3326
Wink Saville3e866722013-01-31 00:30:13 +00003327 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003328 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003329 log("handleInetConditionHoldEnd: net=" + netType +
3330 ", condition=" + mDefaultInetCondition +
3331 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003332 }
3333 mInetConditionChangeInFlight = false;
3334
3335 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003336 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003337 return;
3338 }
3339 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003340 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003341 return;
3342 }
Wink Saville3e866722013-01-31 00:30:13 +00003343 // TODO: Figure out why this optimization sometimes causes a
3344 // change in mDefaultInetCondition to be missed and the
3345 // UI to not be updated.
3346 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3347 // if (DBG) log("no change in condition - aborting");
3348 // return;
3349 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003350 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3351 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003352 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003353 return;
3354 }
Wink Saville3e866722013-01-31 00:30:13 +00003355 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003356 sendInetConditionBroadcast(networkInfo);
3357 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003358 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003359
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003360 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003361 // this information is already available as a world read/writable jvm property
3362 // so this API change wouldn't have a benifit. It also breaks the passing
3363 // of proxy info to all the JVMs.
3364 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003365 synchronized (mProxyLock) {
Jason Monk43324ee2013-07-03 17:04:33 -04003366 ProxyProperties ret = mGlobalProxy;
3367 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3368 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003369 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003370 }
3371
3372 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003373 enforceConnectivityInternalPermission();
Jason Monk43324ee2013-07-03 17:04:33 -04003374
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003375 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003376 if (proxyProperties == mGlobalProxy) return;
3377 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3378 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3379
3380 String host = "";
3381 int port = 0;
3382 String exclList = "";
Jason Monk43324ee2013-07-03 17:04:33 -04003383 String pacFileUrl = "";
3384 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3385 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003386 if (!proxyProperties.isValid()) {
3387 if (DBG)
3388 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3389 return;
3390 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003391 mGlobalProxy = new ProxyProperties(proxyProperties);
3392 host = mGlobalProxy.getHost();
3393 port = mGlobalProxy.getPort();
3394 exclList = mGlobalProxy.getExclusionList();
Jason Monk43324ee2013-07-03 17:04:33 -04003395 if (proxyProperties.getPacFileUrl() != null) {
3396 pacFileUrl = proxyProperties.getPacFileUrl();
3397 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003398 } else {
3399 mGlobalProxy = null;
3400 }
3401 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003402 final long token = Binder.clearCallingIdentity();
3403 try {
3404 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3405 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3406 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3407 exclList);
Jason Monk43324ee2013-07-03 17:04:33 -04003408 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003409 } finally {
3410 Binder.restoreCallingIdentity(token);
3411 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003412 }
3413
3414 if (mGlobalProxy == null) {
3415 proxyProperties = mDefaultProxy;
3416 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003417 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003418 }
3419
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003420 private void loadGlobalProxy() {
3421 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003422 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3423 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3424 String exclList = Settings.Global.getString(res,
3425 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk43324ee2013-07-03 17:04:33 -04003426 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3427 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3428 ProxyProperties proxyProperties;
3429 if (!TextUtils.isEmpty(pacFileUrl)) {
3430 proxyProperties = new ProxyProperties(pacFileUrl);
3431 } else {
3432 proxyProperties = new ProxyProperties(host, port, exclList);
3433 }
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003434 if (!proxyProperties.isValid()) {
3435 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3436 return;
3437 }
3438
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003439 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003440 mGlobalProxy = proxyProperties;
3441 }
3442 }
3443 }
3444
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003445 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003446 // this information is already available as a world read/writable jvm property
3447 // so this API change wouldn't have a benifit. It also breaks the passing
3448 // of proxy info to all the JVMs.
3449 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003450 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003451 return mGlobalProxy;
3452 }
3453 }
3454
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003455 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04003456 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3457 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003458 proxy = null;
3459 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003460 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003461 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003462 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwaltcf8c8942013-11-18 09:43:59 -08003463 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003464 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3465 return;
3466 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003467 mDefaultProxy = proxy;
3468
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003469 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003470 if (!mDefaultProxyDisabled) {
3471 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003472 }
3473 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003474 }
3475
3476 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003477 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3478 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003479 if (!TextUtils.isEmpty(proxy)) {
3480 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003481 if (data.length == 0) {
3482 return;
3483 }
3484
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003485 String proxyHost = data[0];
3486 int proxyPort = 8080;
3487 if (data.length > 1) {
3488 try {
3489 proxyPort = Integer.parseInt(data[1]);
3490 } catch (NumberFormatException e) {
3491 return;
3492 }
3493 }
3494 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3495 setGlobalProxy(p);
3496 }
3497 }
3498
3499 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003500 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monkaf9ded02013-08-23 19:21:25 -04003501 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003502 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003503 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003504 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3505 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003506 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003507 final long ident = Binder.clearCallingIdentity();
3508 try {
3509 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3510 } finally {
3511 Binder.restoreCallingIdentity(ident);
3512 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003513 }
3514
3515 private static class SettingsObserver extends ContentObserver {
3516 private int mWhat;
3517 private Handler mHandler;
3518 SettingsObserver(Handler handler, int what) {
3519 super(handler);
3520 mHandler = handler;
3521 mWhat = what;
3522 }
3523
3524 void observe(Context context) {
3525 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003526 resolver.registerContentObserver(Settings.Global.getUriFor(
3527 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003528 }
3529
3530 @Override
3531 public void onChange(boolean selfChange) {
3532 mHandler.obtainMessage(mWhat).sendToTarget();
3533 }
3534 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003535
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003536 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003537 Slog.d(TAG, s);
3538 }
3539
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003540 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003541 Slog.e(TAG, s);
3542 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003543
repo syncf5de5572011-07-29 23:55:49 -07003544 int convertFeatureToNetworkType(int networkType, String feature) {
3545 int usedNetworkType = networkType;
3546
3547 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3548 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3549 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3550 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3551 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3552 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3553 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3554 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3555 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3556 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3557 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3558 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3559 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3560 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3561 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3562 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3563 } else {
3564 Slog.e(TAG, "Can't match any mobile netTracker!");
3565 }
3566 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3567 if (TextUtils.equals(feature, "p2p")) {
3568 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3569 } else {
3570 Slog.e(TAG, "Can't match any wifi netTracker!");
3571 }
3572 } else {
3573 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003574 }
repo syncf5de5572011-07-29 23:55:49 -07003575 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003576 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003577
3578 private static <T> T checkNotNull(T value, String message) {
3579 if (value == null) {
3580 throw new NullPointerException(message);
3581 }
3582 return value;
3583 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003584
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003585 /**
3586 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003587 * VpnBuilder and not available in ConnectivityManager. Permissions
3588 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003589 * @hide
3590 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003591 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003592 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003593 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003594 try {
3595 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003596 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003597 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003598 synchronized(mVpns) {
3599 mVpns.get(user).protect(socket,
3600 mNetTrackers[type].getLinkProperties().getInterfaceName());
3601 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003602 return true;
3603 }
3604 } catch (Exception e) {
3605 // ignore
3606 } finally {
3607 try {
3608 socket.close();
3609 } catch (Exception e) {
3610 // ignore
3611 }
3612 }
3613 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003614 }
3615
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003616 /**
3617 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003618 * and not available in ConnectivityManager. Permissions are checked
3619 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003620 * @hide
3621 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003622 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003623 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003624 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003625 int user = UserHandle.getUserId(Binder.getCallingUid());
3626 synchronized(mVpns) {
3627 return mVpns.get(user).prepare(oldPackage, newPackage);
3628 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003629 }
3630
Chad Brubaker31de0b62013-07-11 13:29:30 -07003631 @Override
3632 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3633 enforceMarkNetworkSocketPermission();
3634 final long token = Binder.clearCallingIdentity();
3635 try {
3636 int mark = mNetd.getMarkForUid(uid);
3637 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3638 if (mark == -1) {
3639 mark = 0;
3640 }
3641 NetworkUtils.markSocket(socket.getFd(), mark);
3642 } catch (RemoteException e) {
3643 } finally {
3644 Binder.restoreCallingIdentity(token);
3645 }
3646 }
3647
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003648 /**
3649 * Configure a TUN interface and return its file descriptor. Parameters
3650 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003651 * and not available in ConnectivityManager. Permissions are checked in
3652 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003653 * @hide
3654 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003655 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003656 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003657 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003658 int user = UserHandle.getUserId(Binder.getCallingUid());
3659 synchronized(mVpns) {
3660 return mVpns.get(user).establish(config);
3661 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003662 }
3663
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003664 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003665 * Start legacy VPN, controlling native daemons as needed. Creates a
3666 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003667 */
3668 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003669 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003670 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003671 final LinkProperties egress = getActiveLinkProperties();
3672 if (egress == null) {
3673 throw new IllegalStateException("Missing active network connection");
3674 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003675 int user = UserHandle.getUserId(Binder.getCallingUid());
3676 synchronized(mVpns) {
3677 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3678 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003679 }
3680
3681 /**
3682 * Return the information of the ongoing legacy VPN. This method is used
3683 * by VpnSettings and not available in ConnectivityManager. Permissions
3684 * are checked in Vpn class.
3685 * @hide
3686 */
3687 @Override
3688 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003689 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003690 int user = UserHandle.getUserId(Binder.getCallingUid());
3691 synchronized(mVpns) {
3692 return mVpns.get(user).getLegacyVpnInfo();
3693 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003694 }
3695
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003696 /**
Chad Brubaker7dcfa2a2013-07-16 18:59:12 -07003697 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3698 * not available in ConnectivityManager.
3699 * Permissions are checked in Vpn class.
3700 * @hide
3701 */
3702 @Override
3703 public VpnConfig getVpnConfig() {
3704 int user = UserHandle.getUserId(Binder.getCallingUid());
3705 synchronized(mVpns) {
3706 return mVpns.get(user).getVpnConfig();
3707 }
3708 }
3709
3710 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003711 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3712 * through NetworkStateTracker since it works differently. For example, it
3713 * needs to override DNS servers but never takes the default routes. It
3714 * relies on another data network, and it could keep existing connections
3715 * alive after reconnecting, switching between networks, or even resuming
3716 * from deep sleep. Calls from applications should be done synchronously
3717 * to avoid race conditions. As these are all hidden APIs, refactoring can
3718 * be done whenever a better abstraction is developed.
3719 */
3720 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003721 private VpnCallback() {
3722 }
3723
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003724 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003725 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003726 }
3727
Chad Brubakerccae0d32013-06-14 11:16:51 -07003728 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003729 if (dnsServers == null) {
3730 restore();
3731 return;
3732 }
3733
3734 // Convert DNS servers into addresses.
3735 List<InetAddress> addresses = new ArrayList<InetAddress>();
3736 for (String address : dnsServers) {
3737 // Double check the addresses and remove invalid ones.
3738 try {
3739 addresses.add(InetAddress.parseNumericAddress(address));
3740 } catch (Exception e) {
3741 // ignore
3742 }
3743 }
3744 if (addresses.isEmpty()) {
3745 restore();
3746 return;
3747 }
3748
3749 // Concatenate search domains into a string.
3750 StringBuilder buffer = new StringBuilder();
3751 if (searchDomains != null) {
3752 for (String domain : searchDomains) {
3753 buffer.append(domain).append(' ');
3754 }
3755 }
3756 String domains = buffer.toString().trim();
3757
3758 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003759 synchronized (mDnsLock) {
Chad Brubaker45e721f2013-07-23 17:13:36 -07003760 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003761 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003762
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003763 // Temporarily disable the default proxy (not global).
3764 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003765 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003766 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003767 sendProxyBroadcast(null);
3768 }
3769 }
3770
3771 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003772 }
3773
Chia-chi Yehcc844502011-07-14 18:01:57 -07003774 public void restore() {
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003775 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003776 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003777 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003778 sendProxyBroadcast(mDefaultProxy);
3779 }
3780 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003781 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003782
3783 public void protect(ParcelFileDescriptor socket) {
3784 try {
3785 final int mark = mNetd.getMarkForProtect();
3786 NetworkUtils.markSocket(socket.getFd(), mark);
3787 } catch (RemoteException e) {
3788 }
3789 }
3790
3791 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3792 for (RouteInfo route : routes) {
3793 try {
3794 mNetd.setMarkedForwardingRoute(interfaze, route);
3795 } catch (RemoteException e) {
3796 }
3797 }
3798 }
3799
3800 public void setMarkedForwarding(String interfaze) {
3801 try {
3802 mNetd.setMarkedForwarding(interfaze);
3803 } catch (RemoteException e) {
3804 }
3805 }
3806
3807 public void clearMarkedForwarding(String interfaze) {
3808 try {
3809 mNetd.clearMarkedForwarding(interfaze);
3810 } catch (RemoteException e) {
3811 }
3812 }
3813
Robert Greenwalt68534c82013-09-24 11:05:57 -07003814 public void addUserForwarding(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 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003818 }
3819
Robert Greenwalt68534c82013-09-24 11:05:57 -07003820 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003821 int uidStart = uid * UserHandle.PER_USER_RANGE;
3822 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003823 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003824 }
3825
Robert Greenwalt68534c82013-09-24 11:05:57 -07003826 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3827 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003828 try {
3829 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003830 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003831 } catch (RemoteException e) {
3832 }
3833
3834 }
3835
Robert Greenwalt68534c82013-09-24 11:05:57 -07003836 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3837 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003838 try {
3839 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003840 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003841 } catch (RemoteException e) {
3842 }
3843
3844 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003845 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003846
3847 @Override
3848 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003849 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3850 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3851 return false;
3852 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003853
3854 // Tear down existing lockdown if profile was removed
3855 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3856 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003857 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003858 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3859 return false;
3860 }
3861
3862 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3863 final VpnProfile profile = VpnProfile.decode(
3864 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerccae0d32013-06-14 11:16:51 -07003865 int user = UserHandle.getUserId(Binder.getCallingUid());
3866 synchronized(mVpns) {
3867 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3868 profile));
3869 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003870 } else {
3871 setLockdownTracker(null);
3872 }
3873
3874 return true;
3875 }
3876
3877 /**
3878 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3879 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3880 */
3881 private void setLockdownTracker(LockdownVpnTracker tracker) {
3882 // Shutdown any existing tracker
3883 final LockdownVpnTracker existing = mLockdownTracker;
3884 mLockdownTracker = null;
3885 if (existing != null) {
3886 existing.shutdown();
3887 }
3888
3889 try {
3890 if (tracker != null) {
3891 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003892 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003893 mLockdownTracker = tracker;
3894 mLockdownTracker.init();
3895 } else {
3896 mNetd.setFirewallEnabled(false);
3897 }
3898 } catch (RemoteException e) {
3899 // ignored; NMS lives inside system_server
3900 }
3901 }
3902
3903 private void throwIfLockdownEnabled() {
3904 if (mLockdownEnabled) {
3905 throw new IllegalStateException("Unavailable in lockdown mode");
3906 }
3907 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003908
3909 public void supplyMessenger(int networkType, Messenger messenger) {
3910 enforceConnectivityInternalPermission();
3911
3912 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3913 mNetTrackers[networkType].supplyMessenger(messenger);
3914 }
3915 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003916
3917 public int findConnectionTypeForIface(String iface) {
3918 enforceConnectivityInternalPermission();
3919
3920 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3921 for (NetworkStateTracker tracker : mNetTrackers) {
3922 if (tracker != null) {
3923 LinkProperties lp = tracker.getLinkProperties();
3924 if (lp != null && iface.equals(lp.getInterfaceName())) {
3925 return tracker.getNetworkInfo().getType();
3926 }
3927 }
3928 }
3929 return ConnectivityManager.TYPE_NONE;
3930 }
Wink Saville690cb182013-06-29 21:10:57 -07003931
3932 /**
3933 * Have mobile data fail fast if enabled.
3934 *
3935 * @param enabled DctConstants.ENABLED/DISABLED
3936 */
3937 private void setEnableFailFastMobileData(int enabled) {
3938 int tag;
3939
3940 if (enabled == DctConstants.ENABLED) {
3941 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3942 } else {
3943 tag = mEnableFailFastMobileDataTag.get();
3944 }
3945 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3946 enabled));
3947 }
3948
Wink Savillebc588402013-08-16 17:17:28 -07003949 private boolean isMobileDataStateTrackerReady() {
3950 MobileDataStateTracker mdst =
Wink Saville89c87b92013-08-29 08:55:16 -07003951 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savillebc588402013-08-16 17:17:28 -07003952 return (mdst != null) && (mdst.isReady());
3953 }
3954
Wink Saville89c87b92013-08-29 08:55:16 -07003955 /**
3956 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3957 */
3958
3959 /**
3960 * No connection was possible to the network.
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_NO_CONNECTION = 0;
Wink Saville89c87b92013-08-29 08:55:16 -07003964
3965 /**
3966 * A connection was made to the internet, all is well.
Wink Savillea3041492013-09-06 09:53:08 -07003967 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003968 */
Wink Savillea3041492013-09-06 09:53:08 -07003969 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville89c87b92013-08-29 08:55:16 -07003970
3971 /**
3972 * A connection was made but no dns server was available to resolve a name to address.
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_DNS = 2;
Wink Saville89c87b92013-08-29 08:55:16 -07003976
3977 /**
3978 * A connection was made but could not open a TCP connection.
Wink Savillea3041492013-09-06 09:53:08 -07003979 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003980 */
Wink Savillea3041492013-09-06 09:53:08 -07003981 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3982
3983 /**
3984 * A connection was made but there was a redirection, we appear to be in walled garden.
3985 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3986 */
3987 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville89c87b92013-08-29 08:55:16 -07003988
3989 /**
3990 * The mobile network is a provisioning network.
Wink Savillea3041492013-09-06 09:53:08 -07003991 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville89c87b92013-08-29 08:55:16 -07003992 */
Wink Savillea3041492013-09-06 09:53:08 -07003993 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville89c87b92013-08-29 08:55:16 -07003994
Wink Savillea3041492013-09-06 09:53:08 -07003995 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville89c87b92013-08-29 08:55:16 -07003996
Wink Saville690cb182013-06-29 21:10:57 -07003997 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07003998 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3999 int timeOutMs = -1;
4000 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4001 enforceConnectivityInternalPermission();
Wink Savillefdb84862013-07-02 10:55:14 -07004002
Wink Saville690cb182013-06-29 21:10:57 -07004003 final long token = Binder.clearCallingIdentity();
4004 try {
Wink Saville89c87b92013-08-29 08:55:16 -07004005 timeOutMs = suggestedTimeOutMs;
4006 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4007 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4008 }
4009
4010 // Check that mobile networks are supported
4011 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4012 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4013 if (DBG) log("checkMobileProvisioning: X no mobile network");
4014 return timeOutMs;
4015 }
4016
4017 // If we're already checking don't do it again
4018 // TODO: Add a queue of results...
4019 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4020 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4021 return timeOutMs;
4022 }
4023
Wink Savillea65f4732013-10-03 08:34:46 -07004024 // Start off with mobile notification off
4025 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004026
Wink Saville690cb182013-06-29 21:10:57 -07004027 CheckMp checkMp = new CheckMp(mContext, this);
4028 CheckMp.CallBack cb = new CheckMp.CallBack() {
4029 @Override
4030 void onComplete(Integer result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004031 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004032 NetworkInfo ni =
4033 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4034 switch(result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004035 case CMP_RESULT_CODE_CONNECTABLE:
Wink Savillea3041492013-09-06 09:53:08 -07004036 case CMP_RESULT_CODE_NO_CONNECTION:
4037 case CMP_RESULT_CODE_NO_DNS:
4038 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville89c87b92013-08-29 08:55:16 -07004039 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville690cb182013-06-29 21:10:57 -07004040 break;
4041 }
Wink Saville89c87b92013-08-29 08:55:16 -07004042 case CMP_RESULT_CODE_REDIRECTED: {
4043 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004044 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004045 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004046 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004047 }
4048 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004049 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004050 setProvNotificationVisible(true,
4051 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004052 url);
Wink Saville690cb182013-06-29 21:10:57 -07004053 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004054 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004055 }
4056 break;
4057 }
Wink Savillea3041492013-09-06 09:53:08 -07004058 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004059 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004060 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004061 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004062 setProvNotificationVisible(true,
4063 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004064 url);
Wink Saville690cb182013-06-29 21:10:57 -07004065 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004066 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004067 }
4068 break;
4069 }
4070 default: {
4071 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4072 break;
4073 }
4074 }
Wink Saville89c87b92013-08-29 08:55:16 -07004075 mIsCheckingMobileProvisioning.set(false);
Wink Saville690cb182013-06-29 21:10:57 -07004076 }
4077 };
4078 CheckMp.Params params =
4079 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville89c87b92013-08-29 08:55:16 -07004080 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville690cb182013-06-29 21:10:57 -07004081 checkMp.execute(params);
4082 } finally {
4083 Binder.restoreCallingIdentity(token);
Wink Saville89c87b92013-08-29 08:55:16 -07004084 if (DBG) log("checkMobileProvisioning: X");
Wink Saville690cb182013-06-29 21:10:57 -07004085 }
4086 return timeOutMs;
4087 }
4088
4089 static class CheckMp extends
4090 AsyncTask<CheckMp.Params, Void, Integer> {
4091 private static final String CHECKMP_TAG = "CheckMp";
Wink Saville8fe05f12013-10-31 06:35:22 -07004092
4093 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4094 private static boolean mTestingFailures;
4095
4096 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4097 private static final int MAX_LOOPS = 4;
4098
4099 // Number of milli-seconds to complete all of the retires
Wink Saville690cb182013-06-29 21:10:57 -07004100 public static final int MAX_TIMEOUT_MS = 60000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004101
4102 // The socket should retry only 5 seconds, the default is longer
Wink Saville690cb182013-06-29 21:10:57 -07004103 private static final int SOCKET_TIMEOUT_MS = 5000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004104
4105 // Sleep time for network errors
4106 private static final int NET_ERROR_SLEEP_SEC = 3;
4107
4108 // Sleep time for network route establishment
4109 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4110
4111 // Short sleep time for polling :(
4112 private static final int POLLING_SLEEP_SEC = 1;
4113
Wink Saville690cb182013-06-29 21:10:57 -07004114 private Context mContext;
4115 private ConnectivityService mCs;
4116 private TelephonyManager mTm;
4117 private Params mParams;
4118
4119 /**
4120 * Parameters for AsyncTask.execute
4121 */
4122 static class Params {
4123 private String mUrl;
4124 private long mTimeOutMs;
4125 private CallBack mCb;
4126
4127 Params(String url, long timeOutMs, CallBack cb) {
4128 mUrl = url;
4129 mTimeOutMs = timeOutMs;
4130 mCb = cb;
4131 }
4132
4133 @Override
4134 public String toString() {
4135 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4136 }
4137 }
4138
Wink Saville8fe05f12013-10-31 06:35:22 -07004139 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4140 // issued by name or ip address, for Google its by name so when we construct
4141 // this HostnameVerifier we'll pass the original Uri and use it to verify
4142 // the host. If the host name in the original uril fails we'll test the
4143 // hostname parameter just incase things change.
4144 static class CheckMpHostnameVerifier implements HostnameVerifier {
4145 Uri mOrgUri;
4146
4147 CheckMpHostnameVerifier(Uri orgUri) {
4148 mOrgUri = orgUri;
4149 }
4150
4151 @Override
4152 public boolean verify(String hostname, SSLSession session) {
4153 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4154 String orgUriHost = mOrgUri.getHost();
4155 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4156 if (DBG) {
4157 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4158 + " orgUriHost=" + orgUriHost);
4159 }
4160 return retVal;
4161 }
4162 }
4163
Wink Saville690cb182013-06-29 21:10:57 -07004164 /**
4165 * The call back object passed in Params. onComplete will be called
4166 * on the main thread.
4167 */
4168 abstract static class CallBack {
4169 // Called on the main thread.
4170 abstract void onComplete(Integer result);
4171 }
4172
4173 public CheckMp(Context context, ConnectivityService cs) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004174 if (Build.IS_DEBUGGABLE) {
4175 mTestingFailures =
4176 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4177 } else {
4178 mTestingFailures = false;
4179 }
4180
Wink Saville690cb182013-06-29 21:10:57 -07004181 mContext = context;
4182 mCs = cs;
4183
4184 // Setup access to TelephonyService we'll be using.
4185 mTm = (TelephonyManager) mContext.getSystemService(
4186 Context.TELEPHONY_SERVICE);
4187 }
4188
4189 /**
4190 * Get the default url to use for the test.
4191 */
4192 public String getDefaultUrl() {
4193 // See http://go/clientsdns for usage approval
4194 String server = Settings.Global.getString(mContext.getContentResolver(),
4195 Settings.Global.CAPTIVE_PORTAL_SERVER);
4196 if (server == null) {
4197 server = "clients3.google.com";
4198 }
4199 return "http://" + server + "/generate_204";
4200 }
4201
4202 /**
4203 * Detect if its possible to connect to the http url. DNS based detection techniques
4204 * do not work at all hotspots. The best way to check is to perform a request to
4205 * a known address that fetches the data we expect.
4206 */
4207 private synchronized Integer isMobileOk(Params params) {
Wink Saville89c87b92013-08-29 08:55:16 -07004208 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004209 Uri orgUri = Uri.parse(params.mUrl);
4210 Random rand = new Random();
4211 mParams = params;
4212
Wink Saville37e73122013-08-13 12:41:06 -07004213 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004214 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville39856712013-09-13 12:40:11 -07004215 log("isMobileOk: X not mobile capable result=" + result);
4216 return result;
4217 }
4218
4219 // See if we've already determined we've got a provisioning connection,
4220 // if so we don't need to do anything active.
4221 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4222 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4223 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4224 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4225
4226 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4227 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4228 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4229 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4230
4231 if (isDefaultProvisioning || isHipriProvisioning) {
4232 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4233 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville37e73122013-08-13 12:41:06 -07004234 return result;
4235 }
Wink Saville690cb182013-06-29 21:10:57 -07004236
Wink Saville37e73122013-08-13 12:41:06 -07004237 try {
Wink Saville690cb182013-06-29 21:10:57 -07004238 // Continue trying to connect until time has run out
4239 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville4a165bb2013-08-07 11:02:57 -07004240
Wink Savillebc588402013-08-16 17:17:28 -07004241 if (!mCs.isMobileDataStateTrackerReady()) {
4242 // Wait for MobileDataStateTracker to be ready.
4243 if (DBG) log("isMobileOk: mdst is not ready");
4244 while(SystemClock.elapsedRealtime() < endTime) {
4245 if (mCs.isMobileDataStateTrackerReady()) {
4246 // Enable fail fast as we'll do retries here and use a
4247 // hipri connection so the default connection stays active.
4248 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4249 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4250 break;
4251 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004252 sleep(POLLING_SLEEP_SEC);
Wink Savillebc588402013-08-16 17:17:28 -07004253 }
4254 }
4255
4256 log("isMobileOk: start hipri url=" + params.mUrl);
4257
Wink Saville4a165bb2013-08-07 11:02:57 -07004258 // First wait until we can start using hipri
4259 Binder binder = new Binder();
4260 while(SystemClock.elapsedRealtime() < endTime) {
4261 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4262 Phone.FEATURE_ENABLE_HIPRI, binder);
4263 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4264 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4265 log("isMobileOk: hipri started");
4266 break;
4267 }
4268 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville89c87b92013-08-29 08:55:16 -07004269 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville8fe05f12013-10-31 06:35:22 -07004270 sleep(POLLING_SLEEP_SEC);
Wink Saville4a165bb2013-08-07 11:02:57 -07004271 }
4272
4273 // Continue trying to connect until time has run out
Wink Saville690cb182013-06-29 21:10:57 -07004274 while(SystemClock.elapsedRealtime() < endTime) {
4275 try {
4276 // Wait for hipri to connect.
4277 // TODO: Don't poll and handle situation where hipri fails
4278 // because default is retrying. See b/9569540
4279 NetworkInfo.State state = mCs
4280 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4281 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville89c87b92013-08-29 08:55:16 -07004282 if (true/*VDBG*/) {
Wink Saville27f92732013-07-31 15:49:04 -07004283 log("isMobileOk: not connected ni=" +
Wink Saville690cb182013-06-29 21:10:57 -07004284 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville27f92732013-07-31 15:49:04 -07004285 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004286 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004287 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004288 continue;
4289 }
4290
Wink Saville89c87b92013-08-29 08:55:16 -07004291 // Hipri has started check if this is a provisioning url
4292 MobileDataStateTracker mdst = (MobileDataStateTracker)
4293 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4294 if (mdst.isProvisioningNetwork()) {
Wink Savillea3041492013-09-06 09:53:08 -07004295 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville39856712013-09-13 12:40:11 -07004296 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville89c87b92013-08-29 08:55:16 -07004297 return result;
4298 } else {
4299 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4300 }
4301
Wink Saville690cb182013-06-29 21:10:57 -07004302 // Get of the addresses associated with the url host. We need to use the
4303 // address otherwise HttpURLConnection object will use the name to get
Wink Saville8fe05f12013-10-31 06:35:22 -07004304 // the addresses and will try every address but that will bypass the
Wink Saville690cb182013-06-29 21:10:57 -07004305 // route to host we setup and the connection could succeed as the default
4306 // interface might be connected to the internet via wifi or other interface.
4307 InetAddress[] addresses;
4308 try {
4309 addresses = InetAddress.getAllByName(orgUri.getHost());
4310 } catch (UnknownHostException e) {
Wink Saville89c87b92013-08-29 08:55:16 -07004311 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville39856712013-09-13 12:40:11 -07004312 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004313 return result;
4314 }
4315 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4316
4317 // Get the type of addresses supported by this link
4318 LinkProperties lp = mCs.getLinkProperties(
4319 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti662b96c2013-08-08 11:00:12 +09004320 boolean linkHasIpv4 = lp.hasIPv4Address();
4321 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville690cb182013-06-29 21:10:57 -07004322 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4323 + " linkHasIpv6=" + linkHasIpv6);
4324
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004325 final ArrayList<InetAddress> validAddresses =
4326 new ArrayList<InetAddress>(addresses.length);
Wink Saville690cb182013-06-29 21:10:57 -07004327
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004328 for (InetAddress addr : addresses) {
4329 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4330 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4331 validAddresses.add(addr);
Wink Saville690cb182013-06-29 21:10:57 -07004332 }
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004333 }
4334
4335 if (validAddresses.size() == 0) {
4336 return CMP_RESULT_CODE_NO_CONNECTION;
4337 }
4338
4339 int addrTried = 0;
4340 while (true) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004341 // Loop through at most MAX_LOOPS valid addresses or until
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004342 // we run out of time
Wink Saville8fe05f12013-10-31 06:35:22 -07004343 if (addrTried++ >= MAX_LOOPS) {
4344 log("isMobileOk: too many loops tried - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004345 break;
4346 }
4347 if (SystemClock.elapsedRealtime() >= endTime) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004348 log("isMobileOk: spend too much time - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004349 break;
4350 }
4351
4352 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4353 validAddresses.size()));
Wink Saville690cb182013-06-29 21:10:57 -07004354
4355 // Make a route to host so we check the specific interface.
4356 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4357 hostAddr.getAddress())) {
4358 // Wait a short time to be sure the route is established ??
4359 log("isMobileOk:"
4360 + " wait to establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004361 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004362 } else {
4363 log("isMobileOk:"
4364 + " could not establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004365 // Wait a short time before the next attempt
4366 sleep(NET_ERROR_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004367 continue;
4368 }
4369
Wink Saville8fe05f12013-10-31 06:35:22 -07004370 // Rewrite the url to have numeric address to use the specific route
4371 // using http for half the attempts and https for the other half.
4372 // Doing https first and http second as on a redirected walled garden
4373 // such as t-mobile uses we get a SocketTimeoutException: "SSL
4374 // handshake timed out" which we declare as
4375 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4376 // having http second we will be using logic used for some time.
4377 URL newUrl;
4378 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4379 newUrl = new URL(scheme, hostAddr.getHostAddress(),
4380 orgUri.getPath());
Wink Saville690cb182013-06-29 21:10:57 -07004381 log("isMobileOk: newUrl=" + newUrl);
4382
4383 HttpURLConnection urlConn = null;
4384 try {
Wink Saville8fe05f12013-10-31 06:35:22 -07004385 // Open the connection set the request headers and get the response
4386 urlConn = (HttpURLConnection)newUrl.openConnection(
Wink Saville690cb182013-06-29 21:10:57 -07004387 java.net.Proxy.NO_PROXY);
Wink Saville8fe05f12013-10-31 06:35:22 -07004388 if (scheme.equals("https")) {
4389 ((HttpsURLConnection)urlConn).setHostnameVerifier(
4390 new CheckMpHostnameVerifier(orgUri));
4391 }
Wink Saville690cb182013-06-29 21:10:57 -07004392 urlConn.setInstanceFollowRedirects(false);
4393 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4394 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4395 urlConn.setUseCaches(false);
4396 urlConn.setAllowUserInteraction(false);
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004397 // Set the "Connection" to "Close" as by default "Keep-Alive"
4398 // is used which is useless in this case.
Wink Saville690cb182013-06-29 21:10:57 -07004399 urlConn.setRequestProperty("Connection", "close");
4400 int responseCode = urlConn.getResponseCode();
Wink Savillea3041492013-09-06 09:53:08 -07004401
4402 // For debug display the headers
4403 Map<String, List<String>> headers = urlConn.getHeaderFields();
4404 log("isMobileOk: headers=" + headers);
4405
4406 // Close the connection
Wink Saville690cb182013-06-29 21:10:57 -07004407 urlConn.disconnect();
4408 urlConn = null;
Wink Savillea3041492013-09-06 09:53:08 -07004409
Wink Saville8fe05f12013-10-31 06:35:22 -07004410 if (mTestingFailures) {
4411 // Pretend no connection, this tests using http and https
4412 result = CMP_RESULT_CODE_NO_CONNECTION;
4413 log("isMobileOk: TESTING_FAILURES, pretend no connction");
4414 continue;
4415 }
4416
Wink Savillea3041492013-09-06 09:53:08 -07004417 if (responseCode == 204) {
4418 // Return
Wink Savillea3041492013-09-06 09:53:08 -07004419 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville8fe05f12013-10-31 06:35:22 -07004420 log("isMobileOk: X got expected responseCode=" + responseCode
Wink Saville39856712013-09-13 12:40:11 -07004421 + " result=" + result);
Wink Savillea3041492013-09-06 09:53:08 -07004422 return result;
4423 } else {
4424 // Retry to be sure this was redirected, we've gotten
4425 // occasions where a server returned 200 even though
4426 // the device didn't have a "warm" sim.
4427 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004428 // TODO - it would be nice in the single-address case to do
4429 // another DNS resolve here, but flushing the cache is a bit
4430 // heavy-handed.
Wink Savillea3041492013-09-06 09:53:08 -07004431 result = CMP_RESULT_CODE_REDIRECTED;
4432 }
Wink Saville690cb182013-06-29 21:10:57 -07004433 } catch (Exception e) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004434 log("isMobileOk: HttpURLConnection Exception" + e);
Wink Savillea3041492013-09-06 09:53:08 -07004435 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004436 if (urlConn != null) {
4437 urlConn.disconnect();
4438 urlConn = null;
4439 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004440 sleep(NET_ERROR_SLEEP_SEC);
4441 continue;
Wink Saville690cb182013-06-29 21:10:57 -07004442 }
4443 }
Wink Saville39856712013-09-13 12:40:11 -07004444 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004445 return result;
4446 } catch (Exception e) {
4447 log("isMobileOk: Exception e=" + e);
4448 continue;
4449 }
4450 }
4451 log("isMobileOk: timed out");
4452 } finally {
4453 log("isMobileOk: F stop hipri");
4454 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4455 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4456 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville89c87b92013-08-29 08:55:16 -07004457
4458 // Wait for hipri to disconnect.
4459 long endTime = SystemClock.elapsedRealtime() + 5000;
4460
4461 while(SystemClock.elapsedRealtime() < endTime) {
4462 NetworkInfo.State state = mCs
4463 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4464 if (state != NetworkInfo.State.DISCONNECTED) {
4465 if (VDBG) {
4466 log("isMobileOk: connected ni=" +
4467 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4468 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004469 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004470 continue;
4471 }
4472 }
4473
Wink Saville690cb182013-06-29 21:10:57 -07004474 log("isMobileOk: X result=" + result);
4475 }
4476 return result;
4477 }
4478
4479 @Override
4480 protected Integer doInBackground(Params... params) {
4481 return isMobileOk(params[0]);
4482 }
4483
4484 @Override
4485 protected void onPostExecute(Integer result) {
4486 log("onPostExecute: result=" + result);
4487 if ((mParams != null) && (mParams.mCb != null)) {
4488 mParams.mCb.onComplete(result);
4489 }
4490 }
4491
4492 private String inetAddressesToString(InetAddress[] addresses) {
4493 StringBuffer sb = new StringBuffer();
4494 boolean firstTime = true;
4495 for(InetAddress addr : addresses) {
4496 if (firstTime) {
4497 firstTime = false;
4498 } else {
4499 sb.append(",");
4500 }
4501 sb.append(addr);
4502 }
4503 return sb.toString();
4504 }
4505
4506 private void printNetworkInfo() {
4507 boolean hasIccCard = mTm.hasIccCard();
4508 int simState = mTm.getSimState();
4509 log("hasIccCard=" + hasIccCard
4510 + " simState=" + simState);
4511 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4512 if (ni != null) {
4513 log("ni.length=" + ni.length);
4514 for (NetworkInfo netInfo: ni) {
4515 log("netInfo=" + netInfo.toString());
4516 }
4517 } else {
4518 log("no network info ni=null");
4519 }
4520 }
4521
4522 /**
4523 * Sleep for a few seconds then return.
4524 * @param seconds
4525 */
4526 private static void sleep(int seconds) {
4527 try {
4528 Thread.sleep(seconds * 1000);
4529 } catch (InterruptedException e) {
4530 e.printStackTrace();
4531 }
4532 }
4533
Wink Saville8fe05f12013-10-31 06:35:22 -07004534 private static void log(String s) {
Wink Saville690cb182013-06-29 21:10:57 -07004535 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4536 }
4537 }
4538
Wink Saville89c87b92013-08-29 08:55:16 -07004539 // TODO: Move to ConnectivityManager and make public?
4540 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4541 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville690cb182013-06-29 21:10:57 -07004542
Wink Saville89c87b92013-08-29 08:55:16 -07004543 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4544 @Override
4545 public void onReceive(Context context, Intent intent) {
4546 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4547 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4548 }
4549 }
4550 };
4551
4552 private void handleMobileProvisioningAction(String url) {
4553 // Notication mark notification as not visible
Wink Savillea65f4732013-10-03 08:34:46 -07004554 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004555
4556 // If provisioning network handle as a special case,
4557 // otherwise launch browser with the intent directly.
4558 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville860f5282013-09-05 12:02:25 -07004559 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07004560 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4561 MobileDataStateTracker mdst = (MobileDataStateTracker)
4562 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4563 mdst.enableMobileProvisioning(url);
4564 } else {
4565 if (DBG) log("handleMobileProvisioningAction: on default network");
Robert Greenwaltac8d55a2013-10-17 12:46:52 -07004566 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4567 Intent.CATEGORY_APP_BROWSER);
4568 newIntent.setData(Uri.parse(url));
Wink Saville89c87b92013-08-29 08:55:16 -07004569 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4570 Intent.FLAG_ACTIVITY_NEW_TASK);
4571 try {
4572 mContext.startActivity(newIntent);
4573 } catch (ActivityNotFoundException e) {
4574 loge("handleMobileProvisioningAction: startActivity failed" + e);
4575 }
4576 }
4577 }
4578
4579 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4580 private volatile boolean mIsNotificationVisible = false;
4581
4582 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4583 String url) {
4584 if (DBG) {
4585 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4586 + " extraInfo=" + extraInfo + " url=" + url);
4587 }
Wink Saville690cb182013-06-29 21:10:57 -07004588
4589 Resources r = Resources.getSystem();
4590 NotificationManager notificationManager = (NotificationManager) mContext
4591 .getSystemService(Context.NOTIFICATION_SERVICE);
4592
4593 if (visible) {
4594 CharSequence title;
4595 CharSequence details;
4596 int icon;
Wink Saville89c87b92013-08-29 08:55:16 -07004597 Intent intent;
4598 Notification notification = new Notification();
4599 switch (networkType) {
Wink Saville690cb182013-06-29 21:10:57 -07004600 case ConnectivityManager.TYPE_WIFI:
Wink Saville690cb182013-06-29 21:10:57 -07004601 title = r.getString(R.string.wifi_available_sign_in, 0);
4602 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004603 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004604 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004605 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4606 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4607 Intent.FLAG_ACTIVITY_NEW_TASK);
4608 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004609 break;
4610 case ConnectivityManager.TYPE_MOBILE:
4611 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville690cb182013-06-29 21:10:57 -07004612 title = r.getString(R.string.network_available_sign_in, 0);
4613 // TODO: Change this to pull from NetworkInfo once a printable
4614 // name has been added to it
4615 details = mTelephonyManager.getNetworkOperatorName();
4616 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004617 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4618 intent.putExtra("EXTRA_URL", url);
4619 intent.setFlags(0);
4620 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004621 break;
4622 default:
Wink Saville690cb182013-06-29 21:10:57 -07004623 title = r.getString(R.string.network_available_sign_in, 0);
4624 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004625 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004626 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004627 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4628 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4629 Intent.FLAG_ACTIVITY_NEW_TASK);
4630 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004631 break;
4632 }
4633
Wink Saville690cb182013-06-29 21:10:57 -07004634 notification.when = 0;
4635 notification.icon = icon;
4636 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville690cb182013-06-29 21:10:57 -07004637 notification.tickerText = title;
4638 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4639
Wink Saville89c87b92013-08-29 08:55:16 -07004640 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004641 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville89c87b92013-08-29 08:55:16 -07004642 } catch (NullPointerException npe) {
4643 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4644 npe.printStackTrace();
4645 }
Wink Saville690cb182013-06-29 21:10:57 -07004646 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004647 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004648 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville89c87b92013-08-29 08:55:16 -07004649 } catch (NullPointerException npe) {
4650 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4651 npe.printStackTrace();
4652 }
Wink Saville690cb182013-06-29 21:10:57 -07004653 }
Wink Saville89c87b92013-08-29 08:55:16 -07004654 mIsNotificationVisible = visible;
Wink Saville690cb182013-06-29 21:10:57 -07004655 }
4656
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004657 /** Location to an updatable file listing carrier provisioning urls.
4658 * An example:
4659 *
4660 * <?xml version="1.0" encoding="utf-8"?>
4661 * <provisioningUrls>
4662 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4663 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4664 * </provisioningUrls>
4665 */
4666 private static final String PROVISIONING_URL_PATH =
4667 "/data/misc/radio/provisioning_urls.xml";
4668 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004669
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004670 /** XML tag for root element. */
4671 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4672 /** XML tag for individual url */
4673 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4674 /** XML tag for redirected url */
4675 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4676 /** XML attribute for mcc */
4677 private static final String ATTR_MCC = "mcc";
4678 /** XML attribute for mnc */
4679 private static final String ATTR_MNC = "mnc";
4680
4681 private static final int REDIRECTED_PROVISIONING = 1;
4682 private static final int PROVISIONING = 2;
4683
4684 private String getProvisioningUrlBaseFromFile(int type) {
4685 FileReader fileReader = null;
4686 XmlPullParser parser = null;
4687 Configuration config = mContext.getResources().getConfiguration();
4688 String tagType;
4689
4690 switch (type) {
4691 case PROVISIONING:
4692 tagType = TAG_PROVISIONING_URL;
4693 break;
4694 case REDIRECTED_PROVISIONING:
4695 tagType = TAG_REDIRECTED_URL;
4696 break;
4697 default:
4698 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4699 type);
4700 }
4701
4702 try {
4703 fileReader = new FileReader(mProvisioningUrlFile);
4704 parser = Xml.newPullParser();
4705 parser.setInput(fileReader);
4706 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4707
4708 while (true) {
4709 XmlUtils.nextElement(parser);
4710
4711 String element = parser.getName();
4712 if (element == null) break;
4713
4714 if (element.equals(tagType)) {
4715 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4716 try {
4717 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4718 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4719 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4720 parser.next();
4721 if (parser.getEventType() == XmlPullParser.TEXT) {
4722 return parser.getText();
4723 }
4724 }
4725 }
4726 } catch (NumberFormatException e) {
4727 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4728 }
4729 }
4730 }
4731 return null;
4732 } catch (FileNotFoundException e) {
4733 loge("Carrier Provisioning Urls file not found");
4734 } catch (XmlPullParserException e) {
4735 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4736 } catch (IOException e) {
4737 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4738 } finally {
4739 if (fileReader != null) {
4740 try {
4741 fileReader.close();
4742 } catch (IOException e) {}
4743 }
4744 }
4745 return null;
4746 }
4747
Wink Savillef714b7f2013-07-20 20:31:59 -07004748 @Override
4749 public String getMobileRedirectedProvisioningUrl() {
4750 enforceConnectivityInternalPermission();
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004751 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4752 if (TextUtils.isEmpty(url)) {
4753 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4754 }
4755 return url;
4756 }
4757
Wink Savillef714b7f2013-07-20 20:31:59 -07004758 @Override
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004759 public String getMobileProvisioningUrl() {
4760 enforceConnectivityInternalPermission();
4761 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4762 if (TextUtils.isEmpty(url)) {
4763 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillef714b7f2013-07-20 20:31:59 -07004764 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004765 } else {
Wink Savillef714b7f2013-07-20 20:31:59 -07004766 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004767 }
Wink Savilledfabd992013-07-10 23:00:07 -07004768 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004769 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004770 String phoneNumber = mTelephonyManager.getLine1Number();
4771 if (TextUtils.isEmpty(phoneNumber)) {
4772 phoneNumber = "0000000000";
4773 }
Wink Saville690cb182013-06-29 21:10:57 -07004774 url = String.format(url,
4775 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4776 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004777 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004778 }
4779
Wink Saville690cb182013-06-29 21:10:57 -07004780 return url;
4781 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004782
Wink Saville89c87b92013-08-29 08:55:16 -07004783 @Override
4784 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4785 String extraInfo, String url) {
4786 enforceConnectivityInternalPermission();
4787 setProvNotificationVisible(visible, networkType, extraInfo, url);
4788 }
Wink Saville3ade4872013-08-29 14:57:08 -07004789
Yuhao Zheng15019892013-09-09 17:00:04 -07004790 @Override
4791 public void setAirplaneMode(boolean enable) {
4792 enforceConnectivityInternalPermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07004793 final long ident = Binder.clearCallingIdentity();
4794 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07004795 final ContentResolver cr = mContext.getContentResolver();
4796 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4797 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4798 intent.putExtra("state", enable);
Yuhao Zheng15019892013-09-09 17:00:04 -07004799 mContext.sendBroadcast(intent);
4800 } finally {
4801 Binder.restoreCallingIdentity(ident);
4802 }
4803 }
4804
Chad Brubakerccae0d32013-06-14 11:16:51 -07004805 private void onUserStart(int userId) {
4806 synchronized(mVpns) {
4807 Vpn userVpn = mVpns.get(userId);
4808 if (userVpn != null) {
4809 loge("Starting user already has a VPN");
4810 return;
4811 }
4812 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4813 mVpns.put(userId, userVpn);
4814 userVpn.startMonitoring(mContext, mTrackerHandler);
4815 }
4816 }
4817
4818 private void onUserStop(int userId) {
4819 synchronized(mVpns) {
4820 Vpn userVpn = mVpns.get(userId);
4821 if (userVpn == null) {
4822 loge("Stopping user has no VPN");
4823 return;
4824 }
4825 mVpns.delete(userId);
4826 }
4827 }
4828
4829 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4830 @Override
4831 public void onReceive(Context context, Intent intent) {
4832 final String action = intent.getAction();
4833 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4834 if (userId == UserHandle.USER_NULL) return;
4835
4836 if (Intent.ACTION_USER_STARTING.equals(action)) {
4837 onUserStart(userId);
4838 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4839 onUserStop(userId);
4840 }
4841 }
4842 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004843
4844 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004845 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004846 enforceAccessPermission();
4847 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004848 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004849 } else {
4850 return null;
4851 }
4852 }
4853
4854 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004855 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004856 enforceAccessPermission();
4857 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004858 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004859 } else {
4860 return null;
4861 }
4862 }
4863
4864 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004865 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004866 enforceAccessPermission();
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004867 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004868 for (NetworkStateTracker tracker : mNetTrackers) {
4869 if (tracker != null) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004870 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004871 if (li != null) {
4872 result.add(li);
4873 }
4874 }
4875 }
4876
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004877 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004878 }
4879
4880 /* Infrastructure for network sampling */
4881
4882 private void handleNetworkSamplingTimeout() {
4883
4884 log("Sampling interval elapsed, updating statistics ..");
4885
4886 // initialize list of interfaces ..
4887 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4888 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4889 for (NetworkStateTracker tracker : mNetTrackers) {
4890 if (tracker != null) {
4891 String ifaceName = tracker.getNetworkInterfaceName();
4892 if (ifaceName != null) {
4893 mapIfaceToSample.put(ifaceName, null);
4894 }
4895 }
4896 }
4897
4898 // Read samples for all interfaces
4899 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4900
4901 // process samples for all networks
4902 for (NetworkStateTracker tracker : mNetTrackers) {
4903 if (tracker != null) {
4904 String ifaceName = tracker.getNetworkInterfaceName();
4905 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4906 if (ss != null) {
4907 // end the previous sampling cycle
4908 tracker.stopSampling(ss);
4909 // start a new sampling cycle ..
4910 tracker.startSampling(ss);
4911 }
4912 }
4913 }
4914
4915 log("Done.");
4916
4917 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4918 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4919 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4920
4921 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4922
4923 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4924 }
4925
4926 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4927 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4928 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4929 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004930}