blob: b7a1a55e14fccfe3061342135f4ebe00001b3cd4 [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;
Chad Brubaker6c0af462014-02-14 13:24:29 -080035import android.app.AppOpsManager;
Wink Saville690cb182013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080039import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville89c87b92013-08-29 08:55:16 -070040import android.content.ActivityNotFoundException;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070041import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.content.ContentResolver;
43import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090044import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080045import android.content.Intent;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070046import android.content.IntentFilter;
Chad Brubaker6c0af462014-02-14 13:24:29 -080047import android.content.pm.ApplicationInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.content.pm.PackageManager;
Chad Brubaker6c0af462014-02-14 13:24:29 -080049import android.content.pm.PackageManager.NameNotFoundException;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070052import android.database.ContentObserver;
Irfan Sheriffba8388b2012-08-16 12:49:23 -070053import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080055import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080056import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070058import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070059import android.net.INetworkPolicyListener;
60import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070061import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070062import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080063import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070064import android.net.LinkProperties.CompareResult;
Jeff Sharkey86dc7a82013-09-10 21:03:27 -070065import android.net.LinkQualityInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080066import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070070import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070071import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070073import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070074import android.net.Proxy;
75import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070076import android.net.RouteInfo;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -070077import android.net.SamplingDataTracker;
Jason Monk43324ee2013-07-03 17:04:33 -040078import android.net.Uri;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090080import android.net.wimax.WimaxManagerConstants;
Wink Saville690cb182013-06-29 21:10:57 -070081import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import android.os.Binder;
Wink Saville8fe05f12013-10-31 06:35:22 -070083import android.os.Build;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040084import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070086import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070087import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070088import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080089import android.os.Looper;
90import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070091import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070092import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070093import android.os.PowerManager;
Jeff Sharkey5663b6e2012-09-06 17:54:29 -070094import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070095import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080096import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070097import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080098import android.os.SystemProperties;
Dianne Hackbornbc55bd12012-08-29 18:32:08 -070099import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700101import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700102import android.security.KeyStore;
Wink Saville690cb182013-06-29 21:10:57 -0700103import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700104import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800105import android.util.Slog;
Chad Brubakerccae0d32013-06-14 11:16:51 -0700106import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700107import android.util.SparseIntArray;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700108import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800109
Wink Saville690cb182013-06-29 21:10:57 -0700110import com.android.internal.R;
Jason Monk43324ee2013-07-03 17:04:33 -0400111import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700112import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700113import com.android.internal.net.VpnConfig;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700114import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-06-29 21:10:57 -0700115import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700116import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700117import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700118import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700119import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700120import com.android.server.am.BatteryStatsService;
John Spurlock4ba7e412013-06-24 14:20:23 -0400121import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900122import com.android.server.connectivity.Nat464Xlat;
Jason Monk43324ee2013-07-03 17:04:33 -0400123import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800124import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700125import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700126import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700127import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700128import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700129import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700130
tk.mun093f55c2011-10-13 22:51:57 +0900131import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700132
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700133import org.xmlpull.v1.XmlPullParser;
134import org.xmlpull.v1.XmlPullParserException;
135
136import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800137import java.io.FileDescriptor;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700138import java.io.FileNotFoundException;
139import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700140import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800141import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900142import java.lang.reflect.Constructor;
Wink Saville690cb182013-06-29 21:10:57 -0700143import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700144import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700145import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700146import java.net.InetAddress;
Wink Saville690cb182013-06-29 21:10:57 -0700147import java.net.URL;
Wink Saville8fe05f12013-10-31 06:35:22 -0700148import java.net.URLConnection;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700149import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700150import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700151import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700152import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700153import java.util.GregorianCalendar;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700154import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700155import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700156import java.util.List;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700157import java.util.Map;
Wink Saville690cb182013-06-29 21:10:57 -0700158import java.util.Random;
Wink Saville89c87b92013-08-29 08:55:16 -0700159import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville690cb182013-06-29 21:10:57 -0700160import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161
Wink Saville8fe05f12013-10-31 06:35:22 -0700162import javax.net.ssl.HostnameVerifier;
163import javax.net.ssl.HttpsURLConnection;
164import javax.net.ssl.SSLSession;
165
The Android Open Source Project28527d22009-03-03 19:31:44 -0800166/**
167 * @hide
168 */
169public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700170 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800171
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700172 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700173 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800174
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700175 private static final boolean LOGD_RULES = false;
176
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700177 // TODO: create better separation between radio types and network types
178
Robert Greenwalt2034b912009-08-12 16:08:25 -0700179 // how long to wait before switching back to a radio's default network
180 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
181 // system property that can override the above value
182 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
183 "android.telephony.apn-restore";
184
Wink Saville690cb182013-06-29 21:10:57 -0700185 // Default value if FAIL_FAST_TIME_MS is not set
186 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
187 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
188 private static final String FAIL_FAST_TIME_MS =
189 "persist.radio.fail_fast_time_ms";
190
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700191 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
192 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
193
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700194 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700195
196 private PendingIntent mSampleIntervalElapsedIntent;
197
198 // Set network sampling interval at 12 minutes, this way, even if the timers get
199 // aggregated, it will fire at around 15 minutes, which should allow us to
200 // aggregate this timer with other timers (specially the socket keep alive timers)
201 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
202
203 // start network sampling a minute after booting ...
204 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
205
206 AlarmManager mAlarmManager;
207
Robert Greenwaltbd492212011-05-06 17:10:53 -0700208 // used in recursive route setting to add gateways for the host for which
209 // a host route was requested.
210 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
211
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800212 private Tethering mTethering;
213
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700214 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700215
Chad Brubakerccae0d32013-06-14 11:16:51 -0700216 @GuardedBy("mVpns")
217 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700218 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700219
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700220 private boolean mLockdownEnabled;
221 private LockdownVpnTracker mLockdownTracker;
222
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900223 private Nat464Xlat mClat;
224
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700225 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
226 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700227 /** Currently active network rules by UID. */
228 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700229 /** Set of ifaces that are costly. */
230 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700231
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232 /**
233 * Sometimes we want to refer to the individual network state
234 * trackers separately, and sometimes we just want to treat them
235 * abstractly.
236 */
237 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700238
Irfan Sheriffba8388b2012-08-16 12:49:23 -0700239 /* Handles captive portal check on a network */
240 private CaptivePortalTracker mCaptivePortalTracker;
241
Robert Greenwalt2034b912009-08-12 16:08:25 -0700242 /**
Wink Saville051a6642011-07-13 13:44:13 -0700243 * The link properties that define the current links
244 */
245 private LinkProperties mCurrentLinkProperties[];
246
247 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700248 * A per Net list of the PID's that requested access to the net
249 * used both as a refcount and for per-PID DNS selection
250 */
Mattias Falkdc919012011-08-23 14:15:13 +0200251 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700252
Robert Greenwalt2034b912009-08-12 16:08:25 -0700253 // priority order of the nettrackers
254 // (excluding dynamically set mNetworkPreference)
255 // TODO - move mNetworkTypePreference into this
256 private int[] mPriorityList;
257
The Android Open Source Project28527d22009-03-03 19:31:44 -0800258 private Context mContext;
259 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700260 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700261 // 0 is full bad, 100 is full good
Wink Saville3e866722013-01-31 00:30:13 +0000262 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700263 private int mDefaultInetConditionPublished = 0;
264 private boolean mInetConditionChangeInFlight = false;
265 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266
Chia-chi Yehcc844502011-07-14 18:01:57 -0700267 private Object mDnsLock = new Object();
Robert Greenwaltd44340d2013-02-11 15:25:10 -0800268 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800269
270 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700271 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800272
Robert Greenwalt355205c2011-05-10 15:05:02 -0700273 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700274 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700275
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700276 private static final int ENABLED = 1;
277 private static final int DISABLED = 0;
278
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700279 private static final boolean ADD = true;
280 private static final boolean REMOVE = false;
281
282 private static final boolean TO_DEFAULT_TABLE = true;
283 private static final boolean TO_SECONDARY_TABLE = false;
284
Chad Brubaker78850f32013-07-15 16:34:04 -0700285 private static final boolean EXEMPT = true;
286 private static final boolean UNEXEMPT = false;
287
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700288 /**
289 * used internally as a delayed event to make us switch back to the
290 * default network
291 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700292 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700293
294 /**
295 * used internally to change our mobile data enabled flag
296 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700297 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700298
299 /**
300 * used internally to change our network preference setting
301 * arg1 = networkType to prefer
302 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700303 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700304
305 /**
306 * used internally to synchronize inet condition reports
307 * arg1 = networkType
308 * arg2 = condition (0 bad, 100 good)
309 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700310 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700311
312 /**
313 * used internally to mark the end of inet condition hold periods
314 * arg1 = networkType
315 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700316 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700317
318 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700319 * used internally to set enable/disable cellular data
320 * arg1 = ENBALED or DISABLED
321 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700322 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700323
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700324 /**
325 * used internally to clear a wakelock when transitioning
326 * from one net to another
327 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700328 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700329
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700330 /**
331 * used internally to reload global proxy settings
332 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700333 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700334
Robert Greenwalt34848c02011-03-25 13:09:25 -0700335 /**
336 * used internally to set external dependency met/unmet
337 * arg1 = ENABLED (met) or DISABLED (unmet)
338 * arg2 = NetworkType
339 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700340 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700341
Chia-chi Yehcc844502011-07-14 18:01:57 -0700342 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700343 * used internally to send a sticky broadcast delayed.
344 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700345 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700346
Jeff Sharkey805662d2011-08-19 02:24:24 -0700347 /**
348 * Used internally to
349 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
350 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700351 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700352
Chad Brubakera8e81122013-07-23 17:44:41 -0700353 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700354
Wink Saville690cb182013-06-29 21:10:57 -0700355 /**
356 * Used internally to disable fail fast of mobile data
357 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700358 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville690cb182013-06-29 21:10:57 -0700359
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700360 /**
361 * user internally to indicate that data sampling interval is up
362 */
363 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
364
Jason Monk445cea82013-10-10 14:02:51 -0400365 /**
366 * PAC manager has received new port.
367 */
368 private static final int EVENT_PROXY_HAS_CHANGED = 16;
369
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700370 /** Handler used for internal events. */
371 private InternalHandler mHandler;
372 /** Handler used for incoming {@link NetworkStateTracker} events. */
373 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700374
375 // list of DeathRecipients used to make sure features are turned off when
376 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500377 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700378
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400379 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800380 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400381
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700382 private PowerManager.WakeLock mNetTransitionWakeLock;
383 private String mNetTransitionWakeLockCausedBy = "";
384 private int mNetTransitionWakeLockSerialNumber;
385 private int mNetTransitionWakeLockTimeout;
386
Robert Greenwalt94daa182010-09-01 11:34:05 -0700387 private InetAddress mDefaultDns;
388
Chad Brubaker78850f32013-07-15 16:34:04 -0700389 // Lock for protecting access to mAddedRoutes and mExemptAddresses
390 private final Object mRoutesLock = new Object();
391
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700392 // this collection is used to refcount the added routes - if there are none left
393 // it's time to remove the route from the route table
Chad Brubaker78850f32013-07-15 16:34:04 -0700394 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700395 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
396
Chad Brubaker78850f32013-07-15 16:34:04 -0700397 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
398 // used to handle cleanup of exempt rules
399 @GuardedBy("mRoutesLock")
400 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
401
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700402 // used in DBG mode to track inet condition reports
403 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
404 private ArrayList mInetLog;
405
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700406 // track the current default http proxy - tell the world if we get a new one (real change)
407 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltda77cb12013-04-05 17:14:19 -0700408 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700409 private boolean mDefaultProxyDisabled = false;
410
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700411 // track the global proxy.
412 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700413
Jason Monk43324ee2013-07-03 17:04:33 -0400414 private PacManager mPacManager = null;
415
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700416 private SettingsObserver mSettingsObserver;
417
Chad Brubaker6c0af462014-02-14 13:24:29 -0800418 private AppOpsManager mAppOpsManager;
419
Robert Greenwalt34848c02011-03-25 13:09:25 -0700420 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700421 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700422
Robert Greenwalt12c44552009-12-07 11:33:18 -0800423 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700424 public int mSimultaneity;
425 public int mType;
426 public RadioAttributes(String init) {
427 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 mType = Integer.parseInt(fragments[0]);
429 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700430 }
431 }
432 RadioAttributes[] mRadioAttributes;
433
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700434 // the set of network types that can only be enabled by system/sig apps
435 List mProtectedNetworks;
436
John Spurlock4ba7e412013-06-24 14:20:23 -0400437 private DataConnectionStats mDataConnectionStats;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700438
Wink Saville690cb182013-06-29 21:10:57 -0700439 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
440
441 TelephonyManager mTelephonyManager;
John Spurlock4ba7e412013-06-24 14:20:23 -0400442
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700443 public ConnectivityService(Context context, INetworkManagementService netd,
444 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700445 // Currently, omitting a NetworkFactory will create one internally
446 // TODO: create here when we have cleaner WiMAX support
447 this(context, netd, statsService, policyManager, null);
448 }
449
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700450 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700451 INetworkStatsService statsService, INetworkPolicyManager policyManager,
452 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800453 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800454
Wink Saville775aad62010-09-02 19:23:52 -0700455 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
456 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700457 mHandler = new InternalHandler(handlerThread.getLooper());
458 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700459
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700460 if (netFactory == null) {
461 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
462 }
463
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800464 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800465 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
466 String id = Settings.Secure.getString(context.getContentResolver(),
467 Settings.Secure.ANDROID_ID);
468 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700469 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800470 SystemProperties.set("net.hostname", name);
471 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800472 }
473
Robert Greenwalt94daa182010-09-01 11:34:05 -0700474 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700475 String dns = Settings.Global.getString(context.getContentResolver(),
476 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700477 if (dns == null || dns.length() == 0) {
478 dns = context.getResources().getString(
479 com.android.internal.R.string.config_default_dns_server);
480 }
481 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800482 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
483 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800484 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700485 }
486
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700487 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700488 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700489 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700490 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700491 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700492
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700493 try {
494 mPolicyManager.registerListener(mPolicyListener);
495 } catch (RemoteException e) {
496 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700497 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700498 }
499
500 final PowerManager powerManager = (PowerManager) context.getSystemService(
501 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700502 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
503 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
504 com.android.internal.R.integer.config_networkTransitionTimeout);
505
Robert Greenwalt2034b912009-08-12 16:08:25 -0700506 mNetTrackers = new NetworkStateTracker[
507 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700508 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700509
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700510 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700511 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700512
Robert Greenwalt2034b912009-08-12 16:08:25 -0700513 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700514 String[] raStrings = context.getResources().getStringArray(
515 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700516 for (String raString : raStrings) {
517 RadioAttributes r = new RadioAttributes(raString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700518 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700519 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800520 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700521 continue;
522 }
523 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800524 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700525 r.mType);
526 continue;
527 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700528 mRadioAttributes[r.mType] = r;
529 }
530
Wink Saville23ee8db2013-04-23 14:26:51 -0700531 // TODO: What is the "correct" way to do determine if this is a wifi only device?
532 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
533 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700534 String[] naStrings = context.getResources().getStringArray(
535 com.android.internal.R.array.networkAttributes);
536 for (String naString : naStrings) {
537 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700538 NetworkConfig n = new NetworkConfig(naString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700539 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700540 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800541 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700542 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700543 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700544 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700545 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
546 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
547 n.type);
548 continue;
549 }
Wink Savillef2a62832011-04-07 14:23:45 -0700550 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800551 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700552 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700553 continue;
554 }
Wink Savillef2a62832011-04-07 14:23:45 -0700555 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800556 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700557 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700558 continue;
559 }
Wink Savillef2a62832011-04-07 14:23:45 -0700560 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700561 mNetworksDefined++;
562 } catch(Exception e) {
563 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 }
565 }
Wink Saville70dbdcc2013-07-29 15:00:57 -0700566 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700567
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700568 mProtectedNetworks = new ArrayList<Integer>();
569 int[] protectedNetworks = context.getResources().getIntArray(
570 com.android.internal.R.array.config_protectedNetworks);
571 for (int p : protectedNetworks) {
572 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
573 mProtectedNetworks.add(p);
574 } else {
575 if (DBG) loge("Ignoring protectedNetwork " + p);
576 }
577 }
578
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700579 // high priority first
580 mPriorityList = new int[mNetworksDefined];
581 {
582 int insertionPoint = mNetworksDefined-1;
583 int currentLowest = 0;
584 int nextLowest = 0;
585 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700586 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700587 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700588 if (na.priority < currentLowest) continue;
589 if (na.priority > currentLowest) {
590 if (na.priority < nextLowest || nextLowest == 0) {
591 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700592 }
593 continue;
594 }
Wink Savillef2a62832011-04-07 14:23:45 -0700595 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700596 }
597 currentLowest = nextLowest;
598 nextLowest = 0;
599 }
600 }
601
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800602 // Update mNetworkPreference according to user mannually first then overlay config.xml
603 mNetworkPreference = getPersistedNetworkPreference();
604 if (mNetworkPreference == -1) {
605 for (int n : mPriorityList) {
606 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
607 mNetworkPreference = n;
608 break;
609 }
610 }
611 if (mNetworkPreference == -1) {
612 throw new IllegalStateException(
613 "You should set at least one default Network in config.xml!");
614 }
615 }
616
Mattias Falkdc919012011-08-23 14:15:13 +0200617 mNetRequestersPids =
618 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700619 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200620 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700621 }
622
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500623 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700624
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700625 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
626 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700627
628 // Create and start trackers for hard-coded networks
629 for (int targetNetworkType : mPriorityList) {
630 final NetworkConfig config = mNetConfigs[targetNetworkType];
631 final NetworkStateTracker tracker;
632 try {
633 tracker = netFactory.createTracker(targetNetworkType, config);
634 mNetTrackers[targetNetworkType] = tracker;
635 } catch (IllegalArgumentException e) {
636 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
637 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700638 continue;
639 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700640
641 tracker.startMonitoring(context, mTrackerHandler);
642 if (config.isDefault()) {
643 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800644 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700645 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800646
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700647 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800648
Robert Greenwalt00eb17f2013-07-19 14:30:49 -0700649 //set up the listener for user state for creating user VPNs
Chad Brubakerccae0d32013-06-14 11:16:51 -0700650 IntentFilter intentFilter = new IntentFilter();
651 intentFilter.addAction(Intent.ACTION_USER_STARTING);
652 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
653 mContext.registerReceiverAsUser(
654 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900655 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
656
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700657 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700658 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700659 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900660 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700661 } catch (RemoteException e) {
662 loge("Error registering observer :" + e);
663 }
664
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700665 if (DBG) {
666 mInetLog = new ArrayList();
667 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700668
669 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
670 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800671
John Spurlock4ba7e412013-06-24 14:20:23 -0400672 mDataConnectionStats = new DataConnectionStats(mContext);
673 mDataConnectionStats.startMonitoring();
Jason Monk43324ee2013-07-03 17:04:33 -0400674
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700675 // start network sampling ..
676 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
677 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700678 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700679
680 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
681 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
682
683 IntentFilter filter = new IntentFilter();
684 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
685 mContext.registerReceiver(
686 new BroadcastReceiver() {
687 @Override
688 public void onReceive(Context context, Intent intent) {
689 String action = intent.getAction();
690 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
691 mHandler.sendMessage(mHandler.obtainMessage
692 (EVENT_SAMPLE_INTERVAL_ELAPSED));
693 }
694 }
695 },
696 new IntentFilter(filter));
697
Jason Monk445cea82013-10-10 14:02:51 -0400698 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville3ade4872013-08-29 14:57:08 -0700699
700 filter = new IntentFilter();
Wink Saville89c87b92013-08-29 08:55:16 -0700701 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
702 mContext.registerReceiver(mProvisioningReceiver, filter);
Chad Brubaker6c0af462014-02-14 13:24:29 -0800703
704 mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800705 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700706
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700707 /**
708 * Factory that creates {@link NetworkStateTracker} instances using given
709 * {@link NetworkConfig}.
710 */
711 public interface NetworkFactory {
712 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
713 }
714
715 private static class DefaultNetworkFactory implements NetworkFactory {
716 private final Context mContext;
717 private final Handler mTrackerHandler;
718
719 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
720 mContext = context;
721 mTrackerHandler = trackerHandler;
722 }
723
724 @Override
725 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
726 switch (config.radio) {
727 case TYPE_WIFI:
728 return new WifiStateTracker(targetNetworkType, config.name);
729 case TYPE_MOBILE:
730 return new MobileDataStateTracker(targetNetworkType, config.name);
731 case TYPE_DUMMY:
732 return new DummyDataStateTracker(targetNetworkType, config.name);
733 case TYPE_BLUETOOTH:
734 return BluetoothTetheringDataTracker.getInstance();
735 case TYPE_WIMAX:
736 return makeWimaxStateTracker(mContext, mTrackerHandler);
737 case TYPE_ETHERNET:
738 return EthernetDataTracker.getInstance();
739 default:
740 throw new IllegalArgumentException(
741 "Trying to create a NetworkStateTracker for an unknown radio type: "
742 + config.radio);
743 }
744 }
745 }
746
747 /**
748 * Loads external WiMAX library and registers as system service, returning a
749 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
750 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
751 */
752 private static NetworkStateTracker makeWimaxStateTracker(
753 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700754 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900755 DexClassLoader wimaxClassLoader;
756 Class wimaxStateTrackerClass = null;
757 Class wimaxServiceClass = null;
758 Class wimaxManagerClass;
759 String wimaxJarLocation;
760 String wimaxLibLocation;
761 String wimaxManagerClassName;
762 String wimaxServiceClassName;
763 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800764
tk.mun093f55c2011-10-13 22:51:57 +0900765 NetworkStateTracker wimaxStateTracker = null;
766
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700767 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900768 com.android.internal.R.bool.config_wimaxEnabled);
769
770 if (isWimaxEnabled) {
771 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700772 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900773 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700774 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900775 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700776 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900777 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700778 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900779 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700780 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900781 com.android.internal.R.string.config_wimaxStateTrackerClassname);
782
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800783 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900784 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700785 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900786 wimaxLibLocation, ClassLoader.getSystemClassLoader());
787
788 try {
789 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
790 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
791 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
792 } catch (ClassNotFoundException ex) {
793 loge("Exception finding Wimax classes: " + ex.toString());
794 return null;
795 }
796 } catch(Resources.NotFoundException ex) {
797 loge("Wimax Resources does not exist!!! ");
798 return null;
799 }
800
801 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800802 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900803
804 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
805 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700806 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
807 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900808
809 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
810 (new Class[] {Context.class, wimaxStateTrackerClass});
811 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700812 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900813 wmxSrvConst.setAccessible(false);
814
815 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
816
817 } catch(Exception ex) {
818 loge("Exception creating Wimax classes: " + ex.toString());
819 return null;
820 }
821 } else {
822 loge("Wimax is not enabled or not added to the network attributes!!! ");
823 return null;
824 }
825
826 return wimaxStateTracker;
827 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700828
The Android Open Source Project28527d22009-03-03 19:31:44 -0800829 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700830 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800831 * @param preference the new preference
832 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700833 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800834 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700835
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700836 mHandler.sendMessage(
837 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800838 }
839
840 public int getNetworkPreference() {
841 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700842 int preference;
843 synchronized(this) {
844 preference = mNetworkPreference;
845 }
846 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800847 }
848
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700849 private void handleSetNetworkPreference(int preference) {
850 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700851 mNetConfigs[preference] != null &&
852 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700853 if (mNetworkPreference != preference) {
854 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700855 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700856 synchronized(this) {
857 mNetworkPreference = preference;
858 }
859 enforcePreference();
860 }
861 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800862 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700863
Wink Saville4f0de1e2011-08-04 15:01:58 -0700864 private int getConnectivityChangeDelay() {
865 final ContentResolver cr = mContext.getContentResolver();
866
867 /** Check system properties for the default value then use secure settings value, if any. */
868 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700869 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
870 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
871 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700872 defaultDelay);
873 }
874
The Android Open Source Project28527d22009-03-03 19:31:44 -0800875 private int getPersistedNetworkPreference() {
876 final ContentResolver cr = mContext.getContentResolver();
877
Jeff Brown87272712012-09-25 15:03:20 -0700878 final int networkPrefSetting = Settings.Global
879 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800880
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800881 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800882 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700883
The Android Open Source Project28527d22009-03-03 19:31:44 -0800884 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700885 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800886 * In this method, we only tear down a non-preferred network. Establishing
887 * a connection to the preferred network is taken care of when we handle
888 * the disconnect event from the non-preferred network
889 * (see {@link #handleDisconnect(NetworkInfo)}).
890 */
891 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800893 return;
894
Robert Greenwalt2034b912009-08-12 16:08:25 -0700895 if (!mNetTrackers[mNetworkPreference].isAvailable())
896 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800897
Robert Greenwalt2034b912009-08-12 16:08:25 -0700898 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700899 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700900 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700901 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800902 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700903 " in enforcePreference");
904 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700905 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800906 }
907 }
908 }
909
910 private boolean teardown(NetworkStateTracker netTracker) {
911 if (netTracker.teardown()) {
912 netTracker.setTeardownRequested(true);
913 return true;
914 } else {
915 return false;
916 }
917 }
918
919 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700920 * Check if UID should be blocked from using the network represented by the
921 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700922 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700923 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
924 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700925
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700926 final boolean networkCostly;
927 final int uidRules;
928 synchronized (mRulesLock) {
929 networkCostly = mMeteredIfaces.contains(iface);
930 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700931 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700932
933 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
934 return true;
935 }
936
937 // no restrictive rules; network is visible
938 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700939 }
940
941 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700942 * Return a filtered {@link NetworkInfo}, potentially marked
943 * {@link DetailedState#BLOCKED} based on
944 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700945 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700946 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
947 NetworkInfo info = tracker.getNetworkInfo();
948 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700949 // network is blocked; clone and override state
950 info = new NetworkInfo(info);
951 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700953 if (mLockdownTracker != null) {
954 info = mLockdownTracker.augmentNetworkInfo(info);
955 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700956 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700957 }
958
959 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800960 * Return NetworkInfo for the active (i.e., connected) network interface.
961 * It is assumed that at most one network is active at a time. If more
962 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700963 * @return the info for the active network, or {@code null} if none is
964 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800965 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700966 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800967 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700968 enforceAccessPermission();
969 final int uid = Binder.getCallingUid();
970 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800971 }
972
Wink Saville89c87b92013-08-29 08:55:16 -0700973 /**
974 * Find the first Provisioning network.
975 *
976 * @return NetworkInfo or null if none.
977 */
978 private NetworkInfo getProvisioningNetworkInfo() {
979 enforceAccessPermission();
980
981 // Find the first Provisioning Network
982 NetworkInfo provNi = null;
983 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville860f5282013-09-05 12:02:25 -0700984 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -0700985 provNi = ni;
986 break;
987 }
988 }
989 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
990 return provNi;
991 }
992
993 /**
994 * Find the first Provisioning network or the ActiveDefaultNetwork
995 * if there is no Provisioning network
996 *
997 * @return NetworkInfo or null if none.
998 */
999 @Override
1000 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
1001 enforceAccessPermission();
1002
1003 NetworkInfo provNi = getProvisioningNetworkInfo();
1004 if (provNi == null) {
1005 final int uid = Binder.getCallingUid();
1006 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1007 }
1008 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1009 return provNi;
1010 }
1011
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001012 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1013 enforceAccessPermission();
1014 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1015 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1016 if (tracker != null) {
1017 return tracker.getNetworkInfo();
1018 }
1019 }
1020 return null;
1021 }
1022
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001023 @Override
1024 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1025 enforceConnectivityInternalPermission();
1026 return getNetworkInfo(mActiveDefaultNetwork, uid);
1027 }
1028
1029 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 public NetworkInfo getNetworkInfo(int networkType) {
1031 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001032 final int uid = Binder.getCallingUid();
1033 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001034 }
1035
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001036 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1037 NetworkInfo info = null;
1038 if (isNetworkTypeValid(networkType)) {
1039 final NetworkStateTracker tracker = mNetTrackers[networkType];
1040 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001041 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001042 }
1043 }
1044 return info;
1045 }
1046
1047 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001048 public NetworkInfo[] getAllNetworkInfo() {
1049 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001050 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001051 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001052 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001053 for (NetworkStateTracker tracker : mNetTrackers) {
1054 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001055 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001056 }
1057 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001058 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001059 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001060 }
1061
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001062 @Override
1063 public boolean isNetworkSupported(int networkType) {
1064 enforceAccessPermission();
1065 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1066 }
1067
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001068 /**
1069 * Return LinkProperties for the active (i.e., connected) default
1070 * network interface. It is assumed that at most one default network
1071 * is active at a time. If more than one is active, it is indeterminate
1072 * which will be returned.
1073 * @return the ip properties for the active network, or {@code null} if
1074 * none is active
1075 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001076 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001077 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001078 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001079 }
1080
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001081 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001082 public LinkProperties getLinkProperties(int networkType) {
1083 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001084 if (isNetworkTypeValid(networkType)) {
1085 final NetworkStateTracker tracker = mNetTrackers[networkType];
1086 if (tracker != null) {
1087 return tracker.getLinkProperties();
1088 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001089 }
1090 return null;
1091 }
1092
Jeff Sharkey21062e72011-05-28 20:56:34 -07001093 @Override
1094 public NetworkState[] getAllNetworkState() {
1095 enforceAccessPermission();
1096 final int uid = Binder.getCallingUid();
1097 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001098 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001099 for (NetworkStateTracker tracker : mNetTrackers) {
1100 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001101 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001102 result.add(new NetworkState(
1103 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1104 }
1105 }
1106 }
1107 return result.toArray(new NetworkState[result.size()]);
1108 }
1109
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001110 private NetworkState getNetworkStateUnchecked(int networkType) {
1111 if (isNetworkTypeValid(networkType)) {
1112 final NetworkStateTracker tracker = mNetTrackers[networkType];
1113 if (tracker != null) {
1114 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1115 tracker.getLinkCapabilities());
1116 }
1117 }
1118 return null;
1119 }
1120
1121 @Override
1122 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1123 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001124
1125 final long token = Binder.clearCallingIdentity();
1126 try {
1127 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1128 if (state != null) {
1129 try {
1130 return mPolicyManager.getNetworkQuotaInfo(state);
1131 } catch (RemoteException e) {
1132 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001133 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001134 return null;
1135 } finally {
1136 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001137 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001138 }
1139
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001140 @Override
1141 public boolean isActiveNetworkMetered() {
1142 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001143 final long token = Binder.clearCallingIdentity();
1144 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001145 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001146 } finally {
1147 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001148 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001149 }
1150
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001151 private boolean isNetworkMeteredUnchecked(int networkType) {
1152 final NetworkState state = getNetworkStateUnchecked(networkType);
1153 if (state != null) {
1154 try {
1155 return mPolicyManager.isNetworkMetered(state);
1156 } catch (RemoteException e) {
1157 }
1158 }
1159 return false;
1160 }
1161
The Android Open Source Project28527d22009-03-03 19:31:44 -08001162 public boolean setRadios(boolean turnOn) {
1163 boolean result = true;
1164 enforceChangePermission();
1165 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001166 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001167 }
1168 return result;
1169 }
1170
1171 public boolean setRadio(int netType, boolean turnOn) {
1172 enforceChangePermission();
1173 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1174 return false;
1175 }
1176 NetworkStateTracker tracker = mNetTrackers[netType];
1177 return tracker != null && tracker.setRadio(turnOn);
1178 }
1179
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001180 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1181 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001182 public void interfaceClassDataActivityChanged(String label, boolean active) {
1183 int deviceType = Integer.parseInt(label);
1184 sendDataActivityBroadcast(deviceType, active);
1185 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001186 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001187
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001188 /**
1189 * Used to notice when the calling process dies so we can self-expire
1190 *
1191 * Also used to know if the process has cleaned up after itself when
1192 * our auto-expire timer goes off. The timer has a link to an object.
1193 *
1194 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195 private class FeatureUser implements IBinder.DeathRecipient {
1196 int mNetworkType;
1197 String mFeature;
1198 IBinder mBinder;
1199 int mPid;
1200 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001201 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001202
1203 FeatureUser(int type, String feature, IBinder binder) {
1204 super();
1205 mNetworkType = type;
1206 mFeature = feature;
1207 mBinder = binder;
1208 mPid = getCallingPid();
1209 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001210 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001211
Robert Greenwalt2034b912009-08-12 16:08:25 -07001212 try {
1213 mBinder.linkToDeath(this, 0);
1214 } catch (RemoteException e) {
1215 binderDied();
1216 }
1217 }
1218
1219 void unlinkDeathRecipient() {
1220 mBinder.unlinkToDeath(this, 0);
1221 }
1222
1223 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001224 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001225 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1226 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001227 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001228 }
1229
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001230 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001231 if (VDBG) {
1232 log("ConnectivityService FeatureUser expire(" +
1233 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1234 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1235 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001236 stopUsingNetworkFeature(this, false);
1237 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001238
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001239 public boolean isSameUser(FeatureUser u) {
1240 if (u == null) return false;
1241
1242 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1243 }
1244
1245 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1246 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1247 TextUtils.equals(mFeature, feature)) {
1248 return true;
1249 }
1250 return false;
1251 }
1252
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001253 public String toString() {
1254 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1255 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1256 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001257 }
1258
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001259 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001260 public int startUsingNetworkFeature(int networkType, String feature,
1261 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001262 long startTime = 0;
1263 if (DBG) {
1264 startTime = SystemClock.elapsedRealtime();
1265 }
Wink Savillea7d56572011-09-21 11:05:43 -07001266 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001267 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1268 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001269 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001270 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001271 try {
1272 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1273 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001274 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001275 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001276
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001277 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001278
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001279 // TODO - move this into individual networktrackers
1280 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001281
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001282 if (mLockdownEnabled) {
1283 // Since carrier APNs usually aren't available from VPN
1284 // endpoint, mark them as unavailable.
1285 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1286 }
1287
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001288 if (mProtectedNetworks.contains(usedNetworkType)) {
1289 enforceConnectivityInternalPermission();
1290 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001291
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001292 // if UID is restricted, don't allow them to bring up metered APNs
1293 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1294 final int uidRules;
1295 synchronized (mRulesLock) {
1296 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1297 }
1298 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001299 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001300 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001301
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001302 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1303 if (network != null) {
1304 Integer currentPid = new Integer(getCallingPid());
1305 if (usedNetworkType != networkType) {
1306 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001307
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001308 if (ni.isAvailable() == false) {
1309 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1310 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001311 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001312 } else {
1313 // else make the attempt anyway - probably giving REQUEST_STARTED below
1314 if (DBG) {
1315 log("special network not available, but try anyway ni=" +
1316 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001317 }
1318 }
1319 }
1320
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001321 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001322
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001323 synchronized(this) {
1324 boolean addToList = true;
1325 if (restoreTimer < 0) {
1326 // In case there is no timer is specified for the feature,
1327 // make sure we don't add duplicate entry with the same request.
1328 for (FeatureUser u : mFeatureUsers) {
1329 if (u.isSameUser(f)) {
1330 // Duplicate user is found. Do not add.
1331 addToList = false;
1332 break;
1333 }
1334 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001335 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001336
1337 if (addToList) mFeatureUsers.add(f);
1338 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1339 // this gets used for per-pid dns when connected
1340 mNetRequestersPids[usedNetworkType].add(currentPid);
1341 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001342 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001343
1344 if (restoreTimer >= 0) {
1345 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1346 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1347 }
1348
1349 if ((ni.isConnectedOrConnecting() == true) &&
1350 !network.isTeardownRequested()) {
1351 if (ni.isConnected() == true) {
1352 final long token = Binder.clearCallingIdentity();
1353 try {
1354 // add the pid-specific dns
1355 handleDnsConfigurationChange(usedNetworkType);
1356 if (VDBG) log("special network already active");
1357 } finally {
1358 Binder.restoreCallingIdentity(token);
1359 }
Wink Saville64e3f782012-07-10 12:37:54 -07001360 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001361 }
1362 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001363 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001364 }
1365
1366 // check if the radio in play can make another contact
1367 // assume if cannot for now
1368
1369 if (DBG) {
1370 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1371 feature);
1372 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001373 if (network.reconnect()) {
Wink Saville89c87b92013-08-29 08:55:16 -07001374 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001375 return PhoneConstants.APN_REQUEST_STARTED;
1376 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07001377 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001378 return PhoneConstants.APN_REQUEST_FAILED;
1379 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001380 } else {
1381 // need to remember this unsupported request so we respond appropriately on stop
1382 synchronized(this) {
1383 mFeatureUsers.add(f);
1384 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1385 // this gets used for per-pid dns when connected
1386 mNetRequestersPids[usedNetworkType].add(currentPid);
1387 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001388 }
Wink Saville89c87b92013-08-29 08:55:16 -07001389 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001390 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001391 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001392 }
Wink Saville89c87b92013-08-29 08:55:16 -07001393 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001394 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001395 } finally {
1396 if (DBG) {
1397 final long execTime = SystemClock.elapsedRealtime() - startTime;
1398 if (execTime > 250) {
1399 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1400 } else {
1401 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1402 }
1403 }
1404 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001405 }
1406
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001407 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001408 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001409 enforceChangePermission();
1410
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001411 int pid = getCallingPid();
1412 int uid = getCallingUid();
1413
1414 FeatureUser u = null;
1415 boolean found = false;
1416
1417 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001418 for (FeatureUser x : mFeatureUsers) {
1419 if (x.isSameUser(pid, uid, networkType, feature)) {
1420 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001421 found = true;
1422 break;
1423 }
1424 }
1425 }
1426 if (found && u != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07001427 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001428 // stop regardless of how many other time this proc had called start
1429 return stopUsingNetworkFeature(u, true);
1430 } else {
1431 // none found!
Wink Saville89c87b92013-08-29 08:55:16 -07001432 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001433 return 1;
1434 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001435 }
1436
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001437 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1438 int networkType = u.mNetworkType;
1439 String feature = u.mFeature;
1440 int pid = u.mPid;
1441 int uid = u.mUid;
1442
1443 NetworkStateTracker tracker = null;
1444 boolean callTeardown = false; // used to carry our decision outside of sync block
1445
Wink Savillea7d56572011-09-21 11:05:43 -07001446 if (VDBG) {
1447 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001448 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001449
The Android Open Source Project28527d22009-03-03 19:31:44 -08001450 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001451 if (DBG) {
1452 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1453 ", net is invalid");
1454 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001455 return -1;
1456 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001457
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001458 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1459 // sync block
1460 synchronized(this) {
1461 // check if this process still has an outstanding start request
1462 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001463 if (VDBG) {
1464 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1465 ", ignoring");
1466 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001467 return 1;
1468 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001469 u.unlinkDeathRecipient();
1470 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1471 // If we care about duplicate requests, check for that here.
1472 //
1473 // This is done to support the extension of a request - the app
1474 // can request we start the network feature again and renew the
1475 // auto-shutoff delay. Normal "stop" calls from the app though
1476 // do not pay attention to duplicate requests - in effect the
1477 // API does not refcount and a single stop will counter multiple starts.
1478 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001479 for (FeatureUser x : mFeatureUsers) {
1480 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001481 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001482 return 1;
1483 }
1484 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001485 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001486
repo syncf5de5572011-07-29 23:55:49 -07001487 // TODO - move to individual network trackers
1488 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1489
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001490 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001491 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001492 if (DBG) {
1493 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1494 " no known tracker for used net type " + usedNetworkType);
1495 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001496 return -1;
1497 }
1498 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001499 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001500 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001501
1502 final long token = Binder.clearCallingIdentity();
1503 try {
1504 reassessPidDns(pid, true);
1505 } finally {
1506 Binder.restoreCallingIdentity(token);
1507 }
Mattias Falkdc919012011-08-23 14:15:13 +02001508 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001509 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001510 if (VDBG) {
1511 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1512 " others still using it");
1513 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001514 return 1;
1515 }
1516 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001517 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001518 if (DBG) {
1519 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1520 " not a known feature - dropping");
1521 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001522 }
1523 }
Wink Savillea7d56572011-09-21 11:05:43 -07001524
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001525 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001526 if (DBG) {
1527 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1528 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001529 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001530 return 1;
1531 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001532 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001533 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001534 }
1535
1536 /**
Chad Brubaker6c0af462014-02-14 13:24:29 -08001537 * Check if the address falls into any of currently running VPN's route's.
1538 */
1539 private boolean isAddressUnderVpn(InetAddress address) {
1540 synchronized (mVpns) {
1541 synchronized (mRoutesLock) {
1542 int uid = UserHandle.getCallingUserId();
1543 Vpn vpn = mVpns.get(uid);
1544 if (vpn == null) {
1545 return false;
1546 }
1547
1548 // Check if an exemption exists for this address.
1549 for (LinkAddress destination : mExemptAddresses) {
1550 if (!NetworkUtils.addressTypeMatches(address, destination.getAddress())) {
1551 continue;
1552 }
1553
1554 int prefix = destination.getNetworkPrefixLength();
1555 InetAddress addrMasked = NetworkUtils.getNetworkPart(address, prefix);
1556 InetAddress destMasked = NetworkUtils.getNetworkPart(destination.getAddress(),
1557 prefix);
1558
1559 if (addrMasked.equals(destMasked)) {
1560 return false;
1561 }
1562 }
1563
1564 // Finally check if the address is covered by the VPN.
1565 return vpn.isAddressCovered(address);
1566 }
1567 }
1568 }
1569
1570 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001571 * @deprecated use requestRouteToHostAddress instead
1572 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001573 * Ensure that a network route exists to deliver traffic to the specified
1574 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001575 * @param networkType the type of the network over which traffic to the
1576 * specified host is to be routed
1577 * @param hostAddress the IP address of the host to which the route is
1578 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001579 * @return {@code true} on success, {@code false} on failure
1580 */
Chad Brubakerabe88512014-02-14 13:22:34 -08001581 public boolean requestRouteToHost(int networkType, int hostAddress, String packageName) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001582 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1583
1584 if (inetAddress == null) {
1585 return false;
1586 }
1587
Chad Brubakerabe88512014-02-14 13:22:34 -08001588 return requestRouteToHostAddress(networkType, inetAddress.getAddress(), packageName);
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001589 }
1590
1591 /**
1592 * Ensure that a network route exists to deliver traffic to the specified
1593 * host via the specified network interface.
1594 * @param networkType the type of the network over which traffic to the
1595 * specified host is to be routed
1596 * @param hostAddress the IP address of the host to which the route is
1597 * desired
1598 * @return {@code true} on success, {@code false} on failure
1599 */
Chad Brubakerabe88512014-02-14 13:22:34 -08001600 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
1601 String packageName) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001602 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001603 if (mProtectedNetworks.contains(networkType)) {
1604 enforceConnectivityInternalPermission();
1605 }
Chad Brubaker6c0af462014-02-14 13:24:29 -08001606 boolean exempt;
1607 InetAddress addr;
1608 try {
1609 addr = InetAddress.getByAddress(hostAddress);
1610 } catch (UnknownHostException e) {
1611 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1612 return false;
1613 }
1614 // System apps may request routes bypassing the VPN to keep other networks working.
1615 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1616 exempt = true;
1617 } else {
1618 mAppOpsManager.checkPackage(Binder.getCallingUid(), packageName);
1619 try {
1620 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName,
1621 0);
1622 exempt = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
1623 } catch (NameNotFoundException e) {
1624 throw new IllegalArgumentException("Failed to find calling package details", e);
1625 }
1626 }
1627
1628 // Non-exempt routeToHost's can only be added if the host is not covered by the VPN.
1629 // This can be either because the VPN's routes do not cover the destination or a
1630 // system application added an exemption that covers this destination.
1631 if (!exempt && isAddressUnderVpn(addr)) {
1632 return false;
1633 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001634
The Android Open Source Project28527d22009-03-03 19:31:44 -08001635 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001636 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001637 return false;
1638 }
1639 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter7caa36a2013-11-07 22:08:24 -08001640 DetailedState netState = DetailedState.DISCONNECTED;
1641 if (tracker != null) {
1642 netState = tracker.getNetworkInfo().getDetailedState();
1643 }
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001644
Ken Mixter7caa36a2013-11-07 22:08:24 -08001645 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001646 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001647 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001648 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001649 log("requestRouteToHostAddress on down network "
1650 + "(" + networkType + ") - dropped"
1651 + " tracker=" + tracker
1652 + " netState=" + netState
1653 + " isTeardownRequested="
1654 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001655 }
1656 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001657 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001658 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001659 try {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001660 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker6c0af462014-02-14 13:24:29 -08001661 boolean ok = addRouteToAddress(lp, addr, exempt);
Wink Saville690cb182013-06-29 21:10:57 -07001662 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1663 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001664 } finally {
1665 Binder.restoreCallingIdentity(token);
1666 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001667 }
1668
Chad Brubaker78850f32013-07-15 16:34:04 -07001669 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1670 boolean exempt) {
1671 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001672 }
1673
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001674 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001675 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001676 }
1677
Chad Brubaker78850f32013-07-15 16:34:04 -07001678 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1679 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001680 }
1681
1682 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001683 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001684 }
1685
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001686 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001687 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001688 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001689 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001690 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001691 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001692 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001693 if (bestRoute.getGateway().equals(addr)) {
1694 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001695 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001696 } else {
1697 // if we will connect to this through another route, add a direct route
1698 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001699 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001700 }
1701 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001702 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001703 }
1704
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001705 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001706 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001707 if ((lp == null) || (r == null)) {
1708 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001709 return false;
1710 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001711
1712 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001713 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001714 return false;
1715 }
1716
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001717 String ifaceName = r.getInterface();
1718 if(ifaceName == null) {
1719 loge("Error modifying route - no interface name");
1720 return false;
1721 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001722 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001723 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001724 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001725 if (bestRoute.getGateway().equals(r.getGateway())) {
1726 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001727 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001728 } else {
1729 // if we will connect to our gateway through another route, add a direct
1730 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001731 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1732 bestRoute.getGateway(),
1733 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001734 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001735 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001736 }
1737 }
1738 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001739 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001740 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001741 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001742 synchronized (mRoutesLock) {
1743 // only track default table - only one apps can effect
1744 mAddedRoutes.add(r);
1745 mNetd.addRoute(ifaceName, r);
1746 if (exempt) {
1747 LinkAddress dest = r.getDestination();
1748 if (!mExemptAddresses.contains(dest)) {
1749 mNetd.setHostExemption(dest);
1750 mExemptAddresses.add(dest);
1751 }
1752 }
1753 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001754 } else {
1755 mNetd.addSecondaryRoute(ifaceName, r);
1756 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001757 } catch (Exception e) {
1758 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001759 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001760 return false;
1761 }
1762 } else {
1763 // if we remove this one and there are no more like it, then refcount==0 and
1764 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001765 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001766 synchronized (mRoutesLock) {
1767 mAddedRoutes.remove(r);
1768 if (mAddedRoutes.contains(r) == false) {
1769 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1770 try {
1771 mNetd.removeRoute(ifaceName, r);
1772 LinkAddress dest = r.getDestination();
1773 if (mExemptAddresses.contains(dest)) {
1774 mNetd.clearHostExemption(dest);
1775 mExemptAddresses.remove(dest);
1776 }
1777 } catch (Exception e) {
1778 // never crash - catch them all
1779 if (VDBG) loge("Exception trying to remove a route: " + e);
1780 return false;
1781 }
1782 } else {
1783 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001784 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001785 }
1786 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001787 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001788 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001789 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001790 } catch (Exception e) {
1791 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001792 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001793 return false;
1794 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001795 }
1796 }
1797 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001798 }
1799
1800 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001801 * @see ConnectivityManager#getMobileDataEnabled()
1802 */
1803 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001804 // TODO: This detail should probably be in DataConnectionTracker's
1805 // which is where we store the value and maybe make this
1806 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001807 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001808 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1809 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001810 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001811 return retVal;
1812 }
1813
Robert Greenwalt34848c02011-03-25 13:09:25 -07001814 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001815 enforceConnectivityInternalPermission();
1816
Robert Greenwalt34848c02011-03-25 13:09:25 -07001817 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1818 (met ? ENABLED : DISABLED), networkType));
1819 }
1820
1821 private void handleSetDependencyMet(int networkType, boolean met) {
1822 if (mNetTrackers[networkType] != null) {
1823 if (DBG) {
1824 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1825 }
1826 mNetTrackers[networkType].setDependencyMet(met);
1827 }
1828 }
1829
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001830 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1831 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001832 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001833 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001834 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001835 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001836 }
1837
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001838 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001839 // skip update when we've already applied rules
1840 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1841 if (oldRules == uidRules) return;
1842
1843 mUidRules.put(uid, uidRules);
1844 }
1845
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001846 // TODO: notify UID when it has requested targeted updates
1847 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001848
1849 @Override
1850 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001851 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001852 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001853 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001854 }
1855
1856 synchronized (mRulesLock) {
1857 mMeteredIfaces.clear();
1858 for (String iface : meteredIfaces) {
1859 mMeteredIfaces.add(iface);
1860 }
1861 }
1862 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001863
1864 @Override
1865 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1866 // caller is NPMS, since we only register with them
1867 if (LOGD_RULES) {
1868 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1869 }
1870
1871 // kick off connectivity change broadcast for active network, since
1872 // global background policy change is radical.
1873 final int networkType = mActiveDefaultNetwork;
1874 if (isNetworkTypeValid(networkType)) {
1875 final NetworkStateTracker tracker = mNetTrackers[networkType];
1876 if (tracker != null) {
1877 final NetworkInfo info = tracker.getNetworkInfo();
1878 if (info != null && info.isConnected()) {
1879 sendConnectedBroadcast(info);
1880 }
1881 }
1882 }
1883 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001884 };
1885
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001886 /**
1887 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1888 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001889 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001890 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001891 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001892
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001893 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001894 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001895 }
1896
1897 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001898 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001899 if (VDBG) {
1900 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001901 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001902 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1903 }
tk.mun5eee1042012-01-06 10:43:52 +09001904 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1905 if (VDBG) {
1906 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1907 }
1908 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1909 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001910 }
1911
1912 @Override
1913 public void setPolicyDataEnable(int networkType, boolean enabled) {
1914 // only someone like NPMS should only be calling us
1915 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1916
1917 mHandler.sendMessage(mHandler.obtainMessage(
1918 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1919 }
1920
1921 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1922 if (isNetworkTypeValid(networkType)) {
1923 final NetworkStateTracker tracker = mNetTrackers[networkType];
1924 if (tracker != null) {
1925 tracker.setPolicyDataEnable(enabled);
1926 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001927 }
1928 }
1929
The Android Open Source Project28527d22009-03-03 19:31:44 -08001930 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001931 mContext.enforceCallingOrSelfPermission(
1932 android.Manifest.permission.ACCESS_NETWORK_STATE,
1933 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001934 }
1935
1936 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001937 mContext.enforceCallingOrSelfPermission(
1938 android.Manifest.permission.CHANGE_NETWORK_STATE,
1939 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001940 }
1941
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001942 // TODO Make this a special check when it goes public
1943 private void enforceTetherChangePermission() {
1944 mContext.enforceCallingOrSelfPermission(
1945 android.Manifest.permission.CHANGE_NETWORK_STATE,
1946 "ConnectivityService");
1947 }
1948
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001949 private void enforceTetherAccessPermission() {
1950 mContext.enforceCallingOrSelfPermission(
1951 android.Manifest.permission.ACCESS_NETWORK_STATE,
1952 "ConnectivityService");
1953 }
1954
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001955 private void enforceConnectivityInternalPermission() {
1956 mContext.enforceCallingOrSelfPermission(
1957 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1958 "ConnectivityService");
1959 }
1960
Chad Brubaker31de0b62013-07-11 13:29:30 -07001961 private void enforceMarkNetworkSocketPermission() {
1962 //Media server special case
1963 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1964 return;
1965 }
1966 mContext.enforceCallingOrSelfPermission(
1967 android.Manifest.permission.MARK_NETWORK_SOCKET,
1968 "ConnectivityService");
1969 }
1970
The Android Open Source Project28527d22009-03-03 19:31:44 -08001971 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001972 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1973 * network, we ignore it. If it is for the active network, we send out a
1974 * broadcast. But first, we check whether it might be possible to connect
1975 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001976 * @param info the {@code NetworkInfo} for the network
1977 */
1978 private void handleDisconnect(NetworkInfo info) {
1979
Robert Greenwalt2034b912009-08-12 16:08:25 -07001980 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001981
Robert Greenwalt2034b912009-08-12 16:08:25 -07001982 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001983
1984 // Remove idletimer previously setup in {@code handleConnect}
1985 removeDataActivityTracking(prevNetType);
1986
The Android Open Source Project28527d22009-03-03 19:31:44 -08001987 /*
1988 * If the disconnected network is not the active one, then don't report
1989 * this as a loss of connectivity. What probably happened is that we're
1990 * getting the disconnect for a network that we explicitly disabled
1991 * in accordance with network preference policies.
1992 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001993 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001994 List<Integer> pids = mNetRequestersPids[prevNetType];
1995 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001996 // will remove them because the net's no longer connected
1997 // need to do this now as only now do we know the pids and
1998 // can properly null things that are no longer referenced.
1999 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002001 }
2002
The Android Open Source Project28527d22009-03-03 19:31:44 -08002003 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002004 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002005 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002006 if (info.isFailover()) {
2007 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2008 info.setFailover(false);
2009 }
2010 if (info.getReason() != null) {
2011 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2012 }
2013 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002014 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2015 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002016 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002017
Robert Greenwalt34848c02011-03-25 13:09:25 -07002018 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002019 tryFailover(prevNetType);
2020 if (mActiveDefaultNetwork != -1) {
2021 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002022 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2023 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002024 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002025 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2026 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002027 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002028 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002029
2030 // Reset interface if no other connections are using the same interface
2031 boolean doReset = true;
2032 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
2033 if (linkProperties != null) {
2034 String oldIface = linkProperties.getInterfaceName();
2035 if (TextUtils.isEmpty(oldIface) == false) {
2036 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
2037 if (networkStateTracker == null) continue;
2038 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
2039 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
2040 LinkProperties l = networkStateTracker.getLinkProperties();
2041 if (l == null) continue;
2042 if (oldIface.equals(l.getInterfaceName())) {
2043 doReset = false;
2044 break;
2045 }
2046 }
2047 }
2048 }
2049 }
2050
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002051 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002052 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002053
Jeff Sharkey971cd162011-08-29 16:02:57 -07002054 final Intent immediateIntent = new Intent(intent);
2055 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2056 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002057 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002058 /*
2059 * If the failover network is already connected, then immediately send
2060 * out a followup broadcast indicating successful failover
2061 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002062 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07002063 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
2064 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002065 }
2066 }
2067
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002068 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002069 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08002070 * If this is a default network, check if other defaults are available.
2071 * Try to reconnect on all available and let them hash it out when
2072 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07002073 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07002074 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002075 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville89c87b92013-08-29 08:55:16 -07002076 if (DBG) {
2077 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2078 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002079 mActiveDefaultNetwork = -1;
2080 }
2081
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002082 // don't signal a reconnect for anything lower or equal priority than our
2083 // current connected default
2084 // TODO - don't filter by priority now - nice optimization but risky
2085// int currentPriority = -1;
2086// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002087// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002088// }
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002089
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002090 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002091 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002092 if (mNetConfigs[checkType] == null) continue;
2093 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002094 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002095
2096// Enabling the isAvailable() optimization caused mobile to not get
2097// selected if it was in the middle of error handling. Specifically
2098// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2099// would not be available and we wouldn't get connected to anything.
2100// So removing the isAvailable() optimization below for now. TODO: This
2101// optimization should work and we need to investigate why it doesn't work.
2102// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2103// complete before it is really complete.
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002104
Wink Saville72a95b92011-01-26 15:43:49 -08002105// if (!mNetTrackers[checkType].isAvailable()) continue;
2106
Robert Greenwalt34848c02011-03-25 13:09:25 -07002107// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002108
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002109 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2110 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2111 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2112 checkInfo.setFailover(true);
2113 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002114 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002115 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002116 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002117 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002118 }
2119
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002120 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002121 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002122 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2123 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002124 }
2125
Wink Saville4f0de1e2011-08-04 15:01:58 -07002126 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002127 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2128 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002129 }
2130
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002131 private void sendInetConditionBroadcast(NetworkInfo info) {
2132 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2133 }
2134
Wink Saville4f0de1e2011-08-04 15:01:58 -07002135 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002136 if (mLockdownTracker != null) {
2137 info = mLockdownTracker.augmentNetworkInfo(info);
2138 }
2139
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002140 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002141 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002142 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002143 if (info.isFailover()) {
2144 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2145 info.setFailover(false);
2146 }
2147 if (info.getReason() != null) {
2148 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2149 }
2150 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002151 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2152 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002153 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002154 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002155 return intent;
2156 }
2157
2158 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2159 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2160 }
2161
2162 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2163 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002164 }
2165
Haoyu Baib5da5752012-06-20 14:29:57 -07002166 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2167 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2168 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2169 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002170 final long ident = Binder.clearCallingIdentity();
2171 try {
2172 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2173 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2174 } finally {
2175 Binder.restoreCallingIdentity(ident);
2176 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002177 }
2178
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 /**
2180 * Called when an attempt to fail over to another network has failed.
2181 * @param info the {@link NetworkInfo} for the failed network
2182 */
2183 private void handleConnectionFailure(NetworkInfo info) {
2184 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185
Robert Greenwalt2034b912009-08-12 16:08:25 -07002186 String reason = info.getReason();
2187 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002188
Robert Greenwalte981bc52010-10-08 16:35:52 -07002189 String reasonText;
2190 if (reason == null) {
2191 reasonText = ".";
2192 } else {
2193 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002194 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002195 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002196
2197 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002198 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002199 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002200 if (getActiveNetworkInfo() == null) {
2201 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2202 }
2203 if (reason != null) {
2204 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2205 }
2206 if (extraInfo != null) {
2207 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2208 }
2209 if (info.isFailover()) {
2210 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2211 info.setFailover(false);
2212 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002213
Robert Greenwalt34848c02011-03-25 13:09:25 -07002214 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002215 tryFailover(info.getType());
2216 if (mActiveDefaultNetwork != -1) {
2217 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002218 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2219 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002220 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002221 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2222 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002223 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002224
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002225 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002226
2227 final Intent immediateIntent = new Intent(intent);
2228 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2229 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002230 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002231 /*
2232 * If the failover network is already connected, then immediately send
2233 * out a followup broadcast indicating successful failover
2234 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002235 if (mActiveDefaultNetwork != -1) {
2236 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002237 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002238 }
2239
2240 private void sendStickyBroadcast(Intent intent) {
2241 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002242 if (!mSystemReady) {
2243 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002244 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002245 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002246 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002247 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002248 }
2249
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002250 final long ident = Binder.clearCallingIdentity();
2251 try {
2252 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2253 } finally {
2254 Binder.restoreCallingIdentity(ident);
2255 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002256 }
2257 }
2258
Wink Saville4f0de1e2011-08-04 15:01:58 -07002259 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2260 if (delayMs <= 0) {
2261 sendStickyBroadcast(intent);
2262 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002263 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002264 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2265 + intent.getAction());
2266 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002267 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2268 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2269 }
2270 }
2271
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002272 void systemReady() {
Wink Saville89c87b92013-08-29 08:55:16 -07002273 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2274 loadGlobalProxy();
2275
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002276 synchronized(this) {
2277 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002278 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002279 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002280 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002281 }
2282 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002283 // load the global proxy at startup
2284 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002285
2286 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2287 // for user to unlock device.
2288 if (!updateLockdownVpn()) {
2289 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2290 mContext.registerReceiver(mUserPresentReceiver, filter);
2291 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002292 }
2293
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002294 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2295 @Override
2296 public void onReceive(Context context, Intent intent) {
2297 // Try creating lockdown tracker, since user present usually means
2298 // unlocked keystore.
2299 if (updateLockdownVpn()) {
2300 mContext.unregisterReceiver(this);
2301 }
2302 }
2303 };
2304
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002305 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville89c87b92013-08-29 08:55:16 -07002306 if (((type != mNetworkPreference)
2307 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2308 || (mNetworkPreference == mActiveDefaultNetwork)) {
2309 return false;
2310 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002311 return true;
2312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002314 private void handleConnect(NetworkInfo info) {
2315 final int newNetType = info.getType();
2316
2317 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002318
The Android Open Source Project28527d22009-03-03 19:31:44 -08002319 // snapshot isFailover, because sendConnectedBroadcast() resets it
2320 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002321 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002322 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002323
Wink Saville89c87b92013-08-29 08:55:16 -07002324 if (VDBG) {
2325 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2326 + " isFailover" + isFailover);
2327 }
2328
Robert Greenwalt2034b912009-08-12 16:08:25 -07002329 // if this is a default net and other default is running
2330 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002331 if (mNetConfigs[newNetType].isDefault()) {
2332 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2333 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002334 // tear down the other
2335 NetworkStateTracker otherNet =
2336 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002337 if (DBG) {
2338 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002339 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002340 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002341 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002342 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002343 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002344 return;
2345 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002346 } else {
2347 // don't accept this one
2348 if (VDBG) {
2349 log("Not broadcasting CONNECT_ACTION " +
2350 "to torn down network " + info.getTypeName());
2351 }
2352 teardown(thisNet);
2353 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002354 }
2355 }
2356 synchronized (ConnectivityService.this) {
2357 // have a new default network, release the transition wakelock in a second
2358 // if it's held. The second pause is to allow apps to reconnect over the
2359 // new network
2360 if (mNetTransitionWakeLock.isHeld()) {
2361 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002362 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002363 mNetTransitionWakeLockSerialNumber, 0),
2364 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002365 }
2366 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002367 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002368 // this will cause us to come up initially as unconnected and switching
2369 // to connected after our normal pause unless somebody reports us as reall
2370 // disconnected
2371 mDefaultInetConditionPublished = 0;
2372 mDefaultConnectionSequence++;
2373 mInetConditionChangeInFlight = false;
2374 // Don't do this - if we never sign in stay, grey
2375 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwaltc26eb012014-02-28 16:44:00 -08002376 updateNetworkSettings(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002377 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002378 thisNet.setTeardownRequested(false);
sy.yun30043282013-09-02 05:24:09 +09002379 updateMtuSizeSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002380 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002381 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002382
2383 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002384 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002385 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002386 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002387 } catch (RemoteException e) {
2388 // ignored; service lives in system_server
2389 }
2390 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002391 }
2392
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002393 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2394 if (DBG) log("Captive portal check " + info);
2395 int type = info.getType();
2396 final NetworkStateTracker thisNet = mNetTrackers[type];
2397 if (mNetConfigs[type].isDefault()) {
2398 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2399 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2400 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002401 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002402 return;
2403 } else {
2404 if (DBG) log("Tear down low priority net " + info.getTypeName());
2405 teardown(thisNet);
2406 return;
2407 }
2408 }
2409 }
2410
Wink Savilleffdadd62013-08-07 16:22:47 -07002411 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002412 thisNet.captivePortalCheckComplete();
2413 }
2414
2415 /** @hide */
Wink Savilleffdadd62013-08-07 16:22:47 -07002416 @Override
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002417 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002418 enforceConnectivityInternalPermission();
Wink Savilleffdadd62013-08-07 16:22:47 -07002419 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002420 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002421 }
2422
Wink Savilleffdadd62013-08-07 16:22:47 -07002423 /** @hide */
2424 @Override
2425 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2426 enforceConnectivityInternalPermission();
2427 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2428 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2429 }
2430
The Android Open Source Project28527d22009-03-03 19:31:44 -08002431 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002432 * Setup data activity tracking for the given network interface.
2433 *
2434 * Every {@code setupDataActivityTracking} should be paired with a
2435 * {@link removeDataActivityTracking} for cleanup.
2436 */
2437 private void setupDataActivityTracking(int type) {
2438 final NetworkStateTracker thisNet = mNetTrackers[type];
2439 final String iface = thisNet.getLinkProperties().getInterfaceName();
2440
2441 final int timeout;
2442
2443 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002444 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2445 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002446 0);
2447 // Canonicalize mobile network type
2448 type = ConnectivityManager.TYPE_MOBILE;
2449 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002450 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2451 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002452 0);
2453 } else {
2454 // do not track any other networks
2455 timeout = 0;
2456 }
2457
2458 if (timeout > 0 && iface != null) {
2459 try {
2460 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2461 } catch (RemoteException e) {
2462 }
2463 }
2464 }
2465
2466 /**
2467 * Remove data activity tracking when network disconnects.
2468 */
2469 private void removeDataActivityTracking(int type) {
2470 final NetworkStateTracker net = mNetTrackers[type];
2471 final String iface = net.getLinkProperties().getInterfaceName();
2472
2473 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2474 ConnectivityManager.TYPE_WIFI == type)) {
2475 try {
2476 // the call fails silently if no idletimer setup for this interface
2477 mNetd.removeIdleTimer(iface);
2478 } catch (RemoteException e) {
2479 }
2480 }
2481 }
2482
2483 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002484 * After a change in the connectivity state of a network. We're mainly
2485 * concerned with making sure that the list of DNS servers is set up
2486 * according to which networks are connected, and ensuring that the
2487 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002488 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002489 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002490 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker78850f32013-07-15 16:34:04 -07002491 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville89c87b92013-08-29 08:55:16 -07002492 if (VDBG) {
2493 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2494 + " resetMask=" + resetMask);
2495 }
Wink Saville051a6642011-07-13 13:44:13 -07002496
The Android Open Source Project28527d22009-03-03 19:31:44 -08002497 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002498 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002499 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002500 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002501 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002502
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002503 LinkProperties curLp = mCurrentLinkProperties[netType];
2504 LinkProperties newLp = null;
2505
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002506 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002507 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002508 if (VDBG) {
2509 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2510 " doReset=" + doReset + " resetMask=" + resetMask +
2511 "\n curLp=" + curLp +
2512 "\n newLp=" + newLp);
2513 }
2514
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002515 if (curLp != null) {
2516 if (curLp.isIdenticalInterfaceName(newLp)) {
2517 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2518 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2519 for (LinkAddress linkAddr : car.removed) {
2520 if (linkAddr.getAddress() instanceof Inet4Address) {
2521 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2522 }
2523 if (linkAddr.getAddress() instanceof Inet6Address) {
2524 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2525 }
Wink Saville051a6642011-07-13 13:44:13 -07002526 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002527 if (DBG) {
2528 log("handleConnectivityChange: addresses changed" +
2529 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2530 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002531 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002532 } else {
2533 if (DBG) {
2534 log("handleConnectivityChange: address are the same reset per doReset" +
2535 " linkProperty[" + netType + "]:" +
2536 " resetMask=" + resetMask);
2537 }
Wink Saville051a6642011-07-13 13:44:13 -07002538 }
2539 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002540 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002541 if (DBG) {
2542 log("handleConnectivityChange: interface not not equivalent reset both" +
2543 " linkProperty[" + netType + "]:" +
2544 " resetMask=" + resetMask);
2545 }
Wink Saville051a6642011-07-13 13:44:13 -07002546 }
Wink Saville051a6642011-07-13 13:44:13 -07002547 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002548 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002549 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002550 }
2551 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002552 if (VDBG) {
2553 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2554 " doReset=" + doReset + " resetMask=" + resetMask +
2555 "\n curLp=" + curLp +
2556 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002557 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002558 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002559 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker78850f32013-07-15 16:34:04 -07002560 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002561
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002562 if (resetMask != 0 || resetDns) {
Wink Saville89c87b92013-08-29 08:55:16 -07002563 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002564 if (curLp != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07002565 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002566 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002567 if (TextUtils.isEmpty(iface) == false) {
2568 if (resetMask != 0) {
2569 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2570 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002571
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002572 // Tell VPN the interface is down. It is a temporary
2573 // but effective fix to make VPN aware of the change.
2574 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002575 synchronized(mVpns) {
2576 for (int i = 0; i < mVpns.size(); i++) {
2577 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2578 }
2579 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002580 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002581 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002582 if (resetDns) {
2583 flushVmDnsCache();
2584 if (VDBG) log("resetting DNS cache for " + iface);
2585 try {
2586 mNetd.flushInterfaceDnsCache(iface);
2587 } catch (Exception e) {
2588 // never crash - catch them all
2589 if (DBG) loge("Exception resetting dns cache: " + e);
2590 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002591 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002592 } else {
2593 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002594 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002595 }
2596 }
2597 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002598
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002599 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002600 NetworkStateTracker tracker = mNetTrackers[netType];
2601 if (mClat.requiresClat(netType, tracker)) {
Wink Saville89c87b92013-08-29 08:55:16 -07002602
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002603 // If the connection was previously using clat, but is not using it now, stop the clat
2604 // daemon. Normally, this happens automatically when the connection disconnects, but if
2605 // the disconnect is not reported, or if the connection's LinkProperties changed for
2606 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2607 // still be running. If it's not running, then stopping it is a no-op.
2608 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2609 mClat.stopClat();
2610 }
2611 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002612 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2613 mClat.startClat(tracker);
2614 } else {
2615 mClat.stopClat();
2616 }
2617 }
2618
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002619 // TODO: Temporary notifying upstread change to Tethering.
2620 // @see bug/4455071
2621 /** Notify TetheringService if interface name has been changed. */
2622 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002623 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002624 if (isTetheringSupported()) {
2625 mTethering.handleTetherIfaceChange();
2626 }
2627 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002628 }
2629
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002630 /**
2631 * Add and remove routes using the old properties (null if not previously connected),
2632 * new properties (null if becoming disconnected). May even be double null, which
2633 * is a noop.
2634 * Uses isLinkDefault to determine if default routes should be set or conversely if
2635 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002636 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002637 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002638 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker78850f32013-07-15 16:34:04 -07002639 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002640 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002641 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2642 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002643 if (curLp != null) {
2644 // check for the delta between the current set and the new
Lorenzo Colitti43553b62013-07-31 23:23:21 +09002645 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002646 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002647 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002648 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002649 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002650 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002651
Robert Greenwalt8d777252011-08-15 12:31:55 -07002652 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2653
Robert Greenwalt98107422011-07-22 11:55:33 -07002654 for (RouteInfo r : routeDiff.removed) {
2655 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002656 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002657 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2658 }
2659 if (isLinkDefault == false) {
2660 // remove from a secondary route table
2661 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002662 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002663 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002664
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002665 if (!isLinkDefault) {
2666 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002667 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002668 // routes changed - remove all old dns entries and add new
2669 if (curLp != null) {
2670 for (InetAddress oldDns : curLp.getDnses()) {
2671 removeRouteToAddress(curLp, oldDns);
2672 }
2673 }
2674 if (newLp != null) {
2675 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002676 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002677 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002678 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002679 } else {
2680 // no change in routes, check for change in dns themselves
2681 for (InetAddress oldDns : dnsDiff.removed) {
2682 removeRouteToAddress(curLp, oldDns);
2683 }
2684 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002685 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002686 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002687 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002688 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002689
2690 for (RouteInfo r : routeDiff.added) {
2691 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002692 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002693 } else {
2694 // add to a secondary route table
Chad Brubaker78850f32013-07-15 16:34:04 -07002695 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002696
2697 // many radios add a default route even when we don't want one.
2698 // remove the default route unless somebody else has asked for it
2699 String ifaceName = newLp.getInterfaceName();
Chad Brubaker78850f32013-07-15 16:34:04 -07002700 synchronized (mRoutesLock) {
2701 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2702 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2703 try {
2704 mNetd.removeRoute(ifaceName, r);
2705 } catch (Exception e) {
2706 // never crash - catch them all
2707 if (DBG) loge("Exception trying to remove a route: " + e);
2708 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002709 }
2710 }
2711 }
2712 }
2713
Robert Greenwalt8d777252011-08-15 12:31:55 -07002714 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002715 }
2716
sy.yun30043282013-09-02 05:24:09 +09002717 /**
2718 * Reads the network specific MTU size from reources.
2719 * and set it on it's iface.
2720 */
2721 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2722 final String iface = nt.getLinkProperties().getInterfaceName();
2723 final int mtu = nt.getLinkProperties().getMtu();
2724
2725 if (mtu < 68 || mtu > 10000) {
2726 loge("Unexpected mtu value: " + nt);
2727 return;
2728 }
2729
2730 try {
2731 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2732 mNetd.setMtu(iface, mtu);
2733 } catch (Exception e) {
2734 Slog.e(TAG, "exception in setMtu()" + e);
2735 }
2736 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002737
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002738 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002739 * Reads the network specific TCP buffer sizes from SystemProperties
2740 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2741 * wide use
2742 */
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002743 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002744 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002745 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002746
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002747 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002748 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002749
2750 // Setting to default values so we won't be stuck to previous values
2751 key = "net.tcp.buffersize.default";
2752 bufferSizes = SystemProperties.get(key);
2753 }
2754
2755 // Set values in kernel
2756 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002757 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002758 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002759 + "] which comes from [" + key + "]");
2760 }
2761 setBufferSize(bufferSizes);
2762 }
JP Abgrallfe9b47e2014-02-21 12:05:20 -08002763
2764 final String defaultRwndKey = "net.tcp.default_init_rwnd";
2765 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
2766 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
2767 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
2768 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2769 if (rwndValue != 0) {
2770 SystemProperties.set(sysctlKey, rwndValue.toString());
2771 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002772 }
2773
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002774 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002775 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2776 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2777 *
2778 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2779 * writeMin, writeInitial, writeMax"
2780 */
2781 private void setBufferSize(String bufferSizes) {
2782 try {
2783 String[] values = bufferSizes.split(",");
2784
2785 if (values.length == 6) {
2786 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002787 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2788 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2789 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2790 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2791 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2792 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002793 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002794 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002795 }
2796 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002797 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002798 }
2799 }
2800
Robert Greenwalt2034b912009-08-12 16:08:25 -07002801 /**
2802 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2803 * on the highest priority active net which this process requested.
2804 * If there aren't any, clear it out
2805 */
Mattias Falkdc919012011-08-23 14:15:13 +02002806 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002807 {
Mattias Falkdc919012011-08-23 14:15:13 +02002808 if (VDBG) log("reassessPidDns for pid " + pid);
2809 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002810 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002811 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002812 continue;
2813 }
2814 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002815 if (nt.getNetworkInfo().isConnected() &&
2816 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002817 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002818 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002819 if (mNetRequestersPids[i].contains(myPid)) {
2820 try {
2821 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2822 } catch (Exception e) {
2823 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002824 }
Mattias Falkdc919012011-08-23 14:15:13 +02002825 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002826 }
2827 }
2828 }
2829 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002830 try {
2831 mNetd.clearDnsInterfaceForPid(pid);
2832 } catch (Exception e) {
2833 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002834 }
2835 }
2836
Mattias Falkdc919012011-08-23 14:15:13 +02002837 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002838 /*
2839 * Tell the VMs to toss their DNS caches
2840 */
2841 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2842 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002843 /*
2844 * Connectivity events can happen before boot has completed ...
2845 */
2846 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002847 final long ident = Binder.clearCallingIdentity();
2848 try {
2849 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2850 } finally {
2851 Binder.restoreCallingIdentity(ident);
2852 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002853 }
2854
Chia-chi Yehcc844502011-07-14 18:01:57 -07002855 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002856 private void updateDnsLocked(String network, String iface,
Chad Brubaker45e721f2013-07-23 17:13:36 -07002857 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002858 int last = 0;
2859 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002860 dnses = new ArrayList();
2861 dnses.add(mDefaultDns);
2862 if (DBG) {
2863 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002864 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002865 }
2866
Mattias Falkdc919012011-08-23 14:15:13 +02002867 try {
2868 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker45e721f2013-07-23 17:13:36 -07002869 if (defaultDns) {
2870 mNetd.setDefaultInterfaceForDns(iface);
2871 }
2872
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002873 for (InetAddress dns : dnses) {
2874 ++last;
2875 String key = "net.dns" + last;
2876 String value = dns.getHostAddress();
2877 SystemProperties.set(key, value);
2878 }
2879 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2880 String key = "net.dns" + i;
2881 SystemProperties.set(key, "");
2882 }
2883 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002884 } catch (Exception e) {
Robert Greenwalt68534c82013-09-24 11:05:57 -07002885 loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002886 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002887 }
2888
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002889 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002890 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002891 NetworkStateTracker nt = mNetTrackers[netType];
2892 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002893 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002894 if (p == null) return;
2895 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002896 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002897 String network = nt.getNetworkInfo().getTypeName();
2898 synchronized (mDnsLock) {
Chad Brubakera8e81122013-07-23 17:44:41 -07002899 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002900 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002901 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002902 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002903 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002904 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002905 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002906 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002907 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002908 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002909 List<Integer> pids = mNetRequestersPids[netType];
2910 for (Integer pid : pids) {
2911 try {
2912 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2913 } catch (Exception e) {
2914 Slog.e(TAG, "exception setting interface for pid: " + e);
2915 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002916 }
2917 }
Mattias Falkdc919012011-08-23 14:15:13 +02002918 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002919 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002920 }
2921
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002922 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002923 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2924 NETWORK_RESTORE_DELAY_PROP_NAME);
2925 if(restoreDefaultNetworkDelayStr != null &&
2926 restoreDefaultNetworkDelayStr.length() != 0) {
2927 try {
2928 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2929 } catch (NumberFormatException e) {
2930 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002931 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002932 // if the system property isn't set, use the value for the apn type
2933 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2934
2935 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2936 (mNetConfigs[networkType] != null)) {
2937 ret = mNetConfigs[networkType].restoreTime;
2938 }
2939 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002940 }
2941
2942 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002943 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2944 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002945 if (mContext.checkCallingOrSelfPermission(
2946 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002947 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002948 pw.println("Permission Denial: can't dump ConnectivityService " +
2949 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2950 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002951 return;
2952 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002953
2954 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002955 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002956 for (int i = 0; i < mNetTrackers.length; i++) {
2957 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002958 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002959 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2960 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002961 if (nst.getNetworkInfo().isConnected()) {
2962 pw.println("Active network: " + nst.getNetworkInfo().
2963 getTypeName());
2964 }
2965 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002966 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002967 pw.println(nst);
2968 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002969 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002970 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002971 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002972
2973 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002974 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002975 for (int net : mPriorityList) {
2976 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002977 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002978 pidString = pidString + pid.toString() + ", ";
2979 }
2980 pw.println(pidString);
2981 }
2982 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002983 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002984
2985 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002986 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002987 for (Object requester : mFeatureUsers) {
2988 pw.println(requester.toString());
2989 }
2990 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002991 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002992
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002993 synchronized (this) {
2994 pw.println("NetworkTranstionWakeLock is currently " +
2995 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2996 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2997 }
2998 pw.println();
2999
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003000 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003001
3002 if (mInetLog != null) {
3003 pw.println();
3004 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07003005 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003006 for(int i = 0; i < mInetLog.size(); i++) {
3007 pw.println(mInetLog.get(i));
3008 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07003009 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003010 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003011 }
3012
Robert Greenwalt2034b912009-08-12 16:08:25 -07003013 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003014 private class NetworkStateTrackerHandler extends Handler {
3015 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003016 super(looper);
3017 }
3018
The Android Open Source Project28527d22009-03-03 19:31:44 -08003019 @Override
3020 public void handleMessage(Message msg) {
3021 NetworkInfo info;
3022 switch (msg.what) {
Wink Saville89c87b92013-08-29 08:55:16 -07003023 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003024 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08003025 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08003026
Wink Savillea7d56572011-09-21 11:05:43 -07003027 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville860f5282013-09-05 12:02:25 -07003028 (state == NetworkInfo.State.DISCONNECTED) ||
3029 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07003030 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07003031 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08003032 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07003033 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003034
Wink Saville89c87b92013-08-29 08:55:16 -07003035 // Since mobile has the notion of a network/apn that can be used for
3036 // provisioning we need to check every time we're connected as
3037 // CaptiveProtalTracker won't detected it because DCT doesn't report it
3038 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
3039 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
3040 // is received by MDST and sent here as EVENT_STATE_CHANGED.
3041 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Saville9564f2b2013-07-16 17:16:37 -07003042 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
3043 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleab773a72013-09-14 09:04:53 -07003044 && (((state == NetworkInfo.State.CONNECTED)
3045 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
3046 || info.isConnectedToProvisioningNetwork())) {
3047 log("ConnectivityChange checkMobileProvisioning for"
3048 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville89c87b92013-08-29 08:55:16 -07003049 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Saville9564f2b2013-07-16 17:16:37 -07003050 }
3051
Jeff Sharkeybde32692012-11-09 15:57:02 -08003052 EventLogTags.writeConnectivityStateChanged(
3053 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07003054
3055 if (info.getDetailedState() ==
3056 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003057 handleConnectionFailure(info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07003058 } else if (info.getDetailedState() ==
3059 DetailedState.CAPTIVE_PORTAL_CHECK) {
3060 handleCaptivePortalTrackerCheck(info);
Wink Saville860f5282013-09-05 12:02:25 -07003061 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07003062 /**
3063 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
3064 * for now its an in between network, its a network that
3065 * is actually a default network but we don't want it to be
3066 * announced as such to keep background applications from
3067 * trying to use it. It turns out that some still try so we
3068 * take the additional step of clearing any default routes
3069 * to the link that may have incorrectly setup by the lower
3070 * levels.
3071 */
3072 LinkProperties lp = getLinkProperties(info.getType());
3073 if (DBG) {
3074 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3075 }
3076
3077 // Clear any default routes setup by the radio so
3078 // any activity by applications trying to use this
3079 // connection will fail until the provisioning network
3080 // is enabled.
3081 for (RouteInfo r : lp.getRoutes()) {
3082 removeRoute(lp, r, TO_DEFAULT_TABLE);
3083 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08003084 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003085 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003086 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003087 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003088 // the logic here is, handle SUSPENDED the same as
3089 // DISCONNECTED. The only difference being we are
3090 // broadcasting an intent with NetworkInfo that's
3091 // suspended. This allows the applications an
3092 // opportunity to handle DISCONNECTED and SUSPENDED
3093 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003094 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003095 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003096 handleConnect(info);
3097 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003098 if (mLockdownTracker != null) {
3099 mLockdownTracker.onNetworkInfoChanged(info);
3100 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003101 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003102 }
3103 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003104 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003105 // TODO: Temporary allowing network configuration
3106 // change not resetting sockets.
3107 // @see bug/4455071
3108 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003109 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003110 }
3111 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003112 info = (NetworkInfo) msg.obj;
Wink Saville89c87b92013-08-29 08:55:16 -07003113 int type = info.getType();
Robert Greenwaltc26eb012014-02-28 16:44:00 -08003114 if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]);
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003115 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003116 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003117 }
3118 }
3119 }
3120
3121 private class InternalHandler extends Handler {
3122 public InternalHandler(Looper looper) {
3123 super(looper);
3124 }
3125
3126 @Override
3127 public void handleMessage(Message msg) {
3128 NetworkInfo info;
3129 switch (msg.what) {
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003130 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003131 String causedBy = null;
3132 synchronized (ConnectivityService.this) {
3133 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3134 mNetTransitionWakeLock.isHeld()) {
3135 mNetTransitionWakeLock.release();
3136 causedBy = mNetTransitionWakeLockCausedBy;
3137 }
3138 }
3139 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003140 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003141 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003142 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003143 }
3144 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003145 FeatureUser u = (FeatureUser)msg.obj;
3146 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003147 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003148 }
3149 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003150 int netType = msg.arg1;
3151 int condition = msg.arg2;
3152 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003153 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003154 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003155 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003156 int netType = msg.arg1;
3157 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00003158 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003159 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003160 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003161 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003162 int preference = msg.arg1;
3163 handleSetNetworkPreference(preference);
3164 break;
3165 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003166 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003167 boolean enabled = (msg.arg1 == ENABLED);
3168 handleSetMobileData(enabled);
3169 break;
3170 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003171 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003172 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003173 break;
3174 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003175 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003176 boolean met = (msg.arg1 == ENABLED);
3177 handleSetDependencyMet(msg.arg2, met);
3178 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003179 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003180 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003181 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003182 sendStickyBroadcast(intent);
3183 break;
3184 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003185 case EVENT_SET_POLICY_DATA_ENABLE: {
3186 final int networkType = msg.arg1;
3187 final boolean enabled = msg.arg2 == ENABLED;
3188 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003189 break;
3190 }
3191 case EVENT_VPN_STATE_CHANGED: {
3192 if (mLockdownTracker != null) {
3193 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3194 }
3195 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003196 }
Wink Saville690cb182013-06-29 21:10:57 -07003197 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3198 int tag = mEnableFailFastMobileDataTag.get();
3199 if (msg.arg1 == tag) {
3200 MobileDataStateTracker mobileDst =
3201 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3202 if (mobileDst != null) {
3203 mobileDst.setEnableFailFastMobileData(msg.arg2);
3204 }
3205 } else {
3206 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3207 + " != tag:" + tag);
3208 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003209 break;
Wink Saville690cb182013-06-29 21:10:57 -07003210 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003211 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07003212 handleNetworkSamplingTimeout();
3213 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003214 }
Jason Monk445cea82013-10-10 14:02:51 -04003215 case EVENT_PROXY_HAS_CHANGED: {
3216 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3217 break;
3218 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003219 }
3220 }
3221 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003222
3223 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003224 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003225 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003226
3227 if (isTetheringSupported()) {
3228 return mTethering.tether(iface);
3229 } else {
3230 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3231 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003232 }
3233
3234 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003235 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003236 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003237
3238 if (isTetheringSupported()) {
3239 return mTethering.untether(iface);
3240 } else {
3241 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3242 }
3243 }
3244
3245 // javadoc from interface
3246 public int getLastTetherError(String iface) {
3247 enforceTetherAccessPermission();
3248
3249 if (isTetheringSupported()) {
3250 return mTethering.getLastTetherError(iface);
3251 } else {
3252 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3253 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003254 }
3255
3256 // TODO - proper iface API for selection by property, inspection, etc
3257 public String[] getTetherableUsbRegexs() {
3258 enforceTetherAccessPermission();
3259 if (isTetheringSupported()) {
3260 return mTethering.getTetherableUsbRegexs();
3261 } else {
3262 return new String[0];
3263 }
3264 }
3265
3266 public String[] getTetherableWifiRegexs() {
3267 enforceTetherAccessPermission();
3268 if (isTetheringSupported()) {
3269 return mTethering.getTetherableWifiRegexs();
3270 } else {
3271 return new String[0];
3272 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003273 }
3274
Danica Chang96567052010-08-11 14:54:43 -07003275 public String[] getTetherableBluetoothRegexs() {
3276 enforceTetherAccessPermission();
3277 if (isTetheringSupported()) {
3278 return mTethering.getTetherableBluetoothRegexs();
3279 } else {
3280 return new String[0];
3281 }
3282 }
3283
Mike Lockwooded4a1742011-07-19 13:04:47 -07003284 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08003285 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003286 if (isTetheringSupported()) {
3287 return mTethering.setUsbTethering(enable);
3288 } else {
3289 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3290 }
3291 }
3292
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003293 // TODO - move iface listing, queries, etc to new module
3294 // javadoc from interface
3295 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003296 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003297 return mTethering.getTetherableIfaces();
3298 }
3299
3300 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003301 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003302 return mTethering.getTetheredIfaces();
3303 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003304
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003305 public String[] getTetheringErroredIfaces() {
3306 enforceTetherAccessPermission();
3307 return mTethering.getErroredIfaces();
3308 }
3309
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003310 // if ro.tether.denied = true we default to no tethering
3311 // gservices could set the secure setting to 1 though to enable it on a build where it
3312 // had previously been turned off.
3313 public boolean isTetheringSupported() {
3314 enforceTetherAccessPermission();
3315 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003316 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3317 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003318 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3319 mTethering.getTetherableWifiRegexs().length != 0 ||
3320 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3321 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003322 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003323
3324 // An API NetworkStateTrackers can call when they lose their network.
3325 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3326 // whichever happens first. The timer is started by the first caller and not
3327 // restarted by subsequent callers.
3328 public void requestNetworkTransitionWakelock(String forWhom) {
3329 enforceConnectivityInternalPermission();
3330 synchronized (this) {
3331 if (mNetTransitionWakeLock.isHeld()) return;
3332 mNetTransitionWakeLockSerialNumber++;
3333 mNetTransitionWakeLock.acquire();
3334 mNetTransitionWakeLockCausedBy = forWhom;
3335 }
3336 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003337 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003338 mNetTransitionWakeLockSerialNumber, 0),
3339 mNetTransitionWakeLockTimeout);
3340 return;
3341 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003342
Robert Greenwalt986c7412010-09-08 15:24:47 -07003343 // 100 percent is full good, 0 is full bad.
3344 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003345 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003346 mContext.enforceCallingOrSelfPermission(
3347 android.Manifest.permission.STATUS_BAR,
3348 "ConnectivityService");
3349
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003350 if (DBG) {
3351 int pid = getCallingPid();
3352 int uid = getCallingUid();
3353 String s = pid + "(" + uid + ") reports inet is " +
3354 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3355 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3356 mInetLog.add(s);
3357 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3358 mInetLog.remove(0);
3359 }
3360 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003361 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003362 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3363 }
3364
3365 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003366 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003367 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003368 return;
3369 }
3370 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003371 if (DBG) log("handleInetConditionChange: net=" + netType +
3372 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003373 return;
3374 }
Wink Savillea7d56572011-09-21 11:05:43 -07003375 if (VDBG) {
3376 log("handleInetConditionChange: net=" +
3377 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003378 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003379 }
Wink Saville3e866722013-01-31 00:30:13 +00003380 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003381 int delay;
3382 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003383 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003384 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003385 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003386 delay = Settings.Global.getInt(mContext.getContentResolver(),
3387 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003388 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003389 delay = Settings.Global.getInt(mContext.getContentResolver(),
3390 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003391 }
3392 mInetConditionChangeInFlight = true;
3393 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003394 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003395 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003396 // we've set the new condition, when this hold ends that will get picked up
3397 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003398 }
3399 }
3400
Wink Saville3e866722013-01-31 00:30:13 +00003401 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003402 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003403 log("handleInetConditionHoldEnd: net=" + netType +
3404 ", condition=" + mDefaultInetCondition +
3405 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003406 }
3407 mInetConditionChangeInFlight = false;
3408
3409 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003410 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003411 return;
3412 }
3413 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003414 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003415 return;
3416 }
Wink Saville3e866722013-01-31 00:30:13 +00003417 // TODO: Figure out why this optimization sometimes causes a
3418 // change in mDefaultInetCondition to be missed and the
3419 // UI to not be updated.
3420 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3421 // if (DBG) log("no change in condition - aborting");
3422 // return;
3423 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003424 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3425 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003426 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003427 return;
3428 }
Wink Saville3e866722013-01-31 00:30:13 +00003429 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003430 sendInetConditionBroadcast(networkInfo);
3431 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003432 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003433
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003434 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003435 // this information is already available as a world read/writable jvm property
3436 // so this API change wouldn't have a benifit. It also breaks the passing
3437 // of proxy info to all the JVMs.
3438 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003439 synchronized (mProxyLock) {
Jason Monk43324ee2013-07-03 17:04:33 -04003440 ProxyProperties ret = mGlobalProxy;
3441 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3442 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003443 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003444 }
3445
3446 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003447 enforceConnectivityInternalPermission();
Jason Monk43324ee2013-07-03 17:04:33 -04003448
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003449 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003450 if (proxyProperties == mGlobalProxy) return;
3451 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3452 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3453
3454 String host = "";
3455 int port = 0;
3456 String exclList = "";
Jason Monk43324ee2013-07-03 17:04:33 -04003457 String pacFileUrl = "";
3458 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3459 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003460 if (!proxyProperties.isValid()) {
3461 if (DBG)
3462 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3463 return;
3464 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003465 mGlobalProxy = new ProxyProperties(proxyProperties);
3466 host = mGlobalProxy.getHost();
3467 port = mGlobalProxy.getPort();
3468 exclList = mGlobalProxy.getExclusionList();
Jason Monk43324ee2013-07-03 17:04:33 -04003469 if (proxyProperties.getPacFileUrl() != null) {
3470 pacFileUrl = proxyProperties.getPacFileUrl();
3471 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003472 } else {
3473 mGlobalProxy = null;
3474 }
3475 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003476 final long token = Binder.clearCallingIdentity();
3477 try {
3478 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3479 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3480 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3481 exclList);
Jason Monk43324ee2013-07-03 17:04:33 -04003482 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003483 } finally {
3484 Binder.restoreCallingIdentity(token);
3485 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003486 }
3487
3488 if (mGlobalProxy == null) {
3489 proxyProperties = mDefaultProxy;
3490 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003491 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003492 }
3493
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003494 private void loadGlobalProxy() {
3495 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003496 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3497 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3498 String exclList = Settings.Global.getString(res,
3499 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk43324ee2013-07-03 17:04:33 -04003500 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3501 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3502 ProxyProperties proxyProperties;
3503 if (!TextUtils.isEmpty(pacFileUrl)) {
3504 proxyProperties = new ProxyProperties(pacFileUrl);
3505 } else {
3506 proxyProperties = new ProxyProperties(host, port, exclList);
3507 }
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003508 if (!proxyProperties.isValid()) {
3509 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3510 return;
3511 }
3512
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003513 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003514 mGlobalProxy = proxyProperties;
3515 }
3516 }
3517 }
3518
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003519 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003520 // this information is already available as a world read/writable jvm property
3521 // so this API change wouldn't have a benifit. It also breaks the passing
3522 // of proxy info to all the JVMs.
3523 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003524 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003525 return mGlobalProxy;
3526 }
3527 }
3528
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003529 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04003530 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3531 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003532 proxy = null;
3533 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003534 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003535 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003536 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwaltcf8c8942013-11-18 09:43:59 -08003537 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003538 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3539 return;
3540 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003541 mDefaultProxy = proxy;
3542
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003543 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003544 if (!mDefaultProxyDisabled) {
3545 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003546 }
3547 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003548 }
3549
3550 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003551 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3552 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003553 if (!TextUtils.isEmpty(proxy)) {
3554 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003555 if (data.length == 0) {
3556 return;
3557 }
3558
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003559 String proxyHost = data[0];
3560 int proxyPort = 8080;
3561 if (data.length > 1) {
3562 try {
3563 proxyPort = Integer.parseInt(data[1]);
3564 } catch (NumberFormatException e) {
3565 return;
3566 }
3567 }
3568 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3569 setGlobalProxy(p);
3570 }
3571 }
3572
3573 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003574 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monkaf9ded02013-08-23 19:21:25 -04003575 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003576 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003577 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003578 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3579 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003580 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003581 final long ident = Binder.clearCallingIdentity();
3582 try {
3583 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3584 } finally {
3585 Binder.restoreCallingIdentity(ident);
3586 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003587 }
3588
3589 private static class SettingsObserver extends ContentObserver {
3590 private int mWhat;
3591 private Handler mHandler;
3592 SettingsObserver(Handler handler, int what) {
3593 super(handler);
3594 mHandler = handler;
3595 mWhat = what;
3596 }
3597
3598 void observe(Context context) {
3599 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003600 resolver.registerContentObserver(Settings.Global.getUriFor(
3601 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003602 }
3603
3604 @Override
3605 public void onChange(boolean selfChange) {
3606 mHandler.obtainMessage(mWhat).sendToTarget();
3607 }
3608 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003609
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003610 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003611 Slog.d(TAG, s);
3612 }
3613
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003614 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003615 Slog.e(TAG, s);
3616 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003617
repo syncf5de5572011-07-29 23:55:49 -07003618 int convertFeatureToNetworkType(int networkType, String feature) {
3619 int usedNetworkType = networkType;
3620
3621 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3622 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3623 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3624 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3625 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3626 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3627 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3628 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3629 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3630 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3631 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3632 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3633 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3634 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3635 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3636 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3637 } else {
3638 Slog.e(TAG, "Can't match any mobile netTracker!");
3639 }
3640 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3641 if (TextUtils.equals(feature, "p2p")) {
3642 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3643 } else {
3644 Slog.e(TAG, "Can't match any wifi netTracker!");
3645 }
3646 } else {
3647 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003648 }
repo syncf5de5572011-07-29 23:55:49 -07003649 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003650 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003651
3652 private static <T> T checkNotNull(T value, String message) {
3653 if (value == null) {
3654 throw new NullPointerException(message);
3655 }
3656 return value;
3657 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003658
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003659 /**
3660 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003661 * VpnBuilder and not available in ConnectivityManager. Permissions
3662 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003663 * @hide
3664 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003665 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003666 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003667 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003668 try {
3669 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003670 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003671 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003672 synchronized(mVpns) {
Chad Brubaker4452b852014-02-11 14:18:56 -08003673 mVpns.get(user).protect(socket);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003674 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003675 return true;
3676 }
3677 } catch (Exception e) {
3678 // ignore
3679 } finally {
3680 try {
3681 socket.close();
3682 } catch (Exception e) {
3683 // ignore
3684 }
3685 }
3686 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003687 }
3688
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003689 /**
3690 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003691 * and not available in ConnectivityManager. Permissions are checked
3692 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003693 * @hide
3694 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003695 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003696 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003697 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003698 int user = UserHandle.getUserId(Binder.getCallingUid());
3699 synchronized(mVpns) {
3700 return mVpns.get(user).prepare(oldPackage, newPackage);
3701 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003702 }
3703
Chad Brubaker31de0b62013-07-11 13:29:30 -07003704 @Override
3705 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3706 enforceMarkNetworkSocketPermission();
3707 final long token = Binder.clearCallingIdentity();
3708 try {
3709 int mark = mNetd.getMarkForUid(uid);
3710 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3711 if (mark == -1) {
3712 mark = 0;
3713 }
3714 NetworkUtils.markSocket(socket.getFd(), mark);
3715 } catch (RemoteException e) {
3716 } finally {
3717 Binder.restoreCallingIdentity(token);
3718 }
3719 }
3720
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003721 /**
3722 * Configure a TUN interface and return its file descriptor. Parameters
3723 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003724 * and not available in ConnectivityManager. Permissions are checked in
3725 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003726 * @hide
3727 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003728 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003729 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003730 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003731 int user = UserHandle.getUserId(Binder.getCallingUid());
3732 synchronized(mVpns) {
3733 return mVpns.get(user).establish(config);
3734 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003735 }
3736
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003737 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003738 * Start legacy VPN, controlling native daemons as needed. Creates a
3739 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003740 */
3741 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003742 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003743 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003744 final LinkProperties egress = getActiveLinkProperties();
3745 if (egress == null) {
3746 throw new IllegalStateException("Missing active network connection");
3747 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003748 int user = UserHandle.getUserId(Binder.getCallingUid());
3749 synchronized(mVpns) {
3750 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3751 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003752 }
3753
3754 /**
3755 * Return the information of the ongoing legacy VPN. This method is used
3756 * by VpnSettings and not available in ConnectivityManager. Permissions
3757 * are checked in Vpn class.
3758 * @hide
3759 */
3760 @Override
3761 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003762 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003763 int user = UserHandle.getUserId(Binder.getCallingUid());
3764 synchronized(mVpns) {
3765 return mVpns.get(user).getLegacyVpnInfo();
3766 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003767 }
3768
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003769 /**
Chad Brubaker7dcfa2a2013-07-16 18:59:12 -07003770 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3771 * not available in ConnectivityManager.
3772 * Permissions are checked in Vpn class.
3773 * @hide
3774 */
3775 @Override
3776 public VpnConfig getVpnConfig() {
3777 int user = UserHandle.getUserId(Binder.getCallingUid());
3778 synchronized(mVpns) {
3779 return mVpns.get(user).getVpnConfig();
3780 }
3781 }
3782
3783 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003784 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3785 * through NetworkStateTracker since it works differently. For example, it
3786 * needs to override DNS servers but never takes the default routes. It
3787 * relies on another data network, and it could keep existing connections
3788 * alive after reconnecting, switching between networks, or even resuming
3789 * from deep sleep. Calls from applications should be done synchronously
3790 * to avoid race conditions. As these are all hidden APIs, refactoring can
3791 * be done whenever a better abstraction is developed.
3792 */
3793 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003794 private VpnCallback() {
3795 }
3796
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003797 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003798 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003799 }
3800
Chad Brubakerccae0d32013-06-14 11:16:51 -07003801 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003802 if (dnsServers == null) {
3803 restore();
3804 return;
3805 }
3806
3807 // Convert DNS servers into addresses.
3808 List<InetAddress> addresses = new ArrayList<InetAddress>();
3809 for (String address : dnsServers) {
3810 // Double check the addresses and remove invalid ones.
3811 try {
3812 addresses.add(InetAddress.parseNumericAddress(address));
3813 } catch (Exception e) {
3814 // ignore
3815 }
3816 }
3817 if (addresses.isEmpty()) {
3818 restore();
3819 return;
3820 }
3821
3822 // Concatenate search domains into a string.
3823 StringBuilder buffer = new StringBuilder();
3824 if (searchDomains != null) {
3825 for (String domain : searchDomains) {
3826 buffer.append(domain).append(' ');
3827 }
3828 }
3829 String domains = buffer.toString().trim();
3830
3831 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003832 synchronized (mDnsLock) {
Chad Brubaker45e721f2013-07-23 17:13:36 -07003833 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003834 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003835
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003836 // Temporarily disable the default proxy (not global).
3837 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003838 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003839 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003840 sendProxyBroadcast(null);
3841 }
3842 }
3843
3844 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003845 }
3846
Chia-chi Yehcc844502011-07-14 18:01:57 -07003847 public void restore() {
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003848 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003849 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003850 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003851 sendProxyBroadcast(mDefaultProxy);
3852 }
3853 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003854 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003855
3856 public void protect(ParcelFileDescriptor socket) {
3857 try {
3858 final int mark = mNetd.getMarkForProtect();
3859 NetworkUtils.markSocket(socket.getFd(), mark);
3860 } catch (RemoteException e) {
3861 }
3862 }
3863
3864 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3865 for (RouteInfo route : routes) {
3866 try {
3867 mNetd.setMarkedForwardingRoute(interfaze, route);
3868 } catch (RemoteException e) {
3869 }
3870 }
3871 }
3872
3873 public void setMarkedForwarding(String interfaze) {
3874 try {
3875 mNetd.setMarkedForwarding(interfaze);
3876 } catch (RemoteException e) {
3877 }
3878 }
3879
3880 public void clearMarkedForwarding(String interfaze) {
3881 try {
3882 mNetd.clearMarkedForwarding(interfaze);
3883 } catch (RemoteException e) {
3884 }
3885 }
3886
Robert Greenwalt68534c82013-09-24 11:05:57 -07003887 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003888 int uidStart = uid * UserHandle.PER_USER_RANGE;
3889 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003890 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003891 }
3892
Robert Greenwalt68534c82013-09-24 11:05:57 -07003893 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003894 int uidStart = uid * UserHandle.PER_USER_RANGE;
3895 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003896 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003897 }
3898
Robert Greenwalt68534c82013-09-24 11:05:57 -07003899 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3900 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003901 try {
3902 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003903 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003904 } catch (RemoteException e) {
3905 }
3906
3907 }
3908
Robert Greenwalt68534c82013-09-24 11:05:57 -07003909 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3910 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003911 try {
3912 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Chad Brubaker6404b922014-02-20 14:46:33 -08003913 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003914 } catch (RemoteException e) {
3915 }
3916
3917 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003918 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003919
3920 @Override
3921 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003922 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3923 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3924 return false;
3925 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003926
3927 // Tear down existing lockdown if profile was removed
3928 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3929 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003930 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003931 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3932 return false;
3933 }
3934
3935 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3936 final VpnProfile profile = VpnProfile.decode(
3937 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerccae0d32013-06-14 11:16:51 -07003938 int user = UserHandle.getUserId(Binder.getCallingUid());
3939 synchronized(mVpns) {
3940 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3941 profile));
3942 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003943 } else {
3944 setLockdownTracker(null);
3945 }
3946
3947 return true;
3948 }
3949
3950 /**
3951 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3952 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3953 */
3954 private void setLockdownTracker(LockdownVpnTracker tracker) {
3955 // Shutdown any existing tracker
3956 final LockdownVpnTracker existing = mLockdownTracker;
3957 mLockdownTracker = null;
3958 if (existing != null) {
3959 existing.shutdown();
3960 }
3961
3962 try {
3963 if (tracker != null) {
3964 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003965 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003966 mLockdownTracker = tracker;
3967 mLockdownTracker.init();
3968 } else {
3969 mNetd.setFirewallEnabled(false);
3970 }
3971 } catch (RemoteException e) {
3972 // ignored; NMS lives inside system_server
3973 }
3974 }
3975
3976 private void throwIfLockdownEnabled() {
3977 if (mLockdownEnabled) {
3978 throw new IllegalStateException("Unavailable in lockdown mode");
3979 }
3980 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003981
3982 public void supplyMessenger(int networkType, Messenger messenger) {
3983 enforceConnectivityInternalPermission();
3984
3985 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3986 mNetTrackers[networkType].supplyMessenger(messenger);
3987 }
3988 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003989
3990 public int findConnectionTypeForIface(String iface) {
3991 enforceConnectivityInternalPermission();
3992
3993 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3994 for (NetworkStateTracker tracker : mNetTrackers) {
3995 if (tracker != null) {
3996 LinkProperties lp = tracker.getLinkProperties();
3997 if (lp != null && iface.equals(lp.getInterfaceName())) {
3998 return tracker.getNetworkInfo().getType();
3999 }
4000 }
4001 }
4002 return ConnectivityManager.TYPE_NONE;
4003 }
Wink Saville690cb182013-06-29 21:10:57 -07004004
4005 /**
4006 * Have mobile data fail fast if enabled.
4007 *
4008 * @param enabled DctConstants.ENABLED/DISABLED
4009 */
4010 private void setEnableFailFastMobileData(int enabled) {
4011 int tag;
4012
4013 if (enabled == DctConstants.ENABLED) {
4014 tag = mEnableFailFastMobileDataTag.incrementAndGet();
4015 } else {
4016 tag = mEnableFailFastMobileDataTag.get();
4017 }
4018 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
4019 enabled));
4020 }
4021
Wink Savillebc588402013-08-16 17:17:28 -07004022 private boolean isMobileDataStateTrackerReady() {
4023 MobileDataStateTracker mdst =
Wink Saville89c87b92013-08-29 08:55:16 -07004024 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savillebc588402013-08-16 17:17:28 -07004025 return (mdst != null) && (mdst.isReady());
4026 }
4027
Wink Saville89c87b92013-08-29 08:55:16 -07004028 /**
4029 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
4030 */
4031
4032 /**
4033 * No connection was possible to the network.
Wink Savillea3041492013-09-06 09:53:08 -07004034 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07004035 */
Wink Savillea3041492013-09-06 09:53:08 -07004036 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville89c87b92013-08-29 08:55:16 -07004037
4038 /**
4039 * A connection was made to the internet, all is well.
Wink Savillea3041492013-09-06 09:53:08 -07004040 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07004041 */
Wink Savillea3041492013-09-06 09:53:08 -07004042 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville89c87b92013-08-29 08:55:16 -07004043
4044 /**
4045 * A connection was made but no dns server was available to resolve a name to address.
Wink Savillea3041492013-09-06 09:53:08 -07004046 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07004047 */
Wink Savillea3041492013-09-06 09:53:08 -07004048 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville89c87b92013-08-29 08:55:16 -07004049
4050 /**
4051 * A connection was made but could not open a TCP connection.
Wink Savillea3041492013-09-06 09:53:08 -07004052 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07004053 */
Wink Savillea3041492013-09-06 09:53:08 -07004054 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
4055
4056 /**
4057 * A connection was made but there was a redirection, we appear to be in walled garden.
4058 * This is an indication of a warm sim on a mobile network such as T-Mobile.
4059 */
4060 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville89c87b92013-08-29 08:55:16 -07004061
4062 /**
4063 * The mobile network is a provisioning network.
Wink Savillea3041492013-09-06 09:53:08 -07004064 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville89c87b92013-08-29 08:55:16 -07004065 */
Wink Savillea3041492013-09-06 09:53:08 -07004066 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville89c87b92013-08-29 08:55:16 -07004067
Wink Saville22163fb2014-03-13 06:54:59 -07004068 /**
4069 * The mobile network is provisioning
4070 */
4071 private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
4072
4073 private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
4074 private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
4075
Wink Savillea3041492013-09-06 09:53:08 -07004076 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville89c87b92013-08-29 08:55:16 -07004077
Wink Saville690cb182013-06-29 21:10:57 -07004078 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07004079 public int checkMobileProvisioning(int suggestedTimeOutMs) {
4080 int timeOutMs = -1;
4081 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4082 enforceConnectivityInternalPermission();
Wink Savillefdb84862013-07-02 10:55:14 -07004083
Wink Saville690cb182013-06-29 21:10:57 -07004084 final long token = Binder.clearCallingIdentity();
4085 try {
Wink Saville89c87b92013-08-29 08:55:16 -07004086 timeOutMs = suggestedTimeOutMs;
4087 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4088 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4089 }
4090
4091 // Check that mobile networks are supported
4092 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4093 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4094 if (DBG) log("checkMobileProvisioning: X no mobile network");
4095 return timeOutMs;
4096 }
4097
4098 // If we're already checking don't do it again
4099 // TODO: Add a queue of results...
4100 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4101 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4102 return timeOutMs;
4103 }
4104
Wink Savillea65f4732013-10-03 08:34:46 -07004105 // Start off with mobile notification off
4106 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004107
Wink Saville690cb182013-06-29 21:10:57 -07004108 CheckMp checkMp = new CheckMp(mContext, this);
4109 CheckMp.CallBack cb = new CheckMp.CallBack() {
4110 @Override
4111 void onComplete(Integer result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004112 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004113 NetworkInfo ni =
4114 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4115 switch(result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004116 case CMP_RESULT_CODE_CONNECTABLE:
Wink Savillea3041492013-09-06 09:53:08 -07004117 case CMP_RESULT_CODE_NO_CONNECTION:
4118 case CMP_RESULT_CODE_NO_DNS:
4119 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville89c87b92013-08-29 08:55:16 -07004120 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville690cb182013-06-29 21:10:57 -07004121 break;
4122 }
Wink Saville89c87b92013-08-29 08:55:16 -07004123 case CMP_RESULT_CODE_REDIRECTED: {
4124 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004125 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004126 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004127 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004128 }
4129 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004130 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004131 setProvNotificationVisible(true,
4132 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004133 url);
Wink Saville690cb182013-06-29 21:10:57 -07004134 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004135 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004136 }
4137 break;
4138 }
Wink Savillea3041492013-09-06 09:53:08 -07004139 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004140 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004141 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004142 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004143 setProvNotificationVisible(true,
4144 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004145 url);
Wink Saville22163fb2014-03-13 06:54:59 -07004146 // Mark that we've got a provisioning network and
4147 // Disable Mobile Data until user actually starts provisioning.
4148 mIsProvisioningNetwork.set(true);
4149 MobileDataStateTracker mdst = (MobileDataStateTracker)
4150 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4151 mdst.setInternalDataEnable(false);
Wink Saville690cb182013-06-29 21:10:57 -07004152 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004153 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004154 }
4155 break;
4156 }
Wink Saville22163fb2014-03-13 06:54:59 -07004157 case CMP_RESULT_CODE_IS_PROVISIONING: {
4158 // FIXME: Need to know when provisioning is done. Probably we can
4159 // check the completion status if successful we're done if we
4160 // "timedout" or still connected to provisioning APN turn off data?
4161 if (DBG) log("CheckMp.onComplete: provisioning started");
4162 mIsStartingProvisioning.set(false);
4163 break;
4164 }
Wink Saville690cb182013-06-29 21:10:57 -07004165 default: {
4166 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4167 break;
4168 }
4169 }
Wink Saville89c87b92013-08-29 08:55:16 -07004170 mIsCheckingMobileProvisioning.set(false);
Wink Saville690cb182013-06-29 21:10:57 -07004171 }
4172 };
4173 CheckMp.Params params =
4174 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville89c87b92013-08-29 08:55:16 -07004175 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville690cb182013-06-29 21:10:57 -07004176 checkMp.execute(params);
4177 } finally {
4178 Binder.restoreCallingIdentity(token);
Wink Saville89c87b92013-08-29 08:55:16 -07004179 if (DBG) log("checkMobileProvisioning: X");
Wink Saville690cb182013-06-29 21:10:57 -07004180 }
4181 return timeOutMs;
4182 }
4183
4184 static class CheckMp extends
4185 AsyncTask<CheckMp.Params, Void, Integer> {
4186 private static final String CHECKMP_TAG = "CheckMp";
Wink Saville8fe05f12013-10-31 06:35:22 -07004187
4188 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4189 private static boolean mTestingFailures;
4190
4191 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4192 private static final int MAX_LOOPS = 4;
4193
4194 // Number of milli-seconds to complete all of the retires
Wink Saville690cb182013-06-29 21:10:57 -07004195 public static final int MAX_TIMEOUT_MS = 60000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004196
4197 // The socket should retry only 5 seconds, the default is longer
Wink Saville690cb182013-06-29 21:10:57 -07004198 private static final int SOCKET_TIMEOUT_MS = 5000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004199
4200 // Sleep time for network errors
4201 private static final int NET_ERROR_SLEEP_SEC = 3;
4202
4203 // Sleep time for network route establishment
4204 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4205
4206 // Short sleep time for polling :(
4207 private static final int POLLING_SLEEP_SEC = 1;
4208
Wink Saville690cb182013-06-29 21:10:57 -07004209 private Context mContext;
4210 private ConnectivityService mCs;
4211 private TelephonyManager mTm;
4212 private Params mParams;
4213
4214 /**
4215 * Parameters for AsyncTask.execute
4216 */
4217 static class Params {
4218 private String mUrl;
4219 private long mTimeOutMs;
4220 private CallBack mCb;
4221
4222 Params(String url, long timeOutMs, CallBack cb) {
4223 mUrl = url;
4224 mTimeOutMs = timeOutMs;
4225 mCb = cb;
4226 }
4227
4228 @Override
4229 public String toString() {
4230 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4231 }
4232 }
4233
Wink Saville8fe05f12013-10-31 06:35:22 -07004234 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4235 // issued by name or ip address, for Google its by name so when we construct
4236 // this HostnameVerifier we'll pass the original Uri and use it to verify
4237 // the host. If the host name in the original uril fails we'll test the
4238 // hostname parameter just incase things change.
4239 static class CheckMpHostnameVerifier implements HostnameVerifier {
4240 Uri mOrgUri;
4241
4242 CheckMpHostnameVerifier(Uri orgUri) {
4243 mOrgUri = orgUri;
4244 }
4245
4246 @Override
4247 public boolean verify(String hostname, SSLSession session) {
4248 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4249 String orgUriHost = mOrgUri.getHost();
4250 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4251 if (DBG) {
4252 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4253 + " orgUriHost=" + orgUriHost);
4254 }
4255 return retVal;
4256 }
4257 }
4258
Wink Saville690cb182013-06-29 21:10:57 -07004259 /**
4260 * The call back object passed in Params. onComplete will be called
4261 * on the main thread.
4262 */
4263 abstract static class CallBack {
4264 // Called on the main thread.
4265 abstract void onComplete(Integer result);
4266 }
4267
4268 public CheckMp(Context context, ConnectivityService cs) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004269 if (Build.IS_DEBUGGABLE) {
4270 mTestingFailures =
4271 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4272 } else {
4273 mTestingFailures = false;
4274 }
4275
Wink Saville690cb182013-06-29 21:10:57 -07004276 mContext = context;
4277 mCs = cs;
4278
4279 // Setup access to TelephonyService we'll be using.
4280 mTm = (TelephonyManager) mContext.getSystemService(
4281 Context.TELEPHONY_SERVICE);
4282 }
4283
4284 /**
4285 * Get the default url to use for the test.
4286 */
4287 public String getDefaultUrl() {
4288 // See http://go/clientsdns for usage approval
4289 String server = Settings.Global.getString(mContext.getContentResolver(),
4290 Settings.Global.CAPTIVE_PORTAL_SERVER);
4291 if (server == null) {
4292 server = "clients3.google.com";
4293 }
4294 return "http://" + server + "/generate_204";
4295 }
4296
4297 /**
4298 * Detect if its possible to connect to the http url. DNS based detection techniques
4299 * do not work at all hotspots. The best way to check is to perform a request to
4300 * a known address that fetches the data we expect.
4301 */
4302 private synchronized Integer isMobileOk(Params params) {
Wink Saville89c87b92013-08-29 08:55:16 -07004303 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004304 Uri orgUri = Uri.parse(params.mUrl);
4305 Random rand = new Random();
4306 mParams = params;
4307
Wink Saville37e73122013-08-13 12:41:06 -07004308 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004309 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville39856712013-09-13 12:40:11 -07004310 log("isMobileOk: X not mobile capable result=" + result);
4311 return result;
4312 }
4313
Wink Saville22163fb2014-03-13 06:54:59 -07004314 if (mCs.mIsStartingProvisioning.get()) {
4315 result = CMP_RESULT_CODE_IS_PROVISIONING;
4316 log("isMobileOk: X is provisioning result=" + result);
4317 return result;
4318 }
4319
Wink Saville39856712013-09-13 12:40:11 -07004320 // See if we've already determined we've got a provisioning connection,
4321 // if so we don't need to do anything active.
4322 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4323 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4324 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4325 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4326
4327 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4328 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4329 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4330 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4331
4332 if (isDefaultProvisioning || isHipriProvisioning) {
4333 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4334 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville37e73122013-08-13 12:41:06 -07004335 return result;
4336 }
Wink Saville690cb182013-06-29 21:10:57 -07004337
Wink Saville37e73122013-08-13 12:41:06 -07004338 try {
Wink Saville690cb182013-06-29 21:10:57 -07004339 // Continue trying to connect until time has run out
4340 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville4a165bb2013-08-07 11:02:57 -07004341
Wink Savillebc588402013-08-16 17:17:28 -07004342 if (!mCs.isMobileDataStateTrackerReady()) {
4343 // Wait for MobileDataStateTracker to be ready.
4344 if (DBG) log("isMobileOk: mdst is not ready");
4345 while(SystemClock.elapsedRealtime() < endTime) {
4346 if (mCs.isMobileDataStateTrackerReady()) {
4347 // Enable fail fast as we'll do retries here and use a
4348 // hipri connection so the default connection stays active.
4349 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4350 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4351 break;
4352 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004353 sleep(POLLING_SLEEP_SEC);
Wink Savillebc588402013-08-16 17:17:28 -07004354 }
4355 }
4356
4357 log("isMobileOk: start hipri url=" + params.mUrl);
4358
Wink Saville4a165bb2013-08-07 11:02:57 -07004359 // First wait until we can start using hipri
4360 Binder binder = new Binder();
4361 while(SystemClock.elapsedRealtime() < endTime) {
4362 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4363 Phone.FEATURE_ENABLE_HIPRI, binder);
4364 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4365 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4366 log("isMobileOk: hipri started");
4367 break;
4368 }
4369 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville89c87b92013-08-29 08:55:16 -07004370 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville8fe05f12013-10-31 06:35:22 -07004371 sleep(POLLING_SLEEP_SEC);
Wink Saville4a165bb2013-08-07 11:02:57 -07004372 }
4373
4374 // Continue trying to connect until time has run out
Wink Saville690cb182013-06-29 21:10:57 -07004375 while(SystemClock.elapsedRealtime() < endTime) {
4376 try {
4377 // Wait for hipri to connect.
4378 // TODO: Don't poll and handle situation where hipri fails
4379 // because default is retrying. See b/9569540
4380 NetworkInfo.State state = mCs
4381 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4382 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville89c87b92013-08-29 08:55:16 -07004383 if (true/*VDBG*/) {
Wink Saville27f92732013-07-31 15:49:04 -07004384 log("isMobileOk: not connected ni=" +
Wink Saville690cb182013-06-29 21:10:57 -07004385 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville27f92732013-07-31 15:49:04 -07004386 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004387 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004388 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004389 continue;
4390 }
4391
Wink Saville89c87b92013-08-29 08:55:16 -07004392 // Hipri has started check if this is a provisioning url
4393 MobileDataStateTracker mdst = (MobileDataStateTracker)
4394 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4395 if (mdst.isProvisioningNetwork()) {
Wink Savillea3041492013-09-06 09:53:08 -07004396 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville39856712013-09-13 12:40:11 -07004397 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville89c87b92013-08-29 08:55:16 -07004398 return result;
4399 } else {
4400 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4401 }
4402
Wink Saville690cb182013-06-29 21:10:57 -07004403 // Get of the addresses associated with the url host. We need to use the
4404 // address otherwise HttpURLConnection object will use the name to get
Wink Saville8fe05f12013-10-31 06:35:22 -07004405 // the addresses and will try every address but that will bypass the
Wink Saville690cb182013-06-29 21:10:57 -07004406 // route to host we setup and the connection could succeed as the default
4407 // interface might be connected to the internet via wifi or other interface.
4408 InetAddress[] addresses;
4409 try {
4410 addresses = InetAddress.getAllByName(orgUri.getHost());
4411 } catch (UnknownHostException e) {
Wink Saville89c87b92013-08-29 08:55:16 -07004412 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville39856712013-09-13 12:40:11 -07004413 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004414 return result;
4415 }
4416 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4417
4418 // Get the type of addresses supported by this link
4419 LinkProperties lp = mCs.getLinkProperties(
4420 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti662b96c2013-08-08 11:00:12 +09004421 boolean linkHasIpv4 = lp.hasIPv4Address();
4422 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville690cb182013-06-29 21:10:57 -07004423 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4424 + " linkHasIpv6=" + linkHasIpv6);
4425
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004426 final ArrayList<InetAddress> validAddresses =
4427 new ArrayList<InetAddress>(addresses.length);
Wink Saville690cb182013-06-29 21:10:57 -07004428
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004429 for (InetAddress addr : addresses) {
4430 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4431 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4432 validAddresses.add(addr);
Wink Saville690cb182013-06-29 21:10:57 -07004433 }
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004434 }
4435
4436 if (validAddresses.size() == 0) {
4437 return CMP_RESULT_CODE_NO_CONNECTION;
4438 }
4439
4440 int addrTried = 0;
4441 while (true) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004442 // Loop through at most MAX_LOOPS valid addresses or until
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004443 // we run out of time
Wink Saville8fe05f12013-10-31 06:35:22 -07004444 if (addrTried++ >= MAX_LOOPS) {
4445 log("isMobileOk: too many loops tried - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004446 break;
4447 }
4448 if (SystemClock.elapsedRealtime() >= endTime) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004449 log("isMobileOk: spend too much time - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004450 break;
4451 }
4452
4453 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4454 validAddresses.size()));
Wink Saville690cb182013-06-29 21:10:57 -07004455
4456 // Make a route to host so we check the specific interface.
4457 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
Chad Brubakerabe88512014-02-14 13:22:34 -08004458 hostAddr.getAddress(), null)) {
Wink Saville690cb182013-06-29 21:10:57 -07004459 // Wait a short time to be sure the route is established ??
4460 log("isMobileOk:"
4461 + " wait to establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004462 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004463 } else {
4464 log("isMobileOk:"
4465 + " could not establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004466 // Wait a short time before the next attempt
4467 sleep(NET_ERROR_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004468 continue;
4469 }
4470
Wink Saville8fe05f12013-10-31 06:35:22 -07004471 // Rewrite the url to have numeric address to use the specific route
4472 // using http for half the attempts and https for the other half.
4473 // Doing https first and http second as on a redirected walled garden
4474 // such as t-mobile uses we get a SocketTimeoutException: "SSL
4475 // handshake timed out" which we declare as
4476 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4477 // having http second we will be using logic used for some time.
4478 URL newUrl;
4479 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4480 newUrl = new URL(scheme, hostAddr.getHostAddress(),
4481 orgUri.getPath());
Wink Saville690cb182013-06-29 21:10:57 -07004482 log("isMobileOk: newUrl=" + newUrl);
4483
4484 HttpURLConnection urlConn = null;
4485 try {
Wink Saville8fe05f12013-10-31 06:35:22 -07004486 // Open the connection set the request headers and get the response
4487 urlConn = (HttpURLConnection)newUrl.openConnection(
Wink Saville690cb182013-06-29 21:10:57 -07004488 java.net.Proxy.NO_PROXY);
Wink Saville8fe05f12013-10-31 06:35:22 -07004489 if (scheme.equals("https")) {
4490 ((HttpsURLConnection)urlConn).setHostnameVerifier(
4491 new CheckMpHostnameVerifier(orgUri));
4492 }
Wink Saville690cb182013-06-29 21:10:57 -07004493 urlConn.setInstanceFollowRedirects(false);
4494 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4495 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4496 urlConn.setUseCaches(false);
4497 urlConn.setAllowUserInteraction(false);
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004498 // Set the "Connection" to "Close" as by default "Keep-Alive"
4499 // is used which is useless in this case.
Wink Saville690cb182013-06-29 21:10:57 -07004500 urlConn.setRequestProperty("Connection", "close");
4501 int responseCode = urlConn.getResponseCode();
Wink Savillea3041492013-09-06 09:53:08 -07004502
4503 // For debug display the headers
4504 Map<String, List<String>> headers = urlConn.getHeaderFields();
4505 log("isMobileOk: headers=" + headers);
4506
4507 // Close the connection
Wink Saville690cb182013-06-29 21:10:57 -07004508 urlConn.disconnect();
4509 urlConn = null;
Wink Savillea3041492013-09-06 09:53:08 -07004510
Wink Saville8fe05f12013-10-31 06:35:22 -07004511 if (mTestingFailures) {
4512 // Pretend no connection, this tests using http and https
4513 result = CMP_RESULT_CODE_NO_CONNECTION;
4514 log("isMobileOk: TESTING_FAILURES, pretend no connction");
4515 continue;
4516 }
4517
Wink Savillea3041492013-09-06 09:53:08 -07004518 if (responseCode == 204) {
4519 // Return
Wink Savillea3041492013-09-06 09:53:08 -07004520 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville8fe05f12013-10-31 06:35:22 -07004521 log("isMobileOk: X got expected responseCode=" + responseCode
Wink Saville39856712013-09-13 12:40:11 -07004522 + " result=" + result);
Wink Savillea3041492013-09-06 09:53:08 -07004523 return result;
4524 } else {
4525 // Retry to be sure this was redirected, we've gotten
4526 // occasions where a server returned 200 even though
4527 // the device didn't have a "warm" sim.
4528 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004529 // TODO - it would be nice in the single-address case to do
4530 // another DNS resolve here, but flushing the cache is a bit
4531 // heavy-handed.
Wink Savillea3041492013-09-06 09:53:08 -07004532 result = CMP_RESULT_CODE_REDIRECTED;
4533 }
Wink Saville690cb182013-06-29 21:10:57 -07004534 } catch (Exception e) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004535 log("isMobileOk: HttpURLConnection Exception" + e);
Wink Savillea3041492013-09-06 09:53:08 -07004536 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004537 if (urlConn != null) {
4538 urlConn.disconnect();
4539 urlConn = null;
4540 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004541 sleep(NET_ERROR_SLEEP_SEC);
4542 continue;
Wink Saville690cb182013-06-29 21:10:57 -07004543 }
4544 }
Wink Saville39856712013-09-13 12:40:11 -07004545 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004546 return result;
4547 } catch (Exception e) {
4548 log("isMobileOk: Exception e=" + e);
4549 continue;
4550 }
4551 }
4552 log("isMobileOk: timed out");
4553 } finally {
4554 log("isMobileOk: F stop hipri");
4555 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4556 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4557 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville89c87b92013-08-29 08:55:16 -07004558
4559 // Wait for hipri to disconnect.
4560 long endTime = SystemClock.elapsedRealtime() + 5000;
4561
4562 while(SystemClock.elapsedRealtime() < endTime) {
4563 NetworkInfo.State state = mCs
4564 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4565 if (state != NetworkInfo.State.DISCONNECTED) {
4566 if (VDBG) {
4567 log("isMobileOk: connected ni=" +
4568 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4569 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004570 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004571 continue;
4572 }
4573 }
4574
Wink Saville690cb182013-06-29 21:10:57 -07004575 log("isMobileOk: X result=" + result);
4576 }
4577 return result;
4578 }
4579
4580 @Override
4581 protected Integer doInBackground(Params... params) {
4582 return isMobileOk(params[0]);
4583 }
4584
4585 @Override
4586 protected void onPostExecute(Integer result) {
4587 log("onPostExecute: result=" + result);
4588 if ((mParams != null) && (mParams.mCb != null)) {
4589 mParams.mCb.onComplete(result);
4590 }
4591 }
4592
4593 private String inetAddressesToString(InetAddress[] addresses) {
4594 StringBuffer sb = new StringBuffer();
4595 boolean firstTime = true;
4596 for(InetAddress addr : addresses) {
4597 if (firstTime) {
4598 firstTime = false;
4599 } else {
4600 sb.append(",");
4601 }
4602 sb.append(addr);
4603 }
4604 return sb.toString();
4605 }
4606
4607 private void printNetworkInfo() {
4608 boolean hasIccCard = mTm.hasIccCard();
4609 int simState = mTm.getSimState();
4610 log("hasIccCard=" + hasIccCard
4611 + " simState=" + simState);
4612 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4613 if (ni != null) {
4614 log("ni.length=" + ni.length);
4615 for (NetworkInfo netInfo: ni) {
4616 log("netInfo=" + netInfo.toString());
4617 }
4618 } else {
4619 log("no network info ni=null");
4620 }
4621 }
4622
4623 /**
4624 * Sleep for a few seconds then return.
4625 * @param seconds
4626 */
4627 private static void sleep(int seconds) {
4628 try {
4629 Thread.sleep(seconds * 1000);
4630 } catch (InterruptedException e) {
4631 e.printStackTrace();
4632 }
4633 }
4634
Wink Saville8fe05f12013-10-31 06:35:22 -07004635 private static void log(String s) {
Wink Saville690cb182013-06-29 21:10:57 -07004636 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4637 }
4638 }
4639
Wink Saville89c87b92013-08-29 08:55:16 -07004640 // TODO: Move to ConnectivityManager and make public?
4641 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4642 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville690cb182013-06-29 21:10:57 -07004643
Wink Saville89c87b92013-08-29 08:55:16 -07004644 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4645 @Override
4646 public void onReceive(Context context, Intent intent) {
4647 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4648 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4649 }
4650 }
4651 };
4652
4653 private void handleMobileProvisioningAction(String url) {
Wink Saville22163fb2014-03-13 06:54:59 -07004654 // Mark notification as not visible
Wink Savillea65f4732013-10-03 08:34:46 -07004655 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004656
4657 // If provisioning network handle as a special case,
4658 // otherwise launch browser with the intent directly.
Wink Saville22163fb2014-03-13 06:54:59 -07004659 if (mIsProvisioningNetwork.get()) {
4660 if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
4661 mIsStartingProvisioning.set(true);
Wink Saville89c87b92013-08-29 08:55:16 -07004662 MobileDataStateTracker mdst = (MobileDataStateTracker)
4663 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
Wink Saville22163fb2014-03-13 06:54:59 -07004664 mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
Wink Saville89c87b92013-08-29 08:55:16 -07004665 mdst.enableMobileProvisioning(url);
4666 } else {
Wink Saville22163fb2014-03-13 06:54:59 -07004667 if (DBG) log("handleMobileProvisioningAction: not prov network, launch browser directly");
Robert Greenwaltac8d55a2013-10-17 12:46:52 -07004668 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4669 Intent.CATEGORY_APP_BROWSER);
4670 newIntent.setData(Uri.parse(url));
Wink Saville89c87b92013-08-29 08:55:16 -07004671 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4672 Intent.FLAG_ACTIVITY_NEW_TASK);
4673 try {
4674 mContext.startActivity(newIntent);
4675 } catch (ActivityNotFoundException e) {
4676 loge("handleMobileProvisioningAction: startActivity failed" + e);
4677 }
4678 }
4679 }
4680
4681 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4682 private volatile boolean mIsNotificationVisible = false;
4683
4684 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4685 String url) {
4686 if (DBG) {
4687 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4688 + " extraInfo=" + extraInfo + " url=" + url);
4689 }
Wink Saville690cb182013-06-29 21:10:57 -07004690
4691 Resources r = Resources.getSystem();
4692 NotificationManager notificationManager = (NotificationManager) mContext
4693 .getSystemService(Context.NOTIFICATION_SERVICE);
4694
4695 if (visible) {
4696 CharSequence title;
4697 CharSequence details;
4698 int icon;
Wink Saville89c87b92013-08-29 08:55:16 -07004699 Intent intent;
4700 Notification notification = new Notification();
4701 switch (networkType) {
Wink Saville690cb182013-06-29 21:10:57 -07004702 case ConnectivityManager.TYPE_WIFI:
Wink Saville690cb182013-06-29 21:10:57 -07004703 title = r.getString(R.string.wifi_available_sign_in, 0);
4704 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004705 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004706 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004707 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4708 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4709 Intent.FLAG_ACTIVITY_NEW_TASK);
4710 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004711 break;
4712 case ConnectivityManager.TYPE_MOBILE:
4713 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville690cb182013-06-29 21:10:57 -07004714 title = r.getString(R.string.network_available_sign_in, 0);
4715 // TODO: Change this to pull from NetworkInfo once a printable
4716 // name has been added to it
4717 details = mTelephonyManager.getNetworkOperatorName();
4718 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004719 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4720 intent.putExtra("EXTRA_URL", url);
4721 intent.setFlags(0);
4722 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004723 break;
4724 default:
Wink Saville690cb182013-06-29 21:10:57 -07004725 title = r.getString(R.string.network_available_sign_in, 0);
4726 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004727 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004728 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004729 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4730 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4731 Intent.FLAG_ACTIVITY_NEW_TASK);
4732 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004733 break;
4734 }
4735
Wink Saville690cb182013-06-29 21:10:57 -07004736 notification.when = 0;
4737 notification.icon = icon;
4738 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville690cb182013-06-29 21:10:57 -07004739 notification.tickerText = title;
4740 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4741
Wink Saville89c87b92013-08-29 08:55:16 -07004742 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004743 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville89c87b92013-08-29 08:55:16 -07004744 } catch (NullPointerException npe) {
4745 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4746 npe.printStackTrace();
4747 }
Wink Saville690cb182013-06-29 21:10:57 -07004748 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004749 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004750 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville89c87b92013-08-29 08:55:16 -07004751 } catch (NullPointerException npe) {
4752 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4753 npe.printStackTrace();
4754 }
Wink Saville690cb182013-06-29 21:10:57 -07004755 }
Wink Saville89c87b92013-08-29 08:55:16 -07004756 mIsNotificationVisible = visible;
Wink Saville690cb182013-06-29 21:10:57 -07004757 }
4758
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004759 /** Location to an updatable file listing carrier provisioning urls.
4760 * An example:
4761 *
4762 * <?xml version="1.0" encoding="utf-8"?>
4763 * <provisioningUrls>
4764 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4765 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4766 * </provisioningUrls>
4767 */
4768 private static final String PROVISIONING_URL_PATH =
4769 "/data/misc/radio/provisioning_urls.xml";
4770 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004771
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004772 /** XML tag for root element. */
4773 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4774 /** XML tag for individual url */
4775 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4776 /** XML tag for redirected url */
4777 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4778 /** XML attribute for mcc */
4779 private static final String ATTR_MCC = "mcc";
4780 /** XML attribute for mnc */
4781 private static final String ATTR_MNC = "mnc";
4782
4783 private static final int REDIRECTED_PROVISIONING = 1;
4784 private static final int PROVISIONING = 2;
4785
4786 private String getProvisioningUrlBaseFromFile(int type) {
4787 FileReader fileReader = null;
4788 XmlPullParser parser = null;
4789 Configuration config = mContext.getResources().getConfiguration();
4790 String tagType;
4791
4792 switch (type) {
4793 case PROVISIONING:
4794 tagType = TAG_PROVISIONING_URL;
4795 break;
4796 case REDIRECTED_PROVISIONING:
4797 tagType = TAG_REDIRECTED_URL;
4798 break;
4799 default:
4800 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4801 type);
4802 }
4803
4804 try {
4805 fileReader = new FileReader(mProvisioningUrlFile);
4806 parser = Xml.newPullParser();
4807 parser.setInput(fileReader);
4808 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4809
4810 while (true) {
4811 XmlUtils.nextElement(parser);
4812
4813 String element = parser.getName();
4814 if (element == null) break;
4815
4816 if (element.equals(tagType)) {
4817 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4818 try {
4819 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4820 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4821 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4822 parser.next();
4823 if (parser.getEventType() == XmlPullParser.TEXT) {
4824 return parser.getText();
4825 }
4826 }
4827 }
4828 } catch (NumberFormatException e) {
4829 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4830 }
4831 }
4832 }
4833 return null;
4834 } catch (FileNotFoundException e) {
4835 loge("Carrier Provisioning Urls file not found");
4836 } catch (XmlPullParserException e) {
4837 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4838 } catch (IOException e) {
4839 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4840 } finally {
4841 if (fileReader != null) {
4842 try {
4843 fileReader.close();
4844 } catch (IOException e) {}
4845 }
4846 }
4847 return null;
4848 }
4849
Wink Savillef714b7f2013-07-20 20:31:59 -07004850 @Override
4851 public String getMobileRedirectedProvisioningUrl() {
4852 enforceConnectivityInternalPermission();
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004853 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4854 if (TextUtils.isEmpty(url)) {
4855 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4856 }
4857 return url;
4858 }
4859
Wink Savillef714b7f2013-07-20 20:31:59 -07004860 @Override
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004861 public String getMobileProvisioningUrl() {
4862 enforceConnectivityInternalPermission();
4863 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4864 if (TextUtils.isEmpty(url)) {
4865 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillef714b7f2013-07-20 20:31:59 -07004866 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004867 } else {
Wink Savillef714b7f2013-07-20 20:31:59 -07004868 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004869 }
Wink Savilledfabd992013-07-10 23:00:07 -07004870 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004871 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004872 String phoneNumber = mTelephonyManager.getLine1Number();
4873 if (TextUtils.isEmpty(phoneNumber)) {
4874 phoneNumber = "0000000000";
4875 }
Wink Saville690cb182013-06-29 21:10:57 -07004876 url = String.format(url,
4877 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4878 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004879 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004880 }
4881
Wink Saville690cb182013-06-29 21:10:57 -07004882 return url;
4883 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004884
Wink Saville89c87b92013-08-29 08:55:16 -07004885 @Override
4886 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4887 String extraInfo, String url) {
4888 enforceConnectivityInternalPermission();
4889 setProvNotificationVisible(visible, networkType, extraInfo, url);
4890 }
Wink Saville3ade4872013-08-29 14:57:08 -07004891
Yuhao Zheng15019892013-09-09 17:00:04 -07004892 @Override
4893 public void setAirplaneMode(boolean enable) {
4894 enforceConnectivityInternalPermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07004895 final long ident = Binder.clearCallingIdentity();
4896 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07004897 final ContentResolver cr = mContext.getContentResolver();
4898 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4899 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4900 intent.putExtra("state", enable);
Yuhao Zheng15019892013-09-09 17:00:04 -07004901 mContext.sendBroadcast(intent);
4902 } finally {
4903 Binder.restoreCallingIdentity(ident);
4904 }
4905 }
4906
Chad Brubakerccae0d32013-06-14 11:16:51 -07004907 private void onUserStart(int userId) {
4908 synchronized(mVpns) {
4909 Vpn userVpn = mVpns.get(userId);
4910 if (userVpn != null) {
4911 loge("Starting user already has a VPN");
4912 return;
4913 }
4914 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4915 mVpns.put(userId, userVpn);
4916 userVpn.startMonitoring(mContext, mTrackerHandler);
4917 }
4918 }
4919
4920 private void onUserStop(int userId) {
4921 synchronized(mVpns) {
4922 Vpn userVpn = mVpns.get(userId);
4923 if (userVpn == null) {
4924 loge("Stopping user has no VPN");
4925 return;
4926 }
4927 mVpns.delete(userId);
4928 }
4929 }
4930
4931 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4932 @Override
4933 public void onReceive(Context context, Intent intent) {
4934 final String action = intent.getAction();
4935 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4936 if (userId == UserHandle.USER_NULL) return;
4937
4938 if (Intent.ACTION_USER_STARTING.equals(action)) {
4939 onUserStart(userId);
4940 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4941 onUserStop(userId);
4942 }
4943 }
4944 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004945
4946 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004947 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004948 enforceAccessPermission();
4949 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004950 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004951 } else {
4952 return null;
4953 }
4954 }
4955
4956 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004957 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004958 enforceAccessPermission();
4959 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004960 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004961 } else {
4962 return null;
4963 }
4964 }
4965
4966 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004967 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004968 enforceAccessPermission();
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004969 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004970 for (NetworkStateTracker tracker : mNetTrackers) {
4971 if (tracker != null) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004972 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004973 if (li != null) {
4974 result.add(li);
4975 }
4976 }
4977 }
4978
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004979 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004980 }
4981
4982 /* Infrastructure for network sampling */
4983
4984 private void handleNetworkSamplingTimeout() {
4985
4986 log("Sampling interval elapsed, updating statistics ..");
4987
4988 // initialize list of interfaces ..
4989 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4990 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4991 for (NetworkStateTracker tracker : mNetTrackers) {
4992 if (tracker != null) {
4993 String ifaceName = tracker.getNetworkInterfaceName();
4994 if (ifaceName != null) {
4995 mapIfaceToSample.put(ifaceName, null);
4996 }
4997 }
4998 }
4999
5000 // Read samples for all interfaces
5001 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
5002
5003 // process samples for all networks
5004 for (NetworkStateTracker tracker : mNetTrackers) {
5005 if (tracker != null) {
5006 String ifaceName = tracker.getNetworkInterfaceName();
5007 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
5008 if (ss != null) {
5009 // end the previous sampling cycle
5010 tracker.stopSampling(ss);
5011 // start a new sampling cycle ..
5012 tracker.startSampling(ss);
5013 }
5014 }
5015 }
5016
5017 log("Done.");
5018
5019 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
5020 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
5021 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
5022
5023 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
5024
5025 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
5026 }
5027
5028 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
5029 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
5030 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
5031 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005032}