blob: 594f6831be9fe520eb870fa4bc13c3eee2432c90 [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];
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001570 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001571
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001572 if (tracker == null || (netState != DetailedState.CONNECTED &&
1573 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001574 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001575 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001576 log("requestRouteToHostAddress on down network "
1577 + "(" + networkType + ") - dropped"
1578 + " tracker=" + tracker
1579 + " netState=" + netState
1580 + " isTeardownRequested="
1581 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001582 }
1583 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001584 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001585 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001586 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001587 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001588 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker78850f32013-07-15 16:34:04 -07001589 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville690cb182013-06-29 21:10:57 -07001590 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1591 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001592 } catch (UnknownHostException e) {
1593 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1594 } finally {
1595 Binder.restoreCallingIdentity(token);
1596 }
Wink Saville690cb182013-06-29 21:10:57 -07001597 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001598 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001599 }
1600
Chad Brubaker78850f32013-07-15 16:34:04 -07001601 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1602 boolean exempt) {
1603 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001604 }
1605
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001606 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001607 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001608 }
1609
Chad Brubaker78850f32013-07-15 16:34:04 -07001610 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1611 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001612 }
1613
1614 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001615 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001616 }
1617
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001618 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001619 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001620 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001621 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001622 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001623 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001624 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001625 if (bestRoute.getGateway().equals(addr)) {
1626 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001627 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001628 } else {
1629 // if we will connect to this through another route, add a direct route
1630 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001631 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001632 }
1633 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001634 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001635 }
1636
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001637 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001638 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001639 if ((lp == null) || (r == null)) {
1640 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001641 return false;
1642 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001643
1644 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001645 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001646 return false;
1647 }
1648
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001649 String ifaceName = r.getInterface();
1650 if(ifaceName == null) {
1651 loge("Error modifying route - no interface name");
1652 return false;
1653 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001654 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001655 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001656 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001657 if (bestRoute.getGateway().equals(r.getGateway())) {
1658 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001659 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001660 } else {
1661 // if we will connect to our gateway through another route, add a direct
1662 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001663 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1664 bestRoute.getGateway(),
1665 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001666 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001667 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001668 }
1669 }
1670 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001671 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001672 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001673 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001674 synchronized (mRoutesLock) {
1675 // only track default table - only one apps can effect
1676 mAddedRoutes.add(r);
1677 mNetd.addRoute(ifaceName, r);
1678 if (exempt) {
1679 LinkAddress dest = r.getDestination();
1680 if (!mExemptAddresses.contains(dest)) {
1681 mNetd.setHostExemption(dest);
1682 mExemptAddresses.add(dest);
1683 }
1684 }
1685 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001686 } else {
1687 mNetd.addSecondaryRoute(ifaceName, r);
1688 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001689 } catch (Exception e) {
1690 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001691 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001692 return false;
1693 }
1694 } else {
1695 // if we remove this one and there are no more like it, then refcount==0 and
1696 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001697 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001698 synchronized (mRoutesLock) {
1699 mAddedRoutes.remove(r);
1700 if (mAddedRoutes.contains(r) == false) {
1701 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1702 try {
1703 mNetd.removeRoute(ifaceName, r);
1704 LinkAddress dest = r.getDestination();
1705 if (mExemptAddresses.contains(dest)) {
1706 mNetd.clearHostExemption(dest);
1707 mExemptAddresses.remove(dest);
1708 }
1709 } catch (Exception e) {
1710 // never crash - catch them all
1711 if (VDBG) loge("Exception trying to remove a route: " + e);
1712 return false;
1713 }
1714 } else {
1715 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001716 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001717 }
1718 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001719 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001720 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001721 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001722 } catch (Exception e) {
1723 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001724 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001725 return false;
1726 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001727 }
1728 }
1729 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001730 }
1731
1732 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001733 * @see ConnectivityManager#getMobileDataEnabled()
1734 */
1735 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001736 // TODO: This detail should probably be in DataConnectionTracker's
1737 // which is where we store the value and maybe make this
1738 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001739 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001740 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1741 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001742 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001743 return retVal;
1744 }
1745
Robert Greenwalt34848c02011-03-25 13:09:25 -07001746 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001747 enforceConnectivityInternalPermission();
1748
Robert Greenwalt34848c02011-03-25 13:09:25 -07001749 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1750 (met ? ENABLED : DISABLED), networkType));
1751 }
1752
1753 private void handleSetDependencyMet(int networkType, boolean met) {
1754 if (mNetTrackers[networkType] != null) {
1755 if (DBG) {
1756 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1757 }
1758 mNetTrackers[networkType].setDependencyMet(met);
1759 }
1760 }
1761
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001762 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1763 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001764 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001765 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001766 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001767 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001768 }
1769
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001770 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001771 // skip update when we've already applied rules
1772 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1773 if (oldRules == uidRules) return;
1774
1775 mUidRules.put(uid, uidRules);
1776 }
1777
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001778 // TODO: notify UID when it has requested targeted updates
1779 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001780
1781 @Override
1782 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001783 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001784 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001785 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001786 }
1787
1788 synchronized (mRulesLock) {
1789 mMeteredIfaces.clear();
1790 for (String iface : meteredIfaces) {
1791 mMeteredIfaces.add(iface);
1792 }
1793 }
1794 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001795
1796 @Override
1797 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1798 // caller is NPMS, since we only register with them
1799 if (LOGD_RULES) {
1800 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1801 }
1802
1803 // kick off connectivity change broadcast for active network, since
1804 // global background policy change is radical.
1805 final int networkType = mActiveDefaultNetwork;
1806 if (isNetworkTypeValid(networkType)) {
1807 final NetworkStateTracker tracker = mNetTrackers[networkType];
1808 if (tracker != null) {
1809 final NetworkInfo info = tracker.getNetworkInfo();
1810 if (info != null && info.isConnected()) {
1811 sendConnectedBroadcast(info);
1812 }
1813 }
1814 }
1815 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001816 };
1817
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001818 /**
1819 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1820 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001821 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001822 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001823 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001824
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001825 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001826 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001827 }
1828
1829 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001830 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001831 if (VDBG) {
1832 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001833 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001834 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1835 }
tk.mun5eee1042012-01-06 10:43:52 +09001836 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1837 if (VDBG) {
1838 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1839 }
1840 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1841 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001842 }
1843
1844 @Override
1845 public void setPolicyDataEnable(int networkType, boolean enabled) {
1846 // only someone like NPMS should only be calling us
1847 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1848
1849 mHandler.sendMessage(mHandler.obtainMessage(
1850 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1851 }
1852
1853 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1854 if (isNetworkTypeValid(networkType)) {
1855 final NetworkStateTracker tracker = mNetTrackers[networkType];
1856 if (tracker != null) {
1857 tracker.setPolicyDataEnable(enabled);
1858 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001859 }
1860 }
1861
The Android Open Source Project28527d22009-03-03 19:31:44 -08001862 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001863 mContext.enforceCallingOrSelfPermission(
1864 android.Manifest.permission.ACCESS_NETWORK_STATE,
1865 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001866 }
1867
1868 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001869 mContext.enforceCallingOrSelfPermission(
1870 android.Manifest.permission.CHANGE_NETWORK_STATE,
1871 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001872 }
1873
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001874 // TODO Make this a special check when it goes public
1875 private void enforceTetherChangePermission() {
1876 mContext.enforceCallingOrSelfPermission(
1877 android.Manifest.permission.CHANGE_NETWORK_STATE,
1878 "ConnectivityService");
1879 }
1880
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001881 private void enforceTetherAccessPermission() {
1882 mContext.enforceCallingOrSelfPermission(
1883 android.Manifest.permission.ACCESS_NETWORK_STATE,
1884 "ConnectivityService");
1885 }
1886
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001887 private void enforceConnectivityInternalPermission() {
1888 mContext.enforceCallingOrSelfPermission(
1889 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1890 "ConnectivityService");
1891 }
1892
Chad Brubaker31de0b62013-07-11 13:29:30 -07001893 private void enforceMarkNetworkSocketPermission() {
1894 //Media server special case
1895 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1896 return;
1897 }
1898 mContext.enforceCallingOrSelfPermission(
1899 android.Manifest.permission.MARK_NETWORK_SOCKET,
1900 "ConnectivityService");
1901 }
1902
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001904 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1905 * network, we ignore it. If it is for the active network, we send out a
1906 * broadcast. But first, we check whether it might be possible to connect
1907 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 * @param info the {@code NetworkInfo} for the network
1909 */
1910 private void handleDisconnect(NetworkInfo info) {
1911
Robert Greenwalt2034b912009-08-12 16:08:25 -07001912 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001913
Robert Greenwalt2034b912009-08-12 16:08:25 -07001914 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001915
1916 // Remove idletimer previously setup in {@code handleConnect}
1917 removeDataActivityTracking(prevNetType);
1918
The Android Open Source Project28527d22009-03-03 19:31:44 -08001919 /*
1920 * If the disconnected network is not the active one, then don't report
1921 * this as a loss of connectivity. What probably happened is that we're
1922 * getting the disconnect for a network that we explicitly disabled
1923 * in accordance with network preference policies.
1924 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001925 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001926 List<Integer> pids = mNetRequestersPids[prevNetType];
1927 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001928 // will remove them because the net's no longer connected
1929 // need to do this now as only now do we know the pids and
1930 // can properly null things that are no longer referenced.
1931 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001932 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 }
1934
The Android Open Source Project28527d22009-03-03 19:31:44 -08001935 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001936 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001937 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001938 if (info.isFailover()) {
1939 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1940 info.setFailover(false);
1941 }
1942 if (info.getReason() != null) {
1943 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1944 }
1945 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001946 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1947 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001948 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001949
Robert Greenwalt34848c02011-03-25 13:09:25 -07001950 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001951 tryFailover(prevNetType);
1952 if (mActiveDefaultNetwork != -1) {
1953 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001954 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1955 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001956 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001957 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1958 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001959 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001960 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001961
1962 // Reset interface if no other connections are using the same interface
1963 boolean doReset = true;
1964 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1965 if (linkProperties != null) {
1966 String oldIface = linkProperties.getInterfaceName();
1967 if (TextUtils.isEmpty(oldIface) == false) {
1968 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1969 if (networkStateTracker == null) continue;
1970 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1971 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1972 LinkProperties l = networkStateTracker.getLinkProperties();
1973 if (l == null) continue;
1974 if (oldIface.equals(l.getInterfaceName())) {
1975 doReset = false;
1976 break;
1977 }
1978 }
1979 }
1980 }
1981 }
1982
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001983 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001984 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001985
Jeff Sharkey971cd162011-08-29 16:02:57 -07001986 final Intent immediateIntent = new Intent(intent);
1987 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1988 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001989 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001990 /*
1991 * If the failover network is already connected, then immediately send
1992 * out a followup broadcast indicating successful failover
1993 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001994 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001995 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1996 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001997 }
1998 }
1999
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002000 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002001 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08002002 * If this is a default network, check if other defaults are available.
2003 * Try to reconnect on all available and let them hash it out when
2004 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07002005 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07002006 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002007 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville89c87b92013-08-29 08:55:16 -07002008 if (DBG) {
2009 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2010 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002011 mActiveDefaultNetwork = -1;
2012 }
2013
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002014 // don't signal a reconnect for anything lower or equal priority than our
2015 // current connected default
2016 // TODO - don't filter by priority now - nice optimization but risky
2017// int currentPriority = -1;
2018// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002019// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002020// }
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002021
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002022 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002023 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002024 if (mNetConfigs[checkType] == null) continue;
2025 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002026 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002027
2028// Enabling the isAvailable() optimization caused mobile to not get
2029// selected if it was in the middle of error handling. Specifically
2030// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2031// would not be available and we wouldn't get connected to anything.
2032// So removing the isAvailable() optimization below for now. TODO: This
2033// optimization should work and we need to investigate why it doesn't work.
2034// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2035// complete before it is really complete.
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002036
Wink Saville72a95b92011-01-26 15:43:49 -08002037// if (!mNetTrackers[checkType].isAvailable()) continue;
2038
Robert Greenwalt34848c02011-03-25 13:09:25 -07002039// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002040
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002041 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2042 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2043 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2044 checkInfo.setFailover(true);
2045 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002046 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002047 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002048 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002049 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002050 }
2051
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002052 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002053 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002054 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2055 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002056 }
2057
Wink Saville4f0de1e2011-08-04 15:01:58 -07002058 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002059 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2060 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002061 }
2062
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002063 private void sendInetConditionBroadcast(NetworkInfo info) {
2064 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2065 }
2066
Wink Saville4f0de1e2011-08-04 15:01:58 -07002067 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002068 if (mLockdownTracker != null) {
2069 info = mLockdownTracker.augmentNetworkInfo(info);
2070 }
2071
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002072 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002073 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002074 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 if (info.isFailover()) {
2076 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2077 info.setFailover(false);
2078 }
2079 if (info.getReason() != null) {
2080 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2081 }
2082 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002083 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2084 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002086 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002087 return intent;
2088 }
2089
2090 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2091 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2092 }
2093
2094 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2095 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002096 }
2097
Haoyu Baib5da5752012-06-20 14:29:57 -07002098 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2099 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2100 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2101 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002102 final long ident = Binder.clearCallingIdentity();
2103 try {
2104 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2105 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002109 }
2110
The Android Open Source Project28527d22009-03-03 19:31:44 -08002111 /**
2112 * Called when an attempt to fail over to another network has failed.
2113 * @param info the {@link NetworkInfo} for the failed network
2114 */
2115 private void handleConnectionFailure(NetworkInfo info) {
2116 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002117
Robert Greenwalt2034b912009-08-12 16:08:25 -07002118 String reason = info.getReason();
2119 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002120
Robert Greenwalte981bc52010-10-08 16:35:52 -07002121 String reasonText;
2122 if (reason == null) {
2123 reasonText = ".";
2124 } else {
2125 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002126 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002127 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002128
2129 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002130 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002131 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002132 if (getActiveNetworkInfo() == null) {
2133 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2134 }
2135 if (reason != null) {
2136 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2137 }
2138 if (extraInfo != null) {
2139 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2140 }
2141 if (info.isFailover()) {
2142 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2143 info.setFailover(false);
2144 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002145
Robert Greenwalt34848c02011-03-25 13:09:25 -07002146 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002147 tryFailover(info.getType());
2148 if (mActiveDefaultNetwork != -1) {
2149 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002150 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2151 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002152 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002153 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2154 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002155 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002156
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002157 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002158
2159 final Intent immediateIntent = new Intent(intent);
2160 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2161 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002162 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002163 /*
2164 * If the failover network is already connected, then immediately send
2165 * out a followup broadcast indicating successful failover
2166 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002167 if (mActiveDefaultNetwork != -1) {
2168 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002169 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002170 }
2171
2172 private void sendStickyBroadcast(Intent intent) {
2173 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002174 if (!mSystemReady) {
2175 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002176 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002177 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002178 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002179 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002180 }
2181
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002182 final long ident = Binder.clearCallingIdentity();
2183 try {
2184 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2185 } finally {
2186 Binder.restoreCallingIdentity(ident);
2187 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002188 }
2189 }
2190
Wink Saville4f0de1e2011-08-04 15:01:58 -07002191 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2192 if (delayMs <= 0) {
2193 sendStickyBroadcast(intent);
2194 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002195 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002196 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2197 + intent.getAction());
2198 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002199 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2200 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2201 }
2202 }
2203
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002204 void systemReady() {
Wink Saville89c87b92013-08-29 08:55:16 -07002205 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2206 loadGlobalProxy();
2207
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002208 synchronized(this) {
2209 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002210 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002211 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002212 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002213 }
2214 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002215 // load the global proxy at startup
2216 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002217
2218 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2219 // for user to unlock device.
2220 if (!updateLockdownVpn()) {
2221 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2222 mContext.registerReceiver(mUserPresentReceiver, filter);
2223 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002224 }
2225
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002226 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2227 @Override
2228 public void onReceive(Context context, Intent intent) {
2229 // Try creating lockdown tracker, since user present usually means
2230 // unlocked keystore.
2231 if (updateLockdownVpn()) {
2232 mContext.unregisterReceiver(this);
2233 }
2234 }
2235 };
2236
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002237 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville89c87b92013-08-29 08:55:16 -07002238 if (((type != mNetworkPreference)
2239 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2240 || (mNetworkPreference == mActiveDefaultNetwork)) {
2241 return false;
2242 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002243 return true;
2244 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002245
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002246 private void handleConnect(NetworkInfo info) {
2247 final int newNetType = info.getType();
2248
2249 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002250
The Android Open Source Project28527d22009-03-03 19:31:44 -08002251 // snapshot isFailover, because sendConnectedBroadcast() resets it
2252 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002253 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002254 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255
Wink Saville89c87b92013-08-29 08:55:16 -07002256 if (VDBG) {
2257 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2258 + " isFailover" + isFailover);
2259 }
2260
Robert Greenwalt2034b912009-08-12 16:08:25 -07002261 // if this is a default net and other default is running
2262 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002263 if (mNetConfigs[newNetType].isDefault()) {
2264 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2265 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002266 // tear down the other
2267 NetworkStateTracker otherNet =
2268 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002269 if (DBG) {
2270 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002271 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002272 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002273 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002274 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002275 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002276 return;
2277 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002278 } else {
2279 // don't accept this one
2280 if (VDBG) {
2281 log("Not broadcasting CONNECT_ACTION " +
2282 "to torn down network " + info.getTypeName());
2283 }
2284 teardown(thisNet);
2285 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002286 }
2287 }
2288 synchronized (ConnectivityService.this) {
2289 // have a new default network, release the transition wakelock in a second
2290 // if it's held. The second pause is to allow apps to reconnect over the
2291 // new network
2292 if (mNetTransitionWakeLock.isHeld()) {
2293 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002294 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002295 mNetTransitionWakeLockSerialNumber, 0),
2296 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002297 }
2298 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002299 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002300 // this will cause us to come up initially as unconnected and switching
2301 // to connected after our normal pause unless somebody reports us as reall
2302 // disconnected
2303 mDefaultInetConditionPublished = 0;
2304 mDefaultConnectionSequence++;
2305 mInetConditionChangeInFlight = false;
2306 // Don't do this - if we never sign in stay, grey
2307 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002308 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002309 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002310 updateNetworkSettings(thisNet);
sy.yun30043282013-09-02 05:24:09 +09002311 updateMtuSizeSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002312 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002313 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002314
2315 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002316 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002317 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002318 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002319 } catch (RemoteException e) {
2320 // ignored; service lives in system_server
2321 }
2322 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002323 }
2324
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002325 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2326 if (DBG) log("Captive portal check " + info);
2327 int type = info.getType();
2328 final NetworkStateTracker thisNet = mNetTrackers[type];
2329 if (mNetConfigs[type].isDefault()) {
2330 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2331 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2332 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002333 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002334 return;
2335 } else {
2336 if (DBG) log("Tear down low priority net " + info.getTypeName());
2337 teardown(thisNet);
2338 return;
2339 }
2340 }
2341 }
2342
Wink Savilleffdadd62013-08-07 16:22:47 -07002343 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002344 thisNet.captivePortalCheckComplete();
2345 }
2346
2347 /** @hide */
Wink Savilleffdadd62013-08-07 16:22:47 -07002348 @Override
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002349 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002350 enforceConnectivityInternalPermission();
Wink Savilleffdadd62013-08-07 16:22:47 -07002351 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002352 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002353 }
2354
Wink Savilleffdadd62013-08-07 16:22:47 -07002355 /** @hide */
2356 @Override
2357 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2358 enforceConnectivityInternalPermission();
2359 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2360 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2361 }
2362
The Android Open Source Project28527d22009-03-03 19:31:44 -08002363 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002364 * Setup data activity tracking for the given network interface.
2365 *
2366 * Every {@code setupDataActivityTracking} should be paired with a
2367 * {@link removeDataActivityTracking} for cleanup.
2368 */
2369 private void setupDataActivityTracking(int type) {
2370 final NetworkStateTracker thisNet = mNetTrackers[type];
2371 final String iface = thisNet.getLinkProperties().getInterfaceName();
2372
2373 final int timeout;
2374
2375 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002376 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2377 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002378 0);
2379 // Canonicalize mobile network type
2380 type = ConnectivityManager.TYPE_MOBILE;
2381 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002382 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2383 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002384 0);
2385 } else {
2386 // do not track any other networks
2387 timeout = 0;
2388 }
2389
2390 if (timeout > 0 && iface != null) {
2391 try {
2392 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2393 } catch (RemoteException e) {
2394 }
2395 }
2396 }
2397
2398 /**
2399 * Remove data activity tracking when network disconnects.
2400 */
2401 private void removeDataActivityTracking(int type) {
2402 final NetworkStateTracker net = mNetTrackers[type];
2403 final String iface = net.getLinkProperties().getInterfaceName();
2404
2405 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2406 ConnectivityManager.TYPE_WIFI == type)) {
2407 try {
2408 // the call fails silently if no idletimer setup for this interface
2409 mNetd.removeIdleTimer(iface);
2410 } catch (RemoteException e) {
2411 }
2412 }
2413 }
2414
2415 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002416 * After a change in the connectivity state of a network. We're mainly
2417 * concerned with making sure that the list of DNS servers is set up
2418 * according to which networks are connected, and ensuring that the
2419 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002420 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002421 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002422 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker78850f32013-07-15 16:34:04 -07002423 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville89c87b92013-08-29 08:55:16 -07002424 if (VDBG) {
2425 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2426 + " resetMask=" + resetMask);
2427 }
Wink Saville051a6642011-07-13 13:44:13 -07002428
The Android Open Source Project28527d22009-03-03 19:31:44 -08002429 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002430 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002431 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002432 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002433 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002434
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002435 LinkProperties curLp = mCurrentLinkProperties[netType];
2436 LinkProperties newLp = null;
2437
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002438 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002439 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002440 if (VDBG) {
2441 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2442 " doReset=" + doReset + " resetMask=" + resetMask +
2443 "\n curLp=" + curLp +
2444 "\n newLp=" + newLp);
2445 }
2446
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002447 if (curLp != null) {
2448 if (curLp.isIdenticalInterfaceName(newLp)) {
2449 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2450 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2451 for (LinkAddress linkAddr : car.removed) {
2452 if (linkAddr.getAddress() instanceof Inet4Address) {
2453 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2454 }
2455 if (linkAddr.getAddress() instanceof Inet6Address) {
2456 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2457 }
Wink Saville051a6642011-07-13 13:44:13 -07002458 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002459 if (DBG) {
2460 log("handleConnectivityChange: addresses changed" +
2461 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2462 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002463 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002464 } else {
2465 if (DBG) {
2466 log("handleConnectivityChange: address are the same reset per doReset" +
2467 " linkProperty[" + netType + "]:" +
2468 " resetMask=" + resetMask);
2469 }
Wink Saville051a6642011-07-13 13:44:13 -07002470 }
2471 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002472 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002473 if (DBG) {
2474 log("handleConnectivityChange: interface not not equivalent reset both" +
2475 " linkProperty[" + netType + "]:" +
2476 " resetMask=" + resetMask);
2477 }
Wink Saville051a6642011-07-13 13:44:13 -07002478 }
Wink Saville051a6642011-07-13 13:44:13 -07002479 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002480 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002481 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002482 }
2483 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002484 if (VDBG) {
2485 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2486 " doReset=" + doReset + " resetMask=" + resetMask +
2487 "\n curLp=" + curLp +
2488 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002489 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002490 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002491 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker78850f32013-07-15 16:34:04 -07002492 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002493
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002494 if (resetMask != 0 || resetDns) {
Wink Saville89c87b92013-08-29 08:55:16 -07002495 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002496 if (curLp != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07002497 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002498 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002499 if (TextUtils.isEmpty(iface) == false) {
2500 if (resetMask != 0) {
2501 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2502 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002503
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002504 // Tell VPN the interface is down. It is a temporary
2505 // but effective fix to make VPN aware of the change.
2506 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002507 synchronized(mVpns) {
2508 for (int i = 0; i < mVpns.size(); i++) {
2509 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2510 }
2511 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002512 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002513 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002514 if (resetDns) {
2515 flushVmDnsCache();
2516 if (VDBG) log("resetting DNS cache for " + iface);
2517 try {
2518 mNetd.flushInterfaceDnsCache(iface);
2519 } catch (Exception e) {
2520 // never crash - catch them all
2521 if (DBG) loge("Exception resetting dns cache: " + e);
2522 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002523 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002524 } else {
2525 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002526 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002527 }
2528 }
2529 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002530
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002531 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002532 NetworkStateTracker tracker = mNetTrackers[netType];
2533 if (mClat.requiresClat(netType, tracker)) {
Wink Saville89c87b92013-08-29 08:55:16 -07002534
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002535 // If the connection was previously using clat, but is not using it now, stop the clat
2536 // daemon. Normally, this happens automatically when the connection disconnects, but if
2537 // the disconnect is not reported, or if the connection's LinkProperties changed for
2538 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2539 // still be running. If it's not running, then stopping it is a no-op.
2540 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2541 mClat.stopClat();
2542 }
2543 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002544 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2545 mClat.startClat(tracker);
2546 } else {
2547 mClat.stopClat();
2548 }
2549 }
2550
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002551 // TODO: Temporary notifying upstread change to Tethering.
2552 // @see bug/4455071
2553 /** Notify TetheringService if interface name has been changed. */
2554 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002555 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002556 if (isTetheringSupported()) {
2557 mTethering.handleTetherIfaceChange();
2558 }
2559 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002560 }
2561
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002562 /**
2563 * Add and remove routes using the old properties (null if not previously connected),
2564 * new properties (null if becoming disconnected). May even be double null, which
2565 * is a noop.
2566 * Uses isLinkDefault to determine if default routes should be set or conversely if
2567 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002568 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002569 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002570 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker78850f32013-07-15 16:34:04 -07002571 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002572 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002573 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2574 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002575 if (curLp != null) {
2576 // check for the delta between the current set and the new
Lorenzo Colitti43553b62013-07-31 23:23:21 +09002577 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002578 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002579 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002580 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002581 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002582 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002583
Robert Greenwalt8d777252011-08-15 12:31:55 -07002584 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2585
Robert Greenwalt98107422011-07-22 11:55:33 -07002586 for (RouteInfo r : routeDiff.removed) {
2587 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002588 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002589 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2590 }
2591 if (isLinkDefault == false) {
2592 // remove from a secondary route table
2593 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002594 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002595 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002596
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002597 if (!isLinkDefault) {
2598 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002599 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002600 // routes changed - remove all old dns entries and add new
2601 if (curLp != null) {
2602 for (InetAddress oldDns : curLp.getDnses()) {
2603 removeRouteToAddress(curLp, oldDns);
2604 }
2605 }
2606 if (newLp != null) {
2607 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002608 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002609 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002610 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002611 } else {
2612 // no change in routes, check for change in dns themselves
2613 for (InetAddress oldDns : dnsDiff.removed) {
2614 removeRouteToAddress(curLp, oldDns);
2615 }
2616 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002617 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002618 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002619 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002620 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002621
2622 for (RouteInfo r : routeDiff.added) {
2623 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002624 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002625 } else {
2626 // add to a secondary route table
Chad Brubaker78850f32013-07-15 16:34:04 -07002627 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002628
2629 // many radios add a default route even when we don't want one.
2630 // remove the default route unless somebody else has asked for it
2631 String ifaceName = newLp.getInterfaceName();
Chad Brubaker78850f32013-07-15 16:34:04 -07002632 synchronized (mRoutesLock) {
2633 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2634 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2635 try {
2636 mNetd.removeRoute(ifaceName, r);
2637 } catch (Exception e) {
2638 // never crash - catch them all
2639 if (DBG) loge("Exception trying to remove a route: " + e);
2640 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002641 }
2642 }
2643 }
2644 }
2645
Robert Greenwalt8d777252011-08-15 12:31:55 -07002646 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002647 }
2648
sy.yun30043282013-09-02 05:24:09 +09002649 /**
2650 * Reads the network specific MTU size from reources.
2651 * and set it on it's iface.
2652 */
2653 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2654 final String iface = nt.getLinkProperties().getInterfaceName();
2655 final int mtu = nt.getLinkProperties().getMtu();
2656
2657 if (mtu < 68 || mtu > 10000) {
2658 loge("Unexpected mtu value: " + nt);
2659 return;
2660 }
2661
2662 try {
2663 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2664 mNetd.setMtu(iface, mtu);
2665 } catch (Exception e) {
2666 Slog.e(TAG, "exception in setMtu()" + e);
2667 }
2668 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002669
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002670 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002671 * Reads the network specific TCP buffer sizes from SystemProperties
2672 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2673 * wide use
2674 */
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002675 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002676 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002677 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002678
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002679 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002680 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002681
2682 // Setting to default values so we won't be stuck to previous values
2683 key = "net.tcp.buffersize.default";
2684 bufferSizes = SystemProperties.get(key);
2685 }
2686
2687 // Set values in kernel
2688 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002689 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002690 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002691 + "] which comes from [" + key + "]");
2692 }
2693 setBufferSize(bufferSizes);
2694 }
2695 }
2696
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002697 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002698 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2699 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2700 *
2701 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2702 * writeMin, writeInitial, writeMax"
2703 */
2704 private void setBufferSize(String bufferSizes) {
2705 try {
2706 String[] values = bufferSizes.split(",");
2707
2708 if (values.length == 6) {
2709 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002710 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2711 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2712 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2713 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2714 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2715 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002716 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002717 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002718 }
2719 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002720 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002721 }
2722 }
2723
Robert Greenwalt2034b912009-08-12 16:08:25 -07002724 /**
2725 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2726 * on the highest priority active net which this process requested.
2727 * If there aren't any, clear it out
2728 */
Mattias Falkdc919012011-08-23 14:15:13 +02002729 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002730 {
Mattias Falkdc919012011-08-23 14:15:13 +02002731 if (VDBG) log("reassessPidDns for pid " + pid);
2732 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002733 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002734 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002735 continue;
2736 }
2737 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002738 if (nt.getNetworkInfo().isConnected() &&
2739 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002740 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002741 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002742 if (mNetRequestersPids[i].contains(myPid)) {
2743 try {
2744 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2745 } catch (Exception e) {
2746 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002747 }
Mattias Falkdc919012011-08-23 14:15:13 +02002748 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002749 }
2750 }
2751 }
2752 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002753 try {
2754 mNetd.clearDnsInterfaceForPid(pid);
2755 } catch (Exception e) {
2756 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002757 }
2758 }
2759
Mattias Falkdc919012011-08-23 14:15:13 +02002760 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002761 /*
2762 * Tell the VMs to toss their DNS caches
2763 */
2764 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2765 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002766 /*
2767 * Connectivity events can happen before boot has completed ...
2768 */
2769 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002770 final long ident = Binder.clearCallingIdentity();
2771 try {
2772 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2773 } finally {
2774 Binder.restoreCallingIdentity(ident);
2775 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002776 }
2777
Chia-chi Yehcc844502011-07-14 18:01:57 -07002778 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002779 private void updateDnsLocked(String network, String iface,
Chad Brubaker45e721f2013-07-23 17:13:36 -07002780 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002781 int last = 0;
2782 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002783 dnses = new ArrayList();
2784 dnses.add(mDefaultDns);
2785 if (DBG) {
2786 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002787 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002788 }
2789
Mattias Falkdc919012011-08-23 14:15:13 +02002790 try {
2791 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker45e721f2013-07-23 17:13:36 -07002792 if (defaultDns) {
2793 mNetd.setDefaultInterfaceForDns(iface);
2794 }
2795
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002796 for (InetAddress dns : dnses) {
2797 ++last;
2798 String key = "net.dns" + last;
2799 String value = dns.getHostAddress();
2800 SystemProperties.set(key, value);
2801 }
2802 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2803 String key = "net.dns" + i;
2804 SystemProperties.set(key, "");
2805 }
2806 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002807 } catch (Exception e) {
Robert Greenwalt68534c82013-09-24 11:05:57 -07002808 loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002809 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002810 }
2811
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002812 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002813 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002814 NetworkStateTracker nt = mNetTrackers[netType];
2815 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002816 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002817 if (p == null) return;
2818 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002819 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002820 String network = nt.getNetworkInfo().getTypeName();
2821 synchronized (mDnsLock) {
Chad Brubakera8e81122013-07-23 17:44:41 -07002822 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002823 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002824 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002825 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002826 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002827 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002828 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002829 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002830 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002831 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002832 List<Integer> pids = mNetRequestersPids[netType];
2833 for (Integer pid : pids) {
2834 try {
2835 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2836 } catch (Exception e) {
2837 Slog.e(TAG, "exception setting interface for pid: " + e);
2838 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002839 }
2840 }
Mattias Falkdc919012011-08-23 14:15:13 +02002841 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002842 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002843 }
2844
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002845 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002846 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2847 NETWORK_RESTORE_DELAY_PROP_NAME);
2848 if(restoreDefaultNetworkDelayStr != null &&
2849 restoreDefaultNetworkDelayStr.length() != 0) {
2850 try {
2851 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2852 } catch (NumberFormatException e) {
2853 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002854 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002855 // if the system property isn't set, use the value for the apn type
2856 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2857
2858 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2859 (mNetConfigs[networkType] != null)) {
2860 ret = mNetConfigs[networkType].restoreTime;
2861 }
2862 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002863 }
2864
2865 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002866 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2867 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002868 if (mContext.checkCallingOrSelfPermission(
2869 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002870 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002871 pw.println("Permission Denial: can't dump ConnectivityService " +
2872 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2873 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002874 return;
2875 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002876
2877 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002878 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002879 for (int i = 0; i < mNetTrackers.length; i++) {
2880 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002881 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002882 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2883 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002884 if (nst.getNetworkInfo().isConnected()) {
2885 pw.println("Active network: " + nst.getNetworkInfo().
2886 getTypeName());
2887 }
2888 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002889 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002890 pw.println(nst);
2891 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002892 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002893 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002894 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002895
2896 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002897 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002898 for (int net : mPriorityList) {
2899 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002900 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002901 pidString = pidString + pid.toString() + ", ";
2902 }
2903 pw.println(pidString);
2904 }
2905 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002906 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002907
2908 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002909 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002910 for (Object requester : mFeatureUsers) {
2911 pw.println(requester.toString());
2912 }
2913 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002914 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002915
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002916 synchronized (this) {
2917 pw.println("NetworkTranstionWakeLock is currently " +
2918 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2919 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2920 }
2921 pw.println();
2922
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002923 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002924
2925 if (mInetLog != null) {
2926 pw.println();
2927 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002928 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002929 for(int i = 0; i < mInetLog.size(); i++) {
2930 pw.println(mInetLog.get(i));
2931 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002932 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002933 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002934 }
2935
Robert Greenwalt2034b912009-08-12 16:08:25 -07002936 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002937 private class NetworkStateTrackerHandler extends Handler {
2938 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002939 super(looper);
2940 }
2941
The Android Open Source Project28527d22009-03-03 19:31:44 -08002942 @Override
2943 public void handleMessage(Message msg) {
2944 NetworkInfo info;
2945 switch (msg.what) {
Wink Saville89c87b92013-08-29 08:55:16 -07002946 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002947 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002948 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002949
Wink Savillea7d56572011-09-21 11:05:43 -07002950 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville860f5282013-09-05 12:02:25 -07002951 (state == NetworkInfo.State.DISCONNECTED) ||
2952 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002953 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002954 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002955 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002956 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002957
Wink Saville89c87b92013-08-29 08:55:16 -07002958 // Since mobile has the notion of a network/apn that can be used for
2959 // provisioning we need to check every time we're connected as
2960 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2961 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2962 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2963 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2964 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Saville9564f2b2013-07-16 17:16:37 -07002965 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2966 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleab773a72013-09-14 09:04:53 -07002967 && (((state == NetworkInfo.State.CONNECTED)
2968 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2969 || info.isConnectedToProvisioningNetwork())) {
2970 log("ConnectivityChange checkMobileProvisioning for"
2971 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville89c87b92013-08-29 08:55:16 -07002972 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Saville9564f2b2013-07-16 17:16:37 -07002973 }
2974
Jeff Sharkeybde32692012-11-09 15:57:02 -08002975 EventLogTags.writeConnectivityStateChanged(
2976 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002977
2978 if (info.getDetailedState() ==
2979 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002980 handleConnectionFailure(info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002981 } else if (info.getDetailedState() ==
2982 DetailedState.CAPTIVE_PORTAL_CHECK) {
2983 handleCaptivePortalTrackerCheck(info);
Wink Saville860f5282013-09-05 12:02:25 -07002984 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002985 /**
2986 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2987 * for now its an in between network, its a network that
2988 * is actually a default network but we don't want it to be
2989 * announced as such to keep background applications from
2990 * trying to use it. It turns out that some still try so we
2991 * take the additional step of clearing any default routes
2992 * to the link that may have incorrectly setup by the lower
2993 * levels.
2994 */
2995 LinkProperties lp = getLinkProperties(info.getType());
2996 if (DBG) {
2997 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2998 }
2999
3000 // Clear any default routes setup by the radio so
3001 // any activity by applications trying to use this
3002 // connection will fail until the provisioning network
3003 // is enabled.
3004 for (RouteInfo r : lp.getRoutes()) {
3005 removeRoute(lp, r, TO_DEFAULT_TABLE);
3006 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08003007 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003008 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003009 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003010 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003011 // the logic here is, handle SUSPENDED the same as
3012 // DISCONNECTED. The only difference being we are
3013 // broadcasting an intent with NetworkInfo that's
3014 // suspended. This allows the applications an
3015 // opportunity to handle DISCONNECTED and SUSPENDED
3016 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003017 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003018 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003019 handleConnect(info);
3020 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003021 if (mLockdownTracker != null) {
3022 mLockdownTracker.onNetworkInfoChanged(info);
3023 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003024 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003025 }
3026 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003027 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003028 // TODO: Temporary allowing network configuration
3029 // change not resetting sockets.
3030 // @see bug/4455071
3031 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003032 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003033 }
3034 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003035 info = (NetworkInfo) msg.obj;
Wink Saville89c87b92013-08-29 08:55:16 -07003036 int type = info.getType();
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003037 updateNetworkSettings(mNetTrackers[type]);
3038 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003039 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003040 }
3041 }
3042 }
3043
3044 private class InternalHandler extends Handler {
3045 public InternalHandler(Looper looper) {
3046 super(looper);
3047 }
3048
3049 @Override
3050 public void handleMessage(Message msg) {
3051 NetworkInfo info;
3052 switch (msg.what) {
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003053 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003054 String causedBy = null;
3055 synchronized (ConnectivityService.this) {
3056 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3057 mNetTransitionWakeLock.isHeld()) {
3058 mNetTransitionWakeLock.release();
3059 causedBy = mNetTransitionWakeLockCausedBy;
3060 }
3061 }
3062 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003063 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003064 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003065 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003066 }
3067 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003068 FeatureUser u = (FeatureUser)msg.obj;
3069 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003070 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003071 }
3072 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003073 int netType = msg.arg1;
3074 int condition = msg.arg2;
3075 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003076 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003077 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003078 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003079 int netType = msg.arg1;
3080 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00003081 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003082 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003083 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003084 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003085 int preference = msg.arg1;
3086 handleSetNetworkPreference(preference);
3087 break;
3088 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003089 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003090 boolean enabled = (msg.arg1 == ENABLED);
3091 handleSetMobileData(enabled);
3092 break;
3093 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003094 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003095 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003096 break;
3097 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003098 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003099 boolean met = (msg.arg1 == ENABLED);
3100 handleSetDependencyMet(msg.arg2, met);
3101 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003102 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003103 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003104 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003105 sendStickyBroadcast(intent);
3106 break;
3107 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003108 case EVENT_SET_POLICY_DATA_ENABLE: {
3109 final int networkType = msg.arg1;
3110 final boolean enabled = msg.arg2 == ENABLED;
3111 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003112 break;
3113 }
3114 case EVENT_VPN_STATE_CHANGED: {
3115 if (mLockdownTracker != null) {
3116 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3117 }
3118 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003119 }
Wink Saville690cb182013-06-29 21:10:57 -07003120 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3121 int tag = mEnableFailFastMobileDataTag.get();
3122 if (msg.arg1 == tag) {
3123 MobileDataStateTracker mobileDst =
3124 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3125 if (mobileDst != null) {
3126 mobileDst.setEnableFailFastMobileData(msg.arg2);
3127 }
3128 } else {
3129 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3130 + " != tag:" + tag);
3131 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003132 break;
Wink Saville690cb182013-06-29 21:10:57 -07003133 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003134 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07003135 handleNetworkSamplingTimeout();
3136 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003137 }
Jason Monk445cea82013-10-10 14:02:51 -04003138 case EVENT_PROXY_HAS_CHANGED: {
3139 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3140 break;
3141 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003142 }
3143 }
3144 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003145
3146 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003147 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003148 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003149
3150 if (isTetheringSupported()) {
3151 return mTethering.tether(iface);
3152 } else {
3153 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3154 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003155 }
3156
3157 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003158 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003159 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003160
3161 if (isTetheringSupported()) {
3162 return mTethering.untether(iface);
3163 } else {
3164 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3165 }
3166 }
3167
3168 // javadoc from interface
3169 public int getLastTetherError(String iface) {
3170 enforceTetherAccessPermission();
3171
3172 if (isTetheringSupported()) {
3173 return mTethering.getLastTetherError(iface);
3174 } else {
3175 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3176 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003177 }
3178
3179 // TODO - proper iface API for selection by property, inspection, etc
3180 public String[] getTetherableUsbRegexs() {
3181 enforceTetherAccessPermission();
3182 if (isTetheringSupported()) {
3183 return mTethering.getTetherableUsbRegexs();
3184 } else {
3185 return new String[0];
3186 }
3187 }
3188
3189 public String[] getTetherableWifiRegexs() {
3190 enforceTetherAccessPermission();
3191 if (isTetheringSupported()) {
3192 return mTethering.getTetherableWifiRegexs();
3193 } else {
3194 return new String[0];
3195 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003196 }
3197
Danica Chang96567052010-08-11 14:54:43 -07003198 public String[] getTetherableBluetoothRegexs() {
3199 enforceTetherAccessPermission();
3200 if (isTetheringSupported()) {
3201 return mTethering.getTetherableBluetoothRegexs();
3202 } else {
3203 return new String[0];
3204 }
3205 }
3206
Mike Lockwooded4a1742011-07-19 13:04:47 -07003207 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08003208 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003209 if (isTetheringSupported()) {
3210 return mTethering.setUsbTethering(enable);
3211 } else {
3212 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3213 }
3214 }
3215
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003216 // TODO - move iface listing, queries, etc to new module
3217 // javadoc from interface
3218 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003219 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003220 return mTethering.getTetherableIfaces();
3221 }
3222
3223 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003224 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003225 return mTethering.getTetheredIfaces();
3226 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003227
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003228 public String[] getTetheringErroredIfaces() {
3229 enforceTetherAccessPermission();
3230 return mTethering.getErroredIfaces();
3231 }
3232
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003233 // if ro.tether.denied = true we default to no tethering
3234 // gservices could set the secure setting to 1 though to enable it on a build where it
3235 // had previously been turned off.
3236 public boolean isTetheringSupported() {
3237 enforceTetherAccessPermission();
3238 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003239 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3240 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003241 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3242 mTethering.getTetherableWifiRegexs().length != 0 ||
3243 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3244 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003245 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003246
3247 // An API NetworkStateTrackers can call when they lose their network.
3248 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3249 // whichever happens first. The timer is started by the first caller and not
3250 // restarted by subsequent callers.
3251 public void requestNetworkTransitionWakelock(String forWhom) {
3252 enforceConnectivityInternalPermission();
3253 synchronized (this) {
3254 if (mNetTransitionWakeLock.isHeld()) return;
3255 mNetTransitionWakeLockSerialNumber++;
3256 mNetTransitionWakeLock.acquire();
3257 mNetTransitionWakeLockCausedBy = forWhom;
3258 }
3259 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003260 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003261 mNetTransitionWakeLockSerialNumber, 0),
3262 mNetTransitionWakeLockTimeout);
3263 return;
3264 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003265
Robert Greenwalt986c7412010-09-08 15:24:47 -07003266 // 100 percent is full good, 0 is full bad.
3267 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003268 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003269 mContext.enforceCallingOrSelfPermission(
3270 android.Manifest.permission.STATUS_BAR,
3271 "ConnectivityService");
3272
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003273 if (DBG) {
3274 int pid = getCallingPid();
3275 int uid = getCallingUid();
3276 String s = pid + "(" + uid + ") reports inet is " +
3277 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3278 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3279 mInetLog.add(s);
3280 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3281 mInetLog.remove(0);
3282 }
3283 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003284 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003285 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3286 }
3287
3288 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003289 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003290 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003291 return;
3292 }
3293 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003294 if (DBG) log("handleInetConditionChange: net=" + netType +
3295 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003296 return;
3297 }
Wink Savillea7d56572011-09-21 11:05:43 -07003298 if (VDBG) {
3299 log("handleInetConditionChange: net=" +
3300 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003301 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003302 }
Wink Saville3e866722013-01-31 00:30:13 +00003303 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003304 int delay;
3305 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003306 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003307 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003308 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003309 delay = Settings.Global.getInt(mContext.getContentResolver(),
3310 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003311 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003312 delay = Settings.Global.getInt(mContext.getContentResolver(),
3313 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003314 }
3315 mInetConditionChangeInFlight = true;
3316 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003317 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003318 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003319 // we've set the new condition, when this hold ends that will get picked up
3320 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003321 }
3322 }
3323
Wink Saville3e866722013-01-31 00:30:13 +00003324 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003325 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003326 log("handleInetConditionHoldEnd: net=" + netType +
3327 ", condition=" + mDefaultInetCondition +
3328 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003329 }
3330 mInetConditionChangeInFlight = false;
3331
3332 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003333 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003334 return;
3335 }
3336 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003337 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003338 return;
3339 }
Wink Saville3e866722013-01-31 00:30:13 +00003340 // TODO: Figure out why this optimization sometimes causes a
3341 // change in mDefaultInetCondition to be missed and the
3342 // UI to not be updated.
3343 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3344 // if (DBG) log("no change in condition - aborting");
3345 // return;
3346 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003347 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3348 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003349 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003350 return;
3351 }
Wink Saville3e866722013-01-31 00:30:13 +00003352 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003353 sendInetConditionBroadcast(networkInfo);
3354 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003355 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003356
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003357 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003358 // this information is already available as a world read/writable jvm property
3359 // so this API change wouldn't have a benifit. It also breaks the passing
3360 // of proxy info to all the JVMs.
3361 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003362 synchronized (mProxyLock) {
Jason Monk43324ee2013-07-03 17:04:33 -04003363 ProxyProperties ret = mGlobalProxy;
3364 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3365 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003366 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003367 }
3368
3369 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003370 enforceConnectivityInternalPermission();
Jason Monk43324ee2013-07-03 17:04:33 -04003371
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003372 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003373 if (proxyProperties == mGlobalProxy) return;
3374 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3375 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3376
3377 String host = "";
3378 int port = 0;
3379 String exclList = "";
Jason Monk43324ee2013-07-03 17:04:33 -04003380 String pacFileUrl = "";
3381 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3382 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003383 mGlobalProxy = new ProxyProperties(proxyProperties);
3384 host = mGlobalProxy.getHost();
3385 port = mGlobalProxy.getPort();
3386 exclList = mGlobalProxy.getExclusionList();
Jason Monk43324ee2013-07-03 17:04:33 -04003387 if (proxyProperties.getPacFileUrl() != null) {
3388 pacFileUrl = proxyProperties.getPacFileUrl();
3389 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003390 } else {
3391 mGlobalProxy = null;
3392 }
3393 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003394 final long token = Binder.clearCallingIdentity();
3395 try {
3396 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3397 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3398 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3399 exclList);
Jason Monk43324ee2013-07-03 17:04:33 -04003400 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003401 } finally {
3402 Binder.restoreCallingIdentity(token);
3403 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003404 }
3405
3406 if (mGlobalProxy == null) {
3407 proxyProperties = mDefaultProxy;
3408 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003409 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003410 }
3411
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003412 private void loadGlobalProxy() {
3413 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003414 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3415 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3416 String exclList = Settings.Global.getString(res,
3417 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk43324ee2013-07-03 17:04:33 -04003418 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3419 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3420 ProxyProperties proxyProperties;
3421 if (!TextUtils.isEmpty(pacFileUrl)) {
3422 proxyProperties = new ProxyProperties(pacFileUrl);
3423 } else {
3424 proxyProperties = new ProxyProperties(host, port, exclList);
3425 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003426 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003427 mGlobalProxy = proxyProperties;
3428 }
3429 }
3430 }
3431
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003432 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003433 // this information is already available as a world read/writable jvm property
3434 // so this API change wouldn't have a benifit. It also breaks the passing
3435 // of proxy info to all the JVMs.
3436 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003437 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003438 return mGlobalProxy;
3439 }
3440 }
3441
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003442 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04003443 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3444 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003445 proxy = null;
3446 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003447 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003448 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003449 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003450 mDefaultProxy = proxy;
3451
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003452 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003453 if (!mDefaultProxyDisabled) {
3454 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003455 }
3456 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003457 }
3458
3459 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003460 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3461 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003462 if (!TextUtils.isEmpty(proxy)) {
3463 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003464 if (data.length == 0) {
3465 return;
3466 }
3467
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003468 String proxyHost = data[0];
3469 int proxyPort = 8080;
3470 if (data.length > 1) {
3471 try {
3472 proxyPort = Integer.parseInt(data[1]);
3473 } catch (NumberFormatException e) {
3474 return;
3475 }
3476 }
3477 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3478 setGlobalProxy(p);
3479 }
3480 }
3481
3482 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003483 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monkaf9ded02013-08-23 19:21:25 -04003484 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003485 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003486 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003487 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3488 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003489 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003490 final long ident = Binder.clearCallingIdentity();
3491 try {
3492 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3493 } finally {
3494 Binder.restoreCallingIdentity(ident);
3495 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003496 }
3497
3498 private static class SettingsObserver extends ContentObserver {
3499 private int mWhat;
3500 private Handler mHandler;
3501 SettingsObserver(Handler handler, int what) {
3502 super(handler);
3503 mHandler = handler;
3504 mWhat = what;
3505 }
3506
3507 void observe(Context context) {
3508 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003509 resolver.registerContentObserver(Settings.Global.getUriFor(
3510 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003511 }
3512
3513 @Override
3514 public void onChange(boolean selfChange) {
3515 mHandler.obtainMessage(mWhat).sendToTarget();
3516 }
3517 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003518
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003519 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003520 Slog.d(TAG, s);
3521 }
3522
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003523 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003524 Slog.e(TAG, s);
3525 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003526
repo syncf5de5572011-07-29 23:55:49 -07003527 int convertFeatureToNetworkType(int networkType, String feature) {
3528 int usedNetworkType = networkType;
3529
3530 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3531 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3532 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3533 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3534 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3535 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3536 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3537 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3538 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3539 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3540 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3541 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3542 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3543 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3544 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3545 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3546 } else {
3547 Slog.e(TAG, "Can't match any mobile netTracker!");
3548 }
3549 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3550 if (TextUtils.equals(feature, "p2p")) {
3551 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3552 } else {
3553 Slog.e(TAG, "Can't match any wifi netTracker!");
3554 }
3555 } else {
3556 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003557 }
repo syncf5de5572011-07-29 23:55:49 -07003558 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003559 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003560
3561 private static <T> T checkNotNull(T value, String message) {
3562 if (value == null) {
3563 throw new NullPointerException(message);
3564 }
3565 return value;
3566 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003567
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003568 /**
3569 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003570 * VpnBuilder and not available in ConnectivityManager. Permissions
3571 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003572 * @hide
3573 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003574 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003575 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003576 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003577 try {
3578 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003579 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003580 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003581 synchronized(mVpns) {
3582 mVpns.get(user).protect(socket,
3583 mNetTrackers[type].getLinkProperties().getInterfaceName());
3584 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003585 return true;
3586 }
3587 } catch (Exception e) {
3588 // ignore
3589 } finally {
3590 try {
3591 socket.close();
3592 } catch (Exception e) {
3593 // ignore
3594 }
3595 }
3596 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003597 }
3598
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003599 /**
3600 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003601 * and not available in ConnectivityManager. Permissions are checked
3602 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003603 * @hide
3604 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003605 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003606 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003607 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003608 int user = UserHandle.getUserId(Binder.getCallingUid());
3609 synchronized(mVpns) {
3610 return mVpns.get(user).prepare(oldPackage, newPackage);
3611 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003612 }
3613
Chad Brubaker31de0b62013-07-11 13:29:30 -07003614 @Override
3615 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3616 enforceMarkNetworkSocketPermission();
3617 final long token = Binder.clearCallingIdentity();
3618 try {
3619 int mark = mNetd.getMarkForUid(uid);
3620 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3621 if (mark == -1) {
3622 mark = 0;
3623 }
3624 NetworkUtils.markSocket(socket.getFd(), mark);
3625 } catch (RemoteException e) {
3626 } finally {
3627 Binder.restoreCallingIdentity(token);
3628 }
3629 }
3630
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003631 /**
3632 * Configure a TUN interface and return its file descriptor. Parameters
3633 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003634 * and not available in ConnectivityManager. Permissions are checked in
3635 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003636 * @hide
3637 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003638 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003639 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003640 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003641 int user = UserHandle.getUserId(Binder.getCallingUid());
3642 synchronized(mVpns) {
3643 return mVpns.get(user).establish(config);
3644 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003645 }
3646
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003647 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003648 * Start legacy VPN, controlling native daemons as needed. Creates a
3649 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003650 */
3651 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003652 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003653 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003654 final LinkProperties egress = getActiveLinkProperties();
3655 if (egress == null) {
3656 throw new IllegalStateException("Missing active network connection");
3657 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003658 int user = UserHandle.getUserId(Binder.getCallingUid());
3659 synchronized(mVpns) {
3660 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3661 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003662 }
3663
3664 /**
3665 * Return the information of the ongoing legacy VPN. This method is used
3666 * by VpnSettings and not available in ConnectivityManager. Permissions
3667 * are checked in Vpn class.
3668 * @hide
3669 */
3670 @Override
3671 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003672 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003673 int user = UserHandle.getUserId(Binder.getCallingUid());
3674 synchronized(mVpns) {
3675 return mVpns.get(user).getLegacyVpnInfo();
3676 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003677 }
3678
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003679 /**
Chad Brubaker7dcfa2a2013-07-16 18:59:12 -07003680 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3681 * not available in ConnectivityManager.
3682 * Permissions are checked in Vpn class.
3683 * @hide
3684 */
3685 @Override
3686 public VpnConfig getVpnConfig() {
3687 int user = UserHandle.getUserId(Binder.getCallingUid());
3688 synchronized(mVpns) {
3689 return mVpns.get(user).getVpnConfig();
3690 }
3691 }
3692
3693 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003694 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3695 * through NetworkStateTracker since it works differently. For example, it
3696 * needs to override DNS servers but never takes the default routes. It
3697 * relies on another data network, and it could keep existing connections
3698 * alive after reconnecting, switching between networks, or even resuming
3699 * from deep sleep. Calls from applications should be done synchronously
3700 * to avoid race conditions. As these are all hidden APIs, refactoring can
3701 * be done whenever a better abstraction is developed.
3702 */
3703 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003704 private VpnCallback() {
3705 }
3706
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003707 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003708 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003709 }
3710
Chad Brubakerccae0d32013-06-14 11:16:51 -07003711 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003712 if (dnsServers == null) {
3713 restore();
3714 return;
3715 }
3716
3717 // Convert DNS servers into addresses.
3718 List<InetAddress> addresses = new ArrayList<InetAddress>();
3719 for (String address : dnsServers) {
3720 // Double check the addresses and remove invalid ones.
3721 try {
3722 addresses.add(InetAddress.parseNumericAddress(address));
3723 } catch (Exception e) {
3724 // ignore
3725 }
3726 }
3727 if (addresses.isEmpty()) {
3728 restore();
3729 return;
3730 }
3731
3732 // Concatenate search domains into a string.
3733 StringBuilder buffer = new StringBuilder();
3734 if (searchDomains != null) {
3735 for (String domain : searchDomains) {
3736 buffer.append(domain).append(' ');
3737 }
3738 }
3739 String domains = buffer.toString().trim();
3740
3741 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003742 synchronized (mDnsLock) {
Chad Brubaker45e721f2013-07-23 17:13:36 -07003743 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003744 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003745
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003746 // Temporarily disable the default proxy (not global).
3747 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003748 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003749 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003750 sendProxyBroadcast(null);
3751 }
3752 }
3753
3754 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003755 }
3756
Chia-chi Yehcc844502011-07-14 18:01:57 -07003757 public void restore() {
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003758 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003759 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003760 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003761 sendProxyBroadcast(mDefaultProxy);
3762 }
3763 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003764 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003765
3766 public void protect(ParcelFileDescriptor socket) {
3767 try {
3768 final int mark = mNetd.getMarkForProtect();
3769 NetworkUtils.markSocket(socket.getFd(), mark);
3770 } catch (RemoteException e) {
3771 }
3772 }
3773
3774 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3775 for (RouteInfo route : routes) {
3776 try {
3777 mNetd.setMarkedForwardingRoute(interfaze, route);
3778 } catch (RemoteException e) {
3779 }
3780 }
3781 }
3782
3783 public void setMarkedForwarding(String interfaze) {
3784 try {
3785 mNetd.setMarkedForwarding(interfaze);
3786 } catch (RemoteException e) {
3787 }
3788 }
3789
3790 public void clearMarkedForwarding(String interfaze) {
3791 try {
3792 mNetd.clearMarkedForwarding(interfaze);
3793 } catch (RemoteException e) {
3794 }
3795 }
3796
Robert Greenwalt68534c82013-09-24 11:05:57 -07003797 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003798 int uidStart = uid * UserHandle.PER_USER_RANGE;
3799 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003800 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003801 }
3802
Robert Greenwalt68534c82013-09-24 11:05:57 -07003803 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003804 int uidStart = uid * UserHandle.PER_USER_RANGE;
3805 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003806 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003807 }
3808
Robert Greenwalt68534c82013-09-24 11:05:57 -07003809 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3810 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003811 try {
3812 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003813 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003814 } catch (RemoteException e) {
3815 }
3816
3817 }
3818
Robert Greenwalt68534c82013-09-24 11:05:57 -07003819 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3820 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003821 try {
3822 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003823 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003824 } catch (RemoteException e) {
3825 }
3826
3827 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003828 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003829
3830 @Override
3831 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003832 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3833 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3834 return false;
3835 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003836
3837 // Tear down existing lockdown if profile was removed
3838 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3839 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003840 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003841 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3842 return false;
3843 }
3844
3845 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3846 final VpnProfile profile = VpnProfile.decode(
3847 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerccae0d32013-06-14 11:16:51 -07003848 int user = UserHandle.getUserId(Binder.getCallingUid());
3849 synchronized(mVpns) {
3850 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3851 profile));
3852 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003853 } else {
3854 setLockdownTracker(null);
3855 }
3856
3857 return true;
3858 }
3859
3860 /**
3861 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3862 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3863 */
3864 private void setLockdownTracker(LockdownVpnTracker tracker) {
3865 // Shutdown any existing tracker
3866 final LockdownVpnTracker existing = mLockdownTracker;
3867 mLockdownTracker = null;
3868 if (existing != null) {
3869 existing.shutdown();
3870 }
3871
3872 try {
3873 if (tracker != null) {
3874 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003875 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003876 mLockdownTracker = tracker;
3877 mLockdownTracker.init();
3878 } else {
3879 mNetd.setFirewallEnabled(false);
3880 }
3881 } catch (RemoteException e) {
3882 // ignored; NMS lives inside system_server
3883 }
3884 }
3885
3886 private void throwIfLockdownEnabled() {
3887 if (mLockdownEnabled) {
3888 throw new IllegalStateException("Unavailable in lockdown mode");
3889 }
3890 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003891
3892 public void supplyMessenger(int networkType, Messenger messenger) {
3893 enforceConnectivityInternalPermission();
3894
3895 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3896 mNetTrackers[networkType].supplyMessenger(messenger);
3897 }
3898 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003899
3900 public int findConnectionTypeForIface(String iface) {
3901 enforceConnectivityInternalPermission();
3902
3903 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3904 for (NetworkStateTracker tracker : mNetTrackers) {
3905 if (tracker != null) {
3906 LinkProperties lp = tracker.getLinkProperties();
3907 if (lp != null && iface.equals(lp.getInterfaceName())) {
3908 return tracker.getNetworkInfo().getType();
3909 }
3910 }
3911 }
3912 return ConnectivityManager.TYPE_NONE;
3913 }
Wink Saville690cb182013-06-29 21:10:57 -07003914
3915 /**
3916 * Have mobile data fail fast if enabled.
3917 *
3918 * @param enabled DctConstants.ENABLED/DISABLED
3919 */
3920 private void setEnableFailFastMobileData(int enabled) {
3921 int tag;
3922
3923 if (enabled == DctConstants.ENABLED) {
3924 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3925 } else {
3926 tag = mEnableFailFastMobileDataTag.get();
3927 }
3928 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3929 enabled));
3930 }
3931
Wink Savillebc588402013-08-16 17:17:28 -07003932 private boolean isMobileDataStateTrackerReady() {
3933 MobileDataStateTracker mdst =
Wink Saville89c87b92013-08-29 08:55:16 -07003934 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savillebc588402013-08-16 17:17:28 -07003935 return (mdst != null) && (mdst.isReady());
3936 }
3937
Wink Saville89c87b92013-08-29 08:55:16 -07003938 /**
3939 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3940 */
3941
3942 /**
3943 * No connection was possible to the network.
Wink Savillea3041492013-09-06 09:53:08 -07003944 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003945 */
Wink Savillea3041492013-09-06 09:53:08 -07003946 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville89c87b92013-08-29 08:55:16 -07003947
3948 /**
3949 * A connection was made to the internet, all is well.
Wink Savillea3041492013-09-06 09:53:08 -07003950 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003951 */
Wink Savillea3041492013-09-06 09:53:08 -07003952 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville89c87b92013-08-29 08:55:16 -07003953
3954 /**
3955 * A connection was made but no dns server was available to resolve a name to address.
Wink Savillea3041492013-09-06 09:53:08 -07003956 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003957 */
Wink Savillea3041492013-09-06 09:53:08 -07003958 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville89c87b92013-08-29 08:55:16 -07003959
3960 /**
3961 * A connection was made but could not open a TCP connection.
Wink Savillea3041492013-09-06 09:53:08 -07003962 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003963 */
Wink Savillea3041492013-09-06 09:53:08 -07003964 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3965
3966 /**
3967 * A connection was made but there was a redirection, we appear to be in walled garden.
3968 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3969 */
3970 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville89c87b92013-08-29 08:55:16 -07003971
3972 /**
3973 * The mobile network is a provisioning network.
Wink Savillea3041492013-09-06 09:53:08 -07003974 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville89c87b92013-08-29 08:55:16 -07003975 */
Wink Savillea3041492013-09-06 09:53:08 -07003976 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville89c87b92013-08-29 08:55:16 -07003977
Wink Savillea3041492013-09-06 09:53:08 -07003978 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville89c87b92013-08-29 08:55:16 -07003979
Wink Saville690cb182013-06-29 21:10:57 -07003980 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07003981 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3982 int timeOutMs = -1;
3983 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3984 enforceConnectivityInternalPermission();
Wink Savillefdb84862013-07-02 10:55:14 -07003985
Wink Saville690cb182013-06-29 21:10:57 -07003986 final long token = Binder.clearCallingIdentity();
3987 try {
Wink Saville89c87b92013-08-29 08:55:16 -07003988 timeOutMs = suggestedTimeOutMs;
3989 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3990 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3991 }
3992
3993 // Check that mobile networks are supported
3994 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3995 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3996 if (DBG) log("checkMobileProvisioning: X no mobile network");
3997 return timeOutMs;
3998 }
3999
4000 // If we're already checking don't do it again
4001 // TODO: Add a queue of results...
4002 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4003 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4004 return timeOutMs;
4005 }
4006
Wink Savillea65f4732013-10-03 08:34:46 -07004007 // Start off with mobile notification off
4008 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004009
Wink Saville690cb182013-06-29 21:10:57 -07004010 CheckMp checkMp = new CheckMp(mContext, this);
4011 CheckMp.CallBack cb = new CheckMp.CallBack() {
4012 @Override
4013 void onComplete(Integer result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004014 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004015 NetworkInfo ni =
4016 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4017 switch(result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004018 case CMP_RESULT_CODE_CONNECTABLE:
Wink Savillea3041492013-09-06 09:53:08 -07004019 case CMP_RESULT_CODE_NO_CONNECTION:
4020 case CMP_RESULT_CODE_NO_DNS:
4021 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville89c87b92013-08-29 08:55:16 -07004022 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville690cb182013-06-29 21:10:57 -07004023 break;
4024 }
Wink Saville89c87b92013-08-29 08:55:16 -07004025 case CMP_RESULT_CODE_REDIRECTED: {
4026 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004027 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004028 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004029 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004030 }
4031 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004032 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004033 setProvNotificationVisible(true,
4034 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004035 url);
Wink Saville690cb182013-06-29 21:10:57 -07004036 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004037 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004038 }
4039 break;
4040 }
Wink Savillea3041492013-09-06 09:53:08 -07004041 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004042 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004043 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004044 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004045 setProvNotificationVisible(true,
4046 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004047 url);
Wink Saville690cb182013-06-29 21:10:57 -07004048 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004049 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004050 }
4051 break;
4052 }
4053 default: {
4054 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4055 break;
4056 }
4057 }
Wink Saville89c87b92013-08-29 08:55:16 -07004058 mIsCheckingMobileProvisioning.set(false);
Wink Saville690cb182013-06-29 21:10:57 -07004059 }
4060 };
4061 CheckMp.Params params =
4062 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville89c87b92013-08-29 08:55:16 -07004063 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville690cb182013-06-29 21:10:57 -07004064 checkMp.execute(params);
4065 } finally {
4066 Binder.restoreCallingIdentity(token);
Wink Saville89c87b92013-08-29 08:55:16 -07004067 if (DBG) log("checkMobileProvisioning: X");
Wink Saville690cb182013-06-29 21:10:57 -07004068 }
4069 return timeOutMs;
4070 }
4071
4072 static class CheckMp extends
4073 AsyncTask<CheckMp.Params, Void, Integer> {
4074 private static final String CHECKMP_TAG = "CheckMp";
Wink Saville8fe05f12013-10-31 06:35:22 -07004075
4076 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4077 private static boolean mTestingFailures;
4078
4079 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4080 private static final int MAX_LOOPS = 4;
4081
4082 // Number of milli-seconds to complete all of the retires
Wink Saville690cb182013-06-29 21:10:57 -07004083 public static final int MAX_TIMEOUT_MS = 60000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004084
4085 // The socket should retry only 5 seconds, the default is longer
Wink Saville690cb182013-06-29 21:10:57 -07004086 private static final int SOCKET_TIMEOUT_MS = 5000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004087
4088 // Sleep time for network errors
4089 private static final int NET_ERROR_SLEEP_SEC = 3;
4090
4091 // Sleep time for network route establishment
4092 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4093
4094 // Short sleep time for polling :(
4095 private static final int POLLING_SLEEP_SEC = 1;
4096
Wink Saville690cb182013-06-29 21:10:57 -07004097 private Context mContext;
4098 private ConnectivityService mCs;
4099 private TelephonyManager mTm;
4100 private Params mParams;
4101
4102 /**
4103 * Parameters for AsyncTask.execute
4104 */
4105 static class Params {
4106 private String mUrl;
4107 private long mTimeOutMs;
4108 private CallBack mCb;
4109
4110 Params(String url, long timeOutMs, CallBack cb) {
4111 mUrl = url;
4112 mTimeOutMs = timeOutMs;
4113 mCb = cb;
4114 }
4115
4116 @Override
4117 public String toString() {
4118 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4119 }
4120 }
4121
Wink Saville8fe05f12013-10-31 06:35:22 -07004122 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4123 // issued by name or ip address, for Google its by name so when we construct
4124 // this HostnameVerifier we'll pass the original Uri and use it to verify
4125 // the host. If the host name in the original uril fails we'll test the
4126 // hostname parameter just incase things change.
4127 static class CheckMpHostnameVerifier implements HostnameVerifier {
4128 Uri mOrgUri;
4129
4130 CheckMpHostnameVerifier(Uri orgUri) {
4131 mOrgUri = orgUri;
4132 }
4133
4134 @Override
4135 public boolean verify(String hostname, SSLSession session) {
4136 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4137 String orgUriHost = mOrgUri.getHost();
4138 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4139 if (DBG) {
4140 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4141 + " orgUriHost=" + orgUriHost);
4142 }
4143 return retVal;
4144 }
4145 }
4146
Wink Saville690cb182013-06-29 21:10:57 -07004147 /**
4148 * The call back object passed in Params. onComplete will be called
4149 * on the main thread.
4150 */
4151 abstract static class CallBack {
4152 // Called on the main thread.
4153 abstract void onComplete(Integer result);
4154 }
4155
4156 public CheckMp(Context context, ConnectivityService cs) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004157 if (Build.IS_DEBUGGABLE) {
4158 mTestingFailures =
4159 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4160 } else {
4161 mTestingFailures = false;
4162 }
4163
Wink Saville690cb182013-06-29 21:10:57 -07004164 mContext = context;
4165 mCs = cs;
4166
4167 // Setup access to TelephonyService we'll be using.
4168 mTm = (TelephonyManager) mContext.getSystemService(
4169 Context.TELEPHONY_SERVICE);
4170 }
4171
4172 /**
4173 * Get the default url to use for the test.
4174 */
4175 public String getDefaultUrl() {
4176 // See http://go/clientsdns for usage approval
4177 String server = Settings.Global.getString(mContext.getContentResolver(),
4178 Settings.Global.CAPTIVE_PORTAL_SERVER);
4179 if (server == null) {
4180 server = "clients3.google.com";
4181 }
4182 return "http://" + server + "/generate_204";
4183 }
4184
4185 /**
4186 * Detect if its possible to connect to the http url. DNS based detection techniques
4187 * do not work at all hotspots. The best way to check is to perform a request to
4188 * a known address that fetches the data we expect.
4189 */
4190 private synchronized Integer isMobileOk(Params params) {
Wink Saville89c87b92013-08-29 08:55:16 -07004191 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004192 Uri orgUri = Uri.parse(params.mUrl);
4193 Random rand = new Random();
4194 mParams = params;
4195
Wink Saville37e73122013-08-13 12:41:06 -07004196 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004197 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville39856712013-09-13 12:40:11 -07004198 log("isMobileOk: X not mobile capable result=" + result);
4199 return result;
4200 }
4201
4202 // See if we've already determined we've got a provisioning connection,
4203 // if so we don't need to do anything active.
4204 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4205 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4206 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4207 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4208
4209 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4210 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4211 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4212 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4213
4214 if (isDefaultProvisioning || isHipriProvisioning) {
4215 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4216 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville37e73122013-08-13 12:41:06 -07004217 return result;
4218 }
Wink Saville690cb182013-06-29 21:10:57 -07004219
Wink Saville37e73122013-08-13 12:41:06 -07004220 try {
Wink Saville690cb182013-06-29 21:10:57 -07004221 // Continue trying to connect until time has run out
4222 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville4a165bb2013-08-07 11:02:57 -07004223
Wink Savillebc588402013-08-16 17:17:28 -07004224 if (!mCs.isMobileDataStateTrackerReady()) {
4225 // Wait for MobileDataStateTracker to be ready.
4226 if (DBG) log("isMobileOk: mdst is not ready");
4227 while(SystemClock.elapsedRealtime() < endTime) {
4228 if (mCs.isMobileDataStateTrackerReady()) {
4229 // Enable fail fast as we'll do retries here and use a
4230 // hipri connection so the default connection stays active.
4231 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4232 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4233 break;
4234 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004235 sleep(POLLING_SLEEP_SEC);
Wink Savillebc588402013-08-16 17:17:28 -07004236 }
4237 }
4238
4239 log("isMobileOk: start hipri url=" + params.mUrl);
4240
Wink Saville4a165bb2013-08-07 11:02:57 -07004241 // First wait until we can start using hipri
4242 Binder binder = new Binder();
4243 while(SystemClock.elapsedRealtime() < endTime) {
4244 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4245 Phone.FEATURE_ENABLE_HIPRI, binder);
4246 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4247 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4248 log("isMobileOk: hipri started");
4249 break;
4250 }
4251 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville89c87b92013-08-29 08:55:16 -07004252 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville8fe05f12013-10-31 06:35:22 -07004253 sleep(POLLING_SLEEP_SEC);
Wink Saville4a165bb2013-08-07 11:02:57 -07004254 }
4255
4256 // Continue trying to connect until time has run out
Wink Saville690cb182013-06-29 21:10:57 -07004257 while(SystemClock.elapsedRealtime() < endTime) {
4258 try {
4259 // Wait for hipri to connect.
4260 // TODO: Don't poll and handle situation where hipri fails
4261 // because default is retrying. See b/9569540
4262 NetworkInfo.State state = mCs
4263 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4264 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville89c87b92013-08-29 08:55:16 -07004265 if (true/*VDBG*/) {
Wink Saville27f92732013-07-31 15:49:04 -07004266 log("isMobileOk: not connected ni=" +
Wink Saville690cb182013-06-29 21:10:57 -07004267 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville27f92732013-07-31 15:49:04 -07004268 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004269 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004270 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004271 continue;
4272 }
4273
Wink Saville89c87b92013-08-29 08:55:16 -07004274 // Hipri has started check if this is a provisioning url
4275 MobileDataStateTracker mdst = (MobileDataStateTracker)
4276 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4277 if (mdst.isProvisioningNetwork()) {
Wink Savillea3041492013-09-06 09:53:08 -07004278 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville39856712013-09-13 12:40:11 -07004279 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville89c87b92013-08-29 08:55:16 -07004280 return result;
4281 } else {
4282 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4283 }
4284
Wink Saville690cb182013-06-29 21:10:57 -07004285 // Get of the addresses associated with the url host. We need to use the
4286 // address otherwise HttpURLConnection object will use the name to get
Wink Saville8fe05f12013-10-31 06:35:22 -07004287 // the addresses and will try every address but that will bypass the
Wink Saville690cb182013-06-29 21:10:57 -07004288 // route to host we setup and the connection could succeed as the default
4289 // interface might be connected to the internet via wifi or other interface.
4290 InetAddress[] addresses;
4291 try {
4292 addresses = InetAddress.getAllByName(orgUri.getHost());
4293 } catch (UnknownHostException e) {
Wink Saville89c87b92013-08-29 08:55:16 -07004294 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville39856712013-09-13 12:40:11 -07004295 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004296 return result;
4297 }
4298 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4299
4300 // Get the type of addresses supported by this link
4301 LinkProperties lp = mCs.getLinkProperties(
4302 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti662b96c2013-08-08 11:00:12 +09004303 boolean linkHasIpv4 = lp.hasIPv4Address();
4304 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville690cb182013-06-29 21:10:57 -07004305 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4306 + " linkHasIpv6=" + linkHasIpv6);
4307
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004308 final ArrayList<InetAddress> validAddresses =
4309 new ArrayList<InetAddress>(addresses.length);
Wink Saville690cb182013-06-29 21:10:57 -07004310
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004311 for (InetAddress addr : addresses) {
4312 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4313 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4314 validAddresses.add(addr);
Wink Saville690cb182013-06-29 21:10:57 -07004315 }
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004316 }
4317
4318 if (validAddresses.size() == 0) {
4319 return CMP_RESULT_CODE_NO_CONNECTION;
4320 }
4321
4322 int addrTried = 0;
4323 while (true) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004324 // Loop through at most MAX_LOOPS valid addresses or until
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004325 // we run out of time
Wink Saville8fe05f12013-10-31 06:35:22 -07004326 if (addrTried++ >= MAX_LOOPS) {
4327 log("isMobileOk: too many loops tried - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004328 break;
4329 }
4330 if (SystemClock.elapsedRealtime() >= endTime) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004331 log("isMobileOk: spend too much time - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004332 break;
4333 }
4334
4335 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4336 validAddresses.size()));
Wink Saville690cb182013-06-29 21:10:57 -07004337
4338 // Make a route to host so we check the specific interface.
4339 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4340 hostAddr.getAddress())) {
4341 // Wait a short time to be sure the route is established ??
4342 log("isMobileOk:"
4343 + " wait to establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004344 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004345 } else {
4346 log("isMobileOk:"
4347 + " could not establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004348 // Wait a short time before the next attempt
4349 sleep(NET_ERROR_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004350 continue;
4351 }
4352
Wink Saville8fe05f12013-10-31 06:35:22 -07004353 // Rewrite the url to have numeric address to use the specific route
4354 // using http for half the attempts and https for the other half.
4355 // Doing https first and http second as on a redirected walled garden
4356 // such as t-mobile uses we get a SocketTimeoutException: "SSL
4357 // handshake timed out" which we declare as
4358 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4359 // having http second we will be using logic used for some time.
4360 URL newUrl;
4361 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4362 newUrl = new URL(scheme, hostAddr.getHostAddress(),
4363 orgUri.getPath());
Wink Saville690cb182013-06-29 21:10:57 -07004364 log("isMobileOk: newUrl=" + newUrl);
4365
4366 HttpURLConnection urlConn = null;
4367 try {
Wink Saville8fe05f12013-10-31 06:35:22 -07004368 // Open the connection set the request headers and get the response
4369 urlConn = (HttpURLConnection)newUrl.openConnection(
Wink Saville690cb182013-06-29 21:10:57 -07004370 java.net.Proxy.NO_PROXY);
Wink Saville8fe05f12013-10-31 06:35:22 -07004371 if (scheme.equals("https")) {
4372 ((HttpsURLConnection)urlConn).setHostnameVerifier(
4373 new CheckMpHostnameVerifier(orgUri));
4374 }
Wink Saville690cb182013-06-29 21:10:57 -07004375 urlConn.setInstanceFollowRedirects(false);
4376 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4377 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4378 urlConn.setUseCaches(false);
4379 urlConn.setAllowUserInteraction(false);
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004380 // Set the "Connection" to "Close" as by default "Keep-Alive"
4381 // is used which is useless in this case.
Wink Saville690cb182013-06-29 21:10:57 -07004382 urlConn.setRequestProperty("Connection", "close");
4383 int responseCode = urlConn.getResponseCode();
Wink Savillea3041492013-09-06 09:53:08 -07004384
4385 // For debug display the headers
4386 Map<String, List<String>> headers = urlConn.getHeaderFields();
4387 log("isMobileOk: headers=" + headers);
4388
4389 // Close the connection
Wink Saville690cb182013-06-29 21:10:57 -07004390 urlConn.disconnect();
4391 urlConn = null;
Wink Savillea3041492013-09-06 09:53:08 -07004392
Wink Saville8fe05f12013-10-31 06:35:22 -07004393 if (mTestingFailures) {
4394 // Pretend no connection, this tests using http and https
4395 result = CMP_RESULT_CODE_NO_CONNECTION;
4396 log("isMobileOk: TESTING_FAILURES, pretend no connction");
4397 continue;
4398 }
4399
Wink Savillea3041492013-09-06 09:53:08 -07004400 if (responseCode == 204) {
4401 // Return
Wink Savillea3041492013-09-06 09:53:08 -07004402 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville8fe05f12013-10-31 06:35:22 -07004403 log("isMobileOk: X got expected responseCode=" + responseCode
Wink Saville39856712013-09-13 12:40:11 -07004404 + " result=" + result);
Wink Savillea3041492013-09-06 09:53:08 -07004405 return result;
4406 } else {
4407 // Retry to be sure this was redirected, we've gotten
4408 // occasions where a server returned 200 even though
4409 // the device didn't have a "warm" sim.
4410 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004411 // TODO - it would be nice in the single-address case to do
4412 // another DNS resolve here, but flushing the cache is a bit
4413 // heavy-handed.
Wink Savillea3041492013-09-06 09:53:08 -07004414 result = CMP_RESULT_CODE_REDIRECTED;
4415 }
Wink Saville690cb182013-06-29 21:10:57 -07004416 } catch (Exception e) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004417 log("isMobileOk: HttpURLConnection Exception" + e);
Wink Savillea3041492013-09-06 09:53:08 -07004418 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004419 if (urlConn != null) {
4420 urlConn.disconnect();
4421 urlConn = null;
4422 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004423 sleep(NET_ERROR_SLEEP_SEC);
4424 continue;
Wink Saville690cb182013-06-29 21:10:57 -07004425 }
4426 }
Wink Saville39856712013-09-13 12:40:11 -07004427 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004428 return result;
4429 } catch (Exception e) {
4430 log("isMobileOk: Exception e=" + e);
4431 continue;
4432 }
4433 }
4434 log("isMobileOk: timed out");
4435 } finally {
4436 log("isMobileOk: F stop hipri");
4437 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4438 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4439 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville89c87b92013-08-29 08:55:16 -07004440
4441 // Wait for hipri to disconnect.
4442 long endTime = SystemClock.elapsedRealtime() + 5000;
4443
4444 while(SystemClock.elapsedRealtime() < endTime) {
4445 NetworkInfo.State state = mCs
4446 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4447 if (state != NetworkInfo.State.DISCONNECTED) {
4448 if (VDBG) {
4449 log("isMobileOk: connected ni=" +
4450 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4451 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004452 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004453 continue;
4454 }
4455 }
4456
Wink Saville690cb182013-06-29 21:10:57 -07004457 log("isMobileOk: X result=" + result);
4458 }
4459 return result;
4460 }
4461
4462 @Override
4463 protected Integer doInBackground(Params... params) {
4464 return isMobileOk(params[0]);
4465 }
4466
4467 @Override
4468 protected void onPostExecute(Integer result) {
4469 log("onPostExecute: result=" + result);
4470 if ((mParams != null) && (mParams.mCb != null)) {
4471 mParams.mCb.onComplete(result);
4472 }
4473 }
4474
4475 private String inetAddressesToString(InetAddress[] addresses) {
4476 StringBuffer sb = new StringBuffer();
4477 boolean firstTime = true;
4478 for(InetAddress addr : addresses) {
4479 if (firstTime) {
4480 firstTime = false;
4481 } else {
4482 sb.append(",");
4483 }
4484 sb.append(addr);
4485 }
4486 return sb.toString();
4487 }
4488
4489 private void printNetworkInfo() {
4490 boolean hasIccCard = mTm.hasIccCard();
4491 int simState = mTm.getSimState();
4492 log("hasIccCard=" + hasIccCard
4493 + " simState=" + simState);
4494 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4495 if (ni != null) {
4496 log("ni.length=" + ni.length);
4497 for (NetworkInfo netInfo: ni) {
4498 log("netInfo=" + netInfo.toString());
4499 }
4500 } else {
4501 log("no network info ni=null");
4502 }
4503 }
4504
4505 /**
4506 * Sleep for a few seconds then return.
4507 * @param seconds
4508 */
4509 private static void sleep(int seconds) {
4510 try {
4511 Thread.sleep(seconds * 1000);
4512 } catch (InterruptedException e) {
4513 e.printStackTrace();
4514 }
4515 }
4516
Wink Saville8fe05f12013-10-31 06:35:22 -07004517 private static void log(String s) {
Wink Saville690cb182013-06-29 21:10:57 -07004518 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4519 }
4520 }
4521
Wink Saville89c87b92013-08-29 08:55:16 -07004522 // TODO: Move to ConnectivityManager and make public?
4523 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4524 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville690cb182013-06-29 21:10:57 -07004525
Wink Saville89c87b92013-08-29 08:55:16 -07004526 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4527 @Override
4528 public void onReceive(Context context, Intent intent) {
4529 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4530 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4531 }
4532 }
4533 };
4534
4535 private void handleMobileProvisioningAction(String url) {
4536 // Notication mark notification as not visible
Wink Savillea65f4732013-10-03 08:34:46 -07004537 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004538
4539 // If provisioning network handle as a special case,
4540 // otherwise launch browser with the intent directly.
4541 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville860f5282013-09-05 12:02:25 -07004542 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07004543 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4544 MobileDataStateTracker mdst = (MobileDataStateTracker)
4545 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4546 mdst.enableMobileProvisioning(url);
4547 } else {
4548 if (DBG) log("handleMobileProvisioningAction: on default network");
Robert Greenwaltac8d55a2013-10-17 12:46:52 -07004549 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4550 Intent.CATEGORY_APP_BROWSER);
4551 newIntent.setData(Uri.parse(url));
Wink Saville89c87b92013-08-29 08:55:16 -07004552 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4553 Intent.FLAG_ACTIVITY_NEW_TASK);
4554 try {
4555 mContext.startActivity(newIntent);
4556 } catch (ActivityNotFoundException e) {
4557 loge("handleMobileProvisioningAction: startActivity failed" + e);
4558 }
4559 }
4560 }
4561
4562 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4563 private volatile boolean mIsNotificationVisible = false;
4564
4565 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4566 String url) {
4567 if (DBG) {
4568 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4569 + " extraInfo=" + extraInfo + " url=" + url);
4570 }
Wink Saville690cb182013-06-29 21:10:57 -07004571
4572 Resources r = Resources.getSystem();
4573 NotificationManager notificationManager = (NotificationManager) mContext
4574 .getSystemService(Context.NOTIFICATION_SERVICE);
4575
4576 if (visible) {
4577 CharSequence title;
4578 CharSequence details;
4579 int icon;
Wink Saville89c87b92013-08-29 08:55:16 -07004580 Intent intent;
4581 Notification notification = new Notification();
4582 switch (networkType) {
Wink Saville690cb182013-06-29 21:10:57 -07004583 case ConnectivityManager.TYPE_WIFI:
Wink Saville690cb182013-06-29 21:10:57 -07004584 title = r.getString(R.string.wifi_available_sign_in, 0);
4585 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004586 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004587 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004588 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4589 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4590 Intent.FLAG_ACTIVITY_NEW_TASK);
4591 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004592 break;
4593 case ConnectivityManager.TYPE_MOBILE:
4594 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville690cb182013-06-29 21:10:57 -07004595 title = r.getString(R.string.network_available_sign_in, 0);
4596 // TODO: Change this to pull from NetworkInfo once a printable
4597 // name has been added to it
4598 details = mTelephonyManager.getNetworkOperatorName();
4599 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004600 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4601 intent.putExtra("EXTRA_URL", url);
4602 intent.setFlags(0);
4603 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004604 break;
4605 default:
Wink Saville690cb182013-06-29 21:10:57 -07004606 title = r.getString(R.string.network_available_sign_in, 0);
4607 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004608 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004609 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004610 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4611 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4612 Intent.FLAG_ACTIVITY_NEW_TASK);
4613 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004614 break;
4615 }
4616
Wink Saville690cb182013-06-29 21:10:57 -07004617 notification.when = 0;
4618 notification.icon = icon;
4619 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville690cb182013-06-29 21:10:57 -07004620 notification.tickerText = title;
4621 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4622
Wink Saville89c87b92013-08-29 08:55:16 -07004623 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004624 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville89c87b92013-08-29 08:55:16 -07004625 } catch (NullPointerException npe) {
4626 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4627 npe.printStackTrace();
4628 }
Wink Saville690cb182013-06-29 21:10:57 -07004629 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004630 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004631 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville89c87b92013-08-29 08:55:16 -07004632 } catch (NullPointerException npe) {
4633 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4634 npe.printStackTrace();
4635 }
Wink Saville690cb182013-06-29 21:10:57 -07004636 }
Wink Saville89c87b92013-08-29 08:55:16 -07004637 mIsNotificationVisible = visible;
Wink Saville690cb182013-06-29 21:10:57 -07004638 }
4639
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004640 /** Location to an updatable file listing carrier provisioning urls.
4641 * An example:
4642 *
4643 * <?xml version="1.0" encoding="utf-8"?>
4644 * <provisioningUrls>
4645 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4646 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4647 * </provisioningUrls>
4648 */
4649 private static final String PROVISIONING_URL_PATH =
4650 "/data/misc/radio/provisioning_urls.xml";
4651 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004652
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004653 /** XML tag for root element. */
4654 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4655 /** XML tag for individual url */
4656 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4657 /** XML tag for redirected url */
4658 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4659 /** XML attribute for mcc */
4660 private static final String ATTR_MCC = "mcc";
4661 /** XML attribute for mnc */
4662 private static final String ATTR_MNC = "mnc";
4663
4664 private static final int REDIRECTED_PROVISIONING = 1;
4665 private static final int PROVISIONING = 2;
4666
4667 private String getProvisioningUrlBaseFromFile(int type) {
4668 FileReader fileReader = null;
4669 XmlPullParser parser = null;
4670 Configuration config = mContext.getResources().getConfiguration();
4671 String tagType;
4672
4673 switch (type) {
4674 case PROVISIONING:
4675 tagType = TAG_PROVISIONING_URL;
4676 break;
4677 case REDIRECTED_PROVISIONING:
4678 tagType = TAG_REDIRECTED_URL;
4679 break;
4680 default:
4681 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4682 type);
4683 }
4684
4685 try {
4686 fileReader = new FileReader(mProvisioningUrlFile);
4687 parser = Xml.newPullParser();
4688 parser.setInput(fileReader);
4689 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4690
4691 while (true) {
4692 XmlUtils.nextElement(parser);
4693
4694 String element = parser.getName();
4695 if (element == null) break;
4696
4697 if (element.equals(tagType)) {
4698 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4699 try {
4700 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4701 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4702 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4703 parser.next();
4704 if (parser.getEventType() == XmlPullParser.TEXT) {
4705 return parser.getText();
4706 }
4707 }
4708 }
4709 } catch (NumberFormatException e) {
4710 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4711 }
4712 }
4713 }
4714 return null;
4715 } catch (FileNotFoundException e) {
4716 loge("Carrier Provisioning Urls file not found");
4717 } catch (XmlPullParserException e) {
4718 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4719 } catch (IOException e) {
4720 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4721 } finally {
4722 if (fileReader != null) {
4723 try {
4724 fileReader.close();
4725 } catch (IOException e) {}
4726 }
4727 }
4728 return null;
4729 }
4730
Wink Savillef714b7f2013-07-20 20:31:59 -07004731 @Override
4732 public String getMobileRedirectedProvisioningUrl() {
4733 enforceConnectivityInternalPermission();
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004734 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4735 if (TextUtils.isEmpty(url)) {
4736 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4737 }
4738 return url;
4739 }
4740
Wink Savillef714b7f2013-07-20 20:31:59 -07004741 @Override
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004742 public String getMobileProvisioningUrl() {
4743 enforceConnectivityInternalPermission();
4744 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4745 if (TextUtils.isEmpty(url)) {
4746 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillef714b7f2013-07-20 20:31:59 -07004747 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004748 } else {
Wink Savillef714b7f2013-07-20 20:31:59 -07004749 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004750 }
Wink Savilledfabd992013-07-10 23:00:07 -07004751 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004752 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004753 String phoneNumber = mTelephonyManager.getLine1Number();
4754 if (TextUtils.isEmpty(phoneNumber)) {
4755 phoneNumber = "0000000000";
4756 }
Wink Saville690cb182013-06-29 21:10:57 -07004757 url = String.format(url,
4758 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4759 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004760 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004761 }
4762
Wink Saville690cb182013-06-29 21:10:57 -07004763 return url;
4764 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004765
Wink Saville89c87b92013-08-29 08:55:16 -07004766 @Override
4767 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4768 String extraInfo, String url) {
4769 enforceConnectivityInternalPermission();
4770 setProvNotificationVisible(visible, networkType, extraInfo, url);
4771 }
Wink Saville3ade4872013-08-29 14:57:08 -07004772
Yuhao Zheng15019892013-09-09 17:00:04 -07004773 @Override
4774 public void setAirplaneMode(boolean enable) {
4775 enforceConnectivityInternalPermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07004776 final long ident = Binder.clearCallingIdentity();
4777 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07004778 final ContentResolver cr = mContext.getContentResolver();
4779 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4780 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4781 intent.putExtra("state", enable);
Yuhao Zheng15019892013-09-09 17:00:04 -07004782 mContext.sendBroadcast(intent);
4783 } finally {
4784 Binder.restoreCallingIdentity(ident);
4785 }
4786 }
4787
Chad Brubakerccae0d32013-06-14 11:16:51 -07004788 private void onUserStart(int userId) {
4789 synchronized(mVpns) {
4790 Vpn userVpn = mVpns.get(userId);
4791 if (userVpn != null) {
4792 loge("Starting user already has a VPN");
4793 return;
4794 }
4795 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4796 mVpns.put(userId, userVpn);
4797 userVpn.startMonitoring(mContext, mTrackerHandler);
4798 }
4799 }
4800
4801 private void onUserStop(int userId) {
4802 synchronized(mVpns) {
4803 Vpn userVpn = mVpns.get(userId);
4804 if (userVpn == null) {
4805 loge("Stopping user has no VPN");
4806 return;
4807 }
4808 mVpns.delete(userId);
4809 }
4810 }
4811
4812 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4813 @Override
4814 public void onReceive(Context context, Intent intent) {
4815 final String action = intent.getAction();
4816 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4817 if (userId == UserHandle.USER_NULL) return;
4818
4819 if (Intent.ACTION_USER_STARTING.equals(action)) {
4820 onUserStart(userId);
4821 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4822 onUserStop(userId);
4823 }
4824 }
4825 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004826
4827 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004828 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004829 enforceAccessPermission();
4830 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004831 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004832 } else {
4833 return null;
4834 }
4835 }
4836
4837 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004838 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004839 enforceAccessPermission();
4840 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004841 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004842 } else {
4843 return null;
4844 }
4845 }
4846
4847 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004848 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004849 enforceAccessPermission();
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004850 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004851 for (NetworkStateTracker tracker : mNetTrackers) {
4852 if (tracker != null) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004853 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004854 if (li != null) {
4855 result.add(li);
4856 }
4857 }
4858 }
4859
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004860 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004861 }
4862
4863 /* Infrastructure for network sampling */
4864
4865 private void handleNetworkSamplingTimeout() {
4866
4867 log("Sampling interval elapsed, updating statistics ..");
4868
4869 // initialize list of interfaces ..
4870 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4871 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4872 for (NetworkStateTracker tracker : mNetTrackers) {
4873 if (tracker != null) {
4874 String ifaceName = tracker.getNetworkInterfaceName();
4875 if (ifaceName != null) {
4876 mapIfaceToSample.put(ifaceName, null);
4877 }
4878 }
4879 }
4880
4881 // Read samples for all interfaces
4882 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4883
4884 // process samples for all networks
4885 for (NetworkStateTracker tracker : mNetTrackers) {
4886 if (tracker != null) {
4887 String ifaceName = tracker.getNetworkInterfaceName();
4888 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4889 if (ss != null) {
4890 // end the previous sampling cycle
4891 tracker.stopSampling(ss);
4892 // start a new sampling cycle ..
4893 tracker.startSampling(ss);
4894 }
4895 }
4896 }
4897
4898 log("Done.");
4899
4900 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4901 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4902 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4903
4904 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4905
4906 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4907 }
4908
4909 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4910 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4911 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4912 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004913}