blob: 4cba6149d7bdde68427ff6b9266162b7723bb7bd [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Saville690cb182013-06-29 21:10:57 -070035import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080038import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville89c87b92013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090043import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.Intent;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070049import android.database.ContentObserver;
Irfan Sheriffba8388b2012-08-16 12:49:23 -070050import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080052import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080053import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070059import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Jeff Sharkey86dc7a82013-09-10 21:03:27 -070062import android.net.LinkQualityInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070073import android.net.RouteInfo;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monk43324ee2013-07-03 17:04:33 -040075import android.net.Uri;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090077import android.net.wimax.WimaxManagerConstants;
Wink Saville690cb182013-06-29 21:10:57 -070078import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070089import android.os.PowerManager;
Jeff Sharkey5663b6e2012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070093import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080094import android.os.SystemProperties;
Dianne Hackbornbc55bd12012-08-29 18:32:08 -070095import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080096import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070097import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -070098import android.security.KeyStore;
Wink Saville690cb182013-06-29 21:10:57 -070099import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700100import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800101import android.util.Slog;
Chad Brubakerccae0d32013-06-14 11:16:51 -0700102import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800105
Wink Saville690cb182013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk43324ee2013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700108import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700109import com.android.internal.net.VpnConfig;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700110import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-06-29 21:10:57 -0700111import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700112import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700113import com.android.internal.telephony.PhoneConstants;
Andrew Flynn2f158282013-10-11 10:16:31 -0700114import com.android.internal.telephony.TelephonyIntents;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700115import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700116import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700117import com.android.server.am.BatteryStatsService;
John Spurlock4ba7e412013-06-24 14:20:23 -0400118import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900119import com.android.server.connectivity.Nat464Xlat;
Jason Monk43324ee2013-07-03 17:04:33 -0400120import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800121import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700122import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700123import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700124import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700125import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700126import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700127
tk.mun093f55c2011-10-13 22:51:57 +0900128import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700129
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700130import org.xmlpull.v1.XmlPullParser;
131import org.xmlpull.v1.XmlPullParserException;
132
133import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134import java.io.FileDescriptor;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700135import java.io.FileNotFoundException;
136import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700137import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800138import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900139import java.lang.reflect.Constructor;
Wink Saville690cb182013-06-29 21:10:57 -0700140import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700141import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700142import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700143import java.net.InetAddress;
Wink Saville690cb182013-06-29 21:10:57 -0700144import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700145import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700146import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700147import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700148import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700149import java.util.GregorianCalendar;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700150import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700151import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700152import java.util.List;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700153import java.util.Map;
Wink Saville690cb182013-06-29 21:10:57 -0700154import java.util.Random;
Wink Saville89c87b92013-08-29 08:55:16 -0700155import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville690cb182013-06-29 21:10:57 -0700156import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157
158/**
159 * @hide
160 */
161public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700162 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700164 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700165 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800166
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700167 private static final boolean LOGD_RULES = false;
168
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700169 // TODO: create better separation between radio types and network types
170
Robert Greenwalt2034b912009-08-12 16:08:25 -0700171 // how long to wait before switching back to a radio's default network
172 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
173 // system property that can override the above value
174 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
175 "android.telephony.apn-restore";
176
Wink Saville690cb182013-06-29 21:10:57 -0700177 // Default value if FAIL_FAST_TIME_MS is not set
178 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
179 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
180 private static final String FAIL_FAST_TIME_MS =
181 "persist.radio.fail_fast_time_ms";
182
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700183 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
184 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
185
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700186 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700187
188 private PendingIntent mSampleIntervalElapsedIntent;
189
190 // Set network sampling interval at 12 minutes, this way, even if the timers get
191 // aggregated, it will fire at around 15 minutes, which should allow us to
192 // aggregate this timer with other timers (specially the socket keep alive timers)
193 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
194
195 // start network sampling a minute after booting ...
196 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
197
198 AlarmManager mAlarmManager;
199
Robert Greenwaltbd492212011-05-06 17:10:53 -0700200 // used in recursive route setting to add gateways for the host for which
201 // a host route was requested.
202 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
203
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800204 private Tethering mTethering;
205
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700206 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700207
Chad Brubakerccae0d32013-06-14 11:16:51 -0700208 @GuardedBy("mVpns")
209 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700210 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700211
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700212 private boolean mLockdownEnabled;
213 private LockdownVpnTracker mLockdownTracker;
214
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900215 private Nat464Xlat mClat;
216
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700217 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
218 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700219 /** Currently active network rules by UID. */
220 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700221 /** Set of ifaces that are costly. */
222 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700223
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224 /**
225 * Sometimes we want to refer to the individual network state
226 * trackers separately, and sometimes we just want to treat them
227 * abstractly.
228 */
229 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700230
Irfan Sheriffba8388b2012-08-16 12:49:23 -0700231 /* Handles captive portal check on a network */
232 private CaptivePortalTracker mCaptivePortalTracker;
233
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234 /**
Wink Saville051a6642011-07-13 13:44:13 -0700235 * The link properties that define the current links
236 */
237 private LinkProperties mCurrentLinkProperties[];
238
239 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700240 * A per Net list of the PID's that requested access to the net
241 * used both as a refcount and for per-PID DNS selection
242 */
Mattias Falkdc919012011-08-23 14:15:13 +0200243 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245 // priority order of the nettrackers
246 // (excluding dynamically set mNetworkPreference)
247 // TODO - move mNetworkTypePreference into this
248 private int[] mPriorityList;
249
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250 private Context mContext;
251 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700252 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700253 // 0 is full bad, 100 is full good
Wink Saville3e866722013-01-31 00:30:13 +0000254 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700255 private int mDefaultInetConditionPublished = 0;
256 private boolean mInetConditionChangeInFlight = false;
257 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800258
Chia-chi Yehcc844502011-07-14 18:01:57 -0700259 private Object mDnsLock = new Object();
Robert Greenwaltd44340d2013-02-11 15:25:10 -0800260 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800261
262 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700263 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264
Robert Greenwalt355205c2011-05-10 15:05:02 -0700265 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700266 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700267
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700268 private static final int ENABLED = 1;
269 private static final int DISABLED = 0;
270
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700271 private static final boolean ADD = true;
272 private static final boolean REMOVE = false;
273
274 private static final boolean TO_DEFAULT_TABLE = true;
275 private static final boolean TO_SECONDARY_TABLE = false;
276
Chad Brubaker78850f32013-07-15 16:34:04 -0700277 private static final boolean EXEMPT = true;
278 private static final boolean UNEXEMPT = false;
279
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700280 /**
281 * used internally as a delayed event to make us switch back to the
282 * default network
283 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700284 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700285
286 /**
287 * used internally to change our mobile data enabled flag
288 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700289 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700290
291 /**
292 * used internally to change our network preference setting
293 * arg1 = networkType to prefer
294 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700295 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700296
297 /**
298 * used internally to synchronize inet condition reports
299 * arg1 = networkType
300 * arg2 = condition (0 bad, 100 good)
301 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700302 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700303
304 /**
305 * used internally to mark the end of inet condition hold periods
306 * arg1 = networkType
307 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700308 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700309
310 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700311 * used internally to set enable/disable cellular data
312 * arg1 = ENBALED or DISABLED
313 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700314 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700315
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700316 /**
317 * used internally to clear a wakelock when transitioning
318 * from one net to another
319 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700320 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700321
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700322 /**
323 * used internally to reload global proxy settings
324 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700325 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700326
Robert Greenwalt34848c02011-03-25 13:09:25 -0700327 /**
328 * used internally to set external dependency met/unmet
329 * arg1 = ENABLED (met) or DISABLED (unmet)
330 * arg2 = NetworkType
331 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700332 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700333
Chia-chi Yehcc844502011-07-14 18:01:57 -0700334 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700335 * used internally to send a sticky broadcast delayed.
336 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700337 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700338
Jeff Sharkey805662d2011-08-19 02:24:24 -0700339 /**
340 * Used internally to
341 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
342 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700343 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700344
Chad Brubakera8e81122013-07-23 17:44:41 -0700345 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700346
Wink Saville690cb182013-06-29 21:10:57 -0700347 /**
348 * Used internally to disable fail fast of mobile data
349 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700350 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville690cb182013-06-29 21:10:57 -0700351
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700352 /**
353 * user internally to indicate that data sampling interval is up
354 */
355 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
356
Jason Monk445cea82013-10-10 14:02:51 -0400357 /**
358 * PAC manager has received new port.
359 */
360 private static final int EVENT_PROXY_HAS_CHANGED = 16;
361
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700362 /** Handler used for internal events. */
363 private InternalHandler mHandler;
364 /** Handler used for incoming {@link NetworkStateTracker} events. */
365 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366
367 // list of DeathRecipients used to make sure features are turned off when
368 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500369 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700370
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400371 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800372 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400373
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700374 private PowerManager.WakeLock mNetTransitionWakeLock;
375 private String mNetTransitionWakeLockCausedBy = "";
376 private int mNetTransitionWakeLockSerialNumber;
377 private int mNetTransitionWakeLockTimeout;
378
Robert Greenwalt94daa182010-09-01 11:34:05 -0700379 private InetAddress mDefaultDns;
380
Chad Brubaker78850f32013-07-15 16:34:04 -0700381 // Lock for protecting access to mAddedRoutes and mExemptAddresses
382 private final Object mRoutesLock = new Object();
383
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700384 // this collection is used to refcount the added routes - if there are none left
385 // it's time to remove the route from the route table
Chad Brubaker78850f32013-07-15 16:34:04 -0700386 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700387 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
388
Chad Brubaker78850f32013-07-15 16:34:04 -0700389 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
390 // used to handle cleanup of exempt rules
391 @GuardedBy("mRoutesLock")
392 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
393
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700394 // used in DBG mode to track inet condition reports
395 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
396 private ArrayList mInetLog;
397
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700398 // track the current default http proxy - tell the world if we get a new one (real change)
399 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltda77cb12013-04-05 17:14:19 -0700400 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700401 private boolean mDefaultProxyDisabled = false;
402
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700403 // track the global proxy.
404 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700405
Jason Monk43324ee2013-07-03 17:04:33 -0400406 private PacManager mPacManager = null;
407
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700408 private SettingsObserver mSettingsObserver;
409
Robert Greenwalt34848c02011-03-25 13:09:25 -0700410 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700411 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700412
Robert Greenwalt12c44552009-12-07 11:33:18 -0800413 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700414 public int mSimultaneity;
415 public int mType;
416 public RadioAttributes(String init) {
417 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700418 mType = Integer.parseInt(fragments[0]);
419 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700420 }
421 }
422 RadioAttributes[] mRadioAttributes;
423
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700424 // the set of network types that can only be enabled by system/sig apps
425 List mProtectedNetworks;
426
John Spurlock4ba7e412013-06-24 14:20:23 -0400427 private DataConnectionStats mDataConnectionStats;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700428
Wink Saville690cb182013-06-29 21:10:57 -0700429 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
430
431 TelephonyManager mTelephonyManager;
John Spurlock4ba7e412013-06-24 14:20:23 -0400432
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700433 public ConnectivityService(Context context, INetworkManagementService netd,
434 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700435 // Currently, omitting a NetworkFactory will create one internally
436 // TODO: create here when we have cleaner WiMAX support
437 this(context, netd, statsService, policyManager, null);
438 }
439
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700440 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700441 INetworkStatsService statsService, INetworkPolicyManager policyManager,
442 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800443 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800444
Wink Saville775aad62010-09-02 19:23:52 -0700445 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
446 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700447 mHandler = new InternalHandler(handlerThread.getLooper());
448 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700449
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700450 if (netFactory == null) {
451 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
452 }
453
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800454 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800455 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
456 String id = Settings.Secure.getString(context.getContentResolver(),
457 Settings.Secure.ANDROID_ID);
458 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700459 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800460 SystemProperties.set("net.hostname", name);
461 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800462 }
463
Robert Greenwalt94daa182010-09-01 11:34:05 -0700464 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700465 String dns = Settings.Global.getString(context.getContentResolver(),
466 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700467 if (dns == null || dns.length() == 0) {
468 dns = context.getResources().getString(
469 com.android.internal.R.string.config_default_dns_server);
470 }
471 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800472 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
473 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800474 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700475 }
476
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700477 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700478 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700479 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700480 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700481 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700482
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700483 try {
484 mPolicyManager.registerListener(mPolicyListener);
485 } catch (RemoteException e) {
486 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700487 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700488 }
489
490 final PowerManager powerManager = (PowerManager) context.getSystemService(
491 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700492 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
493 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
494 com.android.internal.R.integer.config_networkTransitionTimeout);
495
Robert Greenwalt2034b912009-08-12 16:08:25 -0700496 mNetTrackers = new NetworkStateTracker[
497 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700498 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700499
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700500 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700501 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700502
Robert Greenwalt2034b912009-08-12 16:08:25 -0700503 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700504 String[] raStrings = context.getResources().getStringArray(
505 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700506 for (String raString : raStrings) {
507 RadioAttributes r = new RadioAttributes(raString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700508 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700509 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800510 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 continue;
512 }
513 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800514 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700515 r.mType);
516 continue;
517 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700518 mRadioAttributes[r.mType] = r;
519 }
520
Wink Saville23ee8db2013-04-23 14:26:51 -0700521 // TODO: What is the "correct" way to do determine if this is a wifi only device?
522 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
523 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700524 String[] naStrings = context.getResources().getStringArray(
525 com.android.internal.R.array.networkAttributes);
526 for (String naString : naStrings) {
527 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700528 NetworkConfig n = new NetworkConfig(naString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700529 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700530 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800531 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700532 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700533 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700534 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700535 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
536 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
537 n.type);
538 continue;
539 }
Wink Savillef2a62832011-04-07 14:23:45 -0700540 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800541 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700542 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700543 continue;
544 }
Wink Savillef2a62832011-04-07 14:23:45 -0700545 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800546 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700547 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700548 continue;
549 }
Wink Savillef2a62832011-04-07 14:23:45 -0700550 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700551 mNetworksDefined++;
552 } catch(Exception e) {
553 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700554 }
555 }
Wink Saville70dbdcc2013-07-29 15:00:57 -0700556 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700557
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700558 mProtectedNetworks = new ArrayList<Integer>();
559 int[] protectedNetworks = context.getResources().getIntArray(
560 com.android.internal.R.array.config_protectedNetworks);
561 for (int p : protectedNetworks) {
562 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
563 mProtectedNetworks.add(p);
564 } else {
565 if (DBG) loge("Ignoring protectedNetwork " + p);
566 }
567 }
568
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700569 // high priority first
570 mPriorityList = new int[mNetworksDefined];
571 {
572 int insertionPoint = mNetworksDefined-1;
573 int currentLowest = 0;
574 int nextLowest = 0;
575 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700576 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700577 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700578 if (na.priority < currentLowest) continue;
579 if (na.priority > currentLowest) {
580 if (na.priority < nextLowest || nextLowest == 0) {
581 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700582 }
583 continue;
584 }
Wink Savillef2a62832011-04-07 14:23:45 -0700585 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700586 }
587 currentLowest = nextLowest;
588 nextLowest = 0;
589 }
590 }
591
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800592 // Update mNetworkPreference according to user mannually first then overlay config.xml
593 mNetworkPreference = getPersistedNetworkPreference();
594 if (mNetworkPreference == -1) {
595 for (int n : mPriorityList) {
596 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
597 mNetworkPreference = n;
598 break;
599 }
600 }
601 if (mNetworkPreference == -1) {
602 throw new IllegalStateException(
603 "You should set at least one default Network in config.xml!");
604 }
605 }
606
Mattias Falkdc919012011-08-23 14:15:13 +0200607 mNetRequestersPids =
608 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700609 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200610 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700611 }
612
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500613 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700614
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700615 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
616 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700617
618 // Create and start trackers for hard-coded networks
619 for (int targetNetworkType : mPriorityList) {
620 final NetworkConfig config = mNetConfigs[targetNetworkType];
621 final NetworkStateTracker tracker;
622 try {
623 tracker = netFactory.createTracker(targetNetworkType, config);
624 mNetTrackers[targetNetworkType] = tracker;
625 } catch (IllegalArgumentException e) {
626 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
627 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700628 continue;
629 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700630
631 tracker.startMonitoring(context, mTrackerHandler);
632 if (config.isDefault()) {
633 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800634 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700635 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800636
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700637 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800638
Robert Greenwalt00eb17f2013-07-19 14:30:49 -0700639 //set up the listener for user state for creating user VPNs
Chad Brubakerccae0d32013-06-14 11:16:51 -0700640 IntentFilter intentFilter = new IntentFilter();
641 intentFilter.addAction(Intent.ACTION_USER_STARTING);
642 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
643 mContext.registerReceiverAsUser(
644 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900645 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
646
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700647 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700648 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700649 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900650 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700651 } catch (RemoteException e) {
652 loge("Error registering observer :" + e);
653 }
654
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700655 if (DBG) {
656 mInetLog = new ArrayList();
657 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700658
659 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
660 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800661
John Spurlock4ba7e412013-06-24 14:20:23 -0400662 mDataConnectionStats = new DataConnectionStats(mContext);
663 mDataConnectionStats.startMonitoring();
Jason Monk43324ee2013-07-03 17:04:33 -0400664
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700665 // start network sampling ..
666 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
667 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700668 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700669
670 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
671 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
672
673 IntentFilter filter = new IntentFilter();
674 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
675 mContext.registerReceiver(
676 new BroadcastReceiver() {
677 @Override
678 public void onReceive(Context context, Intent intent) {
679 String action = intent.getAction();
680 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
681 mHandler.sendMessage(mHandler.obtainMessage
682 (EVENT_SAMPLE_INTERVAL_ELAPSED));
683 }
684 }
685 },
686 new IntentFilter(filter));
687
Jason Monk445cea82013-10-10 14:02:51 -0400688 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville3ade4872013-08-29 14:57:08 -0700689
690 filter = new IntentFilter();
Wink Saville89c87b92013-08-29 08:55:16 -0700691 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
692 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800693 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700694
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700695 /**
696 * Factory that creates {@link NetworkStateTracker} instances using given
697 * {@link NetworkConfig}.
698 */
699 public interface NetworkFactory {
700 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
701 }
702
703 private static class DefaultNetworkFactory implements NetworkFactory {
704 private final Context mContext;
705 private final Handler mTrackerHandler;
706
707 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
708 mContext = context;
709 mTrackerHandler = trackerHandler;
710 }
711
712 @Override
713 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
714 switch (config.radio) {
715 case TYPE_WIFI:
716 return new WifiStateTracker(targetNetworkType, config.name);
717 case TYPE_MOBILE:
718 return new MobileDataStateTracker(targetNetworkType, config.name);
719 case TYPE_DUMMY:
720 return new DummyDataStateTracker(targetNetworkType, config.name);
721 case TYPE_BLUETOOTH:
722 return BluetoothTetheringDataTracker.getInstance();
723 case TYPE_WIMAX:
724 return makeWimaxStateTracker(mContext, mTrackerHandler);
725 case TYPE_ETHERNET:
726 return EthernetDataTracker.getInstance();
727 default:
728 throw new IllegalArgumentException(
729 "Trying to create a NetworkStateTracker for an unknown radio type: "
730 + config.radio);
731 }
732 }
733 }
734
735 /**
736 * Loads external WiMAX library and registers as system service, returning a
737 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
738 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
739 */
740 private static NetworkStateTracker makeWimaxStateTracker(
741 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700742 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900743 DexClassLoader wimaxClassLoader;
744 Class wimaxStateTrackerClass = null;
745 Class wimaxServiceClass = null;
746 Class wimaxManagerClass;
747 String wimaxJarLocation;
748 String wimaxLibLocation;
749 String wimaxManagerClassName;
750 String wimaxServiceClassName;
751 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800752
tk.mun093f55c2011-10-13 22:51:57 +0900753 NetworkStateTracker wimaxStateTracker = null;
754
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700755 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900756 com.android.internal.R.bool.config_wimaxEnabled);
757
758 if (isWimaxEnabled) {
759 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700760 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900761 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700762 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900763 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700764 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900765 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700766 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900767 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700768 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900769 com.android.internal.R.string.config_wimaxStateTrackerClassname);
770
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800771 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900772 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700773 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900774 wimaxLibLocation, ClassLoader.getSystemClassLoader());
775
776 try {
777 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
778 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
779 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
780 } catch (ClassNotFoundException ex) {
781 loge("Exception finding Wimax classes: " + ex.toString());
782 return null;
783 }
784 } catch(Resources.NotFoundException ex) {
785 loge("Wimax Resources does not exist!!! ");
786 return null;
787 }
788
789 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800790 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900791
792 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
793 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700794 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
795 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900796
797 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
798 (new Class[] {Context.class, wimaxStateTrackerClass});
799 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700800 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900801 wmxSrvConst.setAccessible(false);
802
803 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
804
805 } catch(Exception ex) {
806 loge("Exception creating Wimax classes: " + ex.toString());
807 return null;
808 }
809 } else {
810 loge("Wimax is not enabled or not added to the network attributes!!! ");
811 return null;
812 }
813
814 return wimaxStateTracker;
815 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700816
The Android Open Source Project28527d22009-03-03 19:31:44 -0800817 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700818 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800819 * @param preference the new preference
820 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700821 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800822 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700823
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700824 mHandler.sendMessage(
825 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800826 }
827
828 public int getNetworkPreference() {
829 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700830 int preference;
831 synchronized(this) {
832 preference = mNetworkPreference;
833 }
834 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800835 }
836
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700837 private void handleSetNetworkPreference(int preference) {
838 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700839 mNetConfigs[preference] != null &&
840 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700841 if (mNetworkPreference != preference) {
842 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700843 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700844 synchronized(this) {
845 mNetworkPreference = preference;
846 }
847 enforcePreference();
848 }
849 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800850 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700851
Wink Saville4f0de1e2011-08-04 15:01:58 -0700852 private int getConnectivityChangeDelay() {
853 final ContentResolver cr = mContext.getContentResolver();
854
855 /** Check system properties for the default value then use secure settings value, if any. */
856 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700857 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
858 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
859 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700860 defaultDelay);
861 }
862
The Android Open Source Project28527d22009-03-03 19:31:44 -0800863 private int getPersistedNetworkPreference() {
864 final ContentResolver cr = mContext.getContentResolver();
865
Jeff Brown87272712012-09-25 15:03:20 -0700866 final int networkPrefSetting = Settings.Global
867 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800869 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800870 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700871
The Android Open Source Project28527d22009-03-03 19:31:44 -0800872 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700873 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800874 * In this method, we only tear down a non-preferred network. Establishing
875 * a connection to the preferred network is taken care of when we handle
876 * the disconnect event from the non-preferred network
877 * (see {@link #handleDisconnect(NetworkInfo)}).
878 */
879 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700880 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881 return;
882
Robert Greenwalt2034b912009-08-12 16:08:25 -0700883 if (!mNetTrackers[mNetworkPreference].isAvailable())
884 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800885
Robert Greenwalt2034b912009-08-12 16:08:25 -0700886 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700887 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700889 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800890 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700891 " in enforcePreference");
892 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700893 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800894 }
895 }
896 }
897
898 private boolean teardown(NetworkStateTracker netTracker) {
899 if (netTracker.teardown()) {
900 netTracker.setTeardownRequested(true);
901 return true;
902 } else {
903 return false;
904 }
905 }
906
907 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700908 * Check if UID should be blocked from using the network represented by the
909 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700910 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700911 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
912 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700913
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700914 final boolean networkCostly;
915 final int uidRules;
916 synchronized (mRulesLock) {
917 networkCostly = mMeteredIfaces.contains(iface);
918 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700919 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700920
921 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
922 return true;
923 }
924
925 // no restrictive rules; network is visible
926 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700927 }
928
929 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700930 * Return a filtered {@link NetworkInfo}, potentially marked
931 * {@link DetailedState#BLOCKED} based on
932 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700933 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700934 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
935 NetworkInfo info = tracker.getNetworkInfo();
936 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700937 // network is blocked; clone and override state
938 info = new NetworkInfo(info);
939 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700940 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700941 if (mLockdownTracker != null) {
942 info = mLockdownTracker.augmentNetworkInfo(info);
943 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700944 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700945 }
946
947 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800948 * Return NetworkInfo for the active (i.e., connected) network interface.
949 * It is assumed that at most one network is active at a time. If more
950 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700951 * @return the info for the active network, or {@code null} if none is
952 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800953 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700954 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800955 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700956 enforceAccessPermission();
957 final int uid = Binder.getCallingUid();
958 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800959 }
960
Wink Saville89c87b92013-08-29 08:55:16 -0700961 /**
962 * Find the first Provisioning network.
963 *
964 * @return NetworkInfo or null if none.
965 */
966 private NetworkInfo getProvisioningNetworkInfo() {
967 enforceAccessPermission();
968
969 // Find the first Provisioning Network
970 NetworkInfo provNi = null;
971 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville860f5282013-09-05 12:02:25 -0700972 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -0700973 provNi = ni;
974 break;
975 }
976 }
977 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
978 return provNi;
979 }
980
981 /**
982 * Find the first Provisioning network or the ActiveDefaultNetwork
983 * if there is no Provisioning network
984 *
985 * @return NetworkInfo or null if none.
986 */
987 @Override
988 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
989 enforceAccessPermission();
990
991 NetworkInfo provNi = getProvisioningNetworkInfo();
992 if (provNi == null) {
993 final int uid = Binder.getCallingUid();
994 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
995 }
996 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
997 return provNi;
998 }
999
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001000 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1001 enforceAccessPermission();
1002 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1003 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1004 if (tracker != null) {
1005 return tracker.getNetworkInfo();
1006 }
1007 }
1008 return null;
1009 }
1010
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001011 @Override
1012 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1013 enforceConnectivityInternalPermission();
1014 return getNetworkInfo(mActiveDefaultNetwork, uid);
1015 }
1016
1017 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001018 public NetworkInfo getNetworkInfo(int networkType) {
1019 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001020 final int uid = Binder.getCallingUid();
1021 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001022 }
1023
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001024 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1025 NetworkInfo info = null;
1026 if (isNetworkTypeValid(networkType)) {
1027 final NetworkStateTracker tracker = mNetTrackers[networkType];
1028 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001029 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001030 }
1031 }
1032 return info;
1033 }
1034
1035 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001036 public NetworkInfo[] getAllNetworkInfo() {
1037 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001038 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001039 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001040 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001041 for (NetworkStateTracker tracker : mNetTrackers) {
1042 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001043 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001044 }
1045 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001046 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001047 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001048 }
1049
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001050 @Override
1051 public boolean isNetworkSupported(int networkType) {
1052 enforceAccessPermission();
1053 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1054 }
1055
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001056 /**
1057 * Return LinkProperties for the active (i.e., connected) default
1058 * network interface. It is assumed that at most one default network
1059 * is active at a time. If more than one is active, it is indeterminate
1060 * which will be returned.
1061 * @return the ip properties for the active network, or {@code null} if
1062 * none is active
1063 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001064 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001065 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001066 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001067 }
1068
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001069 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001070 public LinkProperties getLinkProperties(int networkType) {
1071 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001072 if (isNetworkTypeValid(networkType)) {
1073 final NetworkStateTracker tracker = mNetTrackers[networkType];
1074 if (tracker != null) {
1075 return tracker.getLinkProperties();
1076 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001077 }
1078 return null;
1079 }
1080
Jeff Sharkey21062e72011-05-28 20:56:34 -07001081 @Override
1082 public NetworkState[] getAllNetworkState() {
1083 enforceAccessPermission();
1084 final int uid = Binder.getCallingUid();
1085 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001086 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001087 for (NetworkStateTracker tracker : mNetTrackers) {
1088 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001089 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001090 result.add(new NetworkState(
1091 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1092 }
1093 }
1094 }
1095 return result.toArray(new NetworkState[result.size()]);
1096 }
1097
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001098 private NetworkState getNetworkStateUnchecked(int networkType) {
1099 if (isNetworkTypeValid(networkType)) {
1100 final NetworkStateTracker tracker = mNetTrackers[networkType];
1101 if (tracker != null) {
1102 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1103 tracker.getLinkCapabilities());
1104 }
1105 }
1106 return null;
1107 }
1108
1109 @Override
1110 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1111 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001112
1113 final long token = Binder.clearCallingIdentity();
1114 try {
1115 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1116 if (state != null) {
1117 try {
1118 return mPolicyManager.getNetworkQuotaInfo(state);
1119 } catch (RemoteException e) {
1120 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001121 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001122 return null;
1123 } finally {
1124 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001125 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001126 }
1127
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001128 @Override
1129 public boolean isActiveNetworkMetered() {
1130 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001131 final long token = Binder.clearCallingIdentity();
1132 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001133 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001134 } finally {
1135 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001136 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001137 }
1138
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001139 private boolean isNetworkMeteredUnchecked(int networkType) {
1140 final NetworkState state = getNetworkStateUnchecked(networkType);
1141 if (state != null) {
1142 try {
1143 return mPolicyManager.isNetworkMetered(state);
1144 } catch (RemoteException e) {
1145 }
1146 }
1147 return false;
1148 }
1149
The Android Open Source Project28527d22009-03-03 19:31:44 -08001150 public boolean setRadios(boolean turnOn) {
1151 boolean result = true;
1152 enforceChangePermission();
1153 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001154 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 }
1156 return result;
1157 }
1158
1159 public boolean setRadio(int netType, boolean turnOn) {
1160 enforceChangePermission();
1161 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1162 return false;
1163 }
1164 NetworkStateTracker tracker = mNetTrackers[netType];
1165 return tracker != null && tracker.setRadio(turnOn);
1166 }
1167
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001168 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1169 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001170 public void interfaceClassDataActivityChanged(String label, boolean active) {
1171 int deviceType = Integer.parseInt(label);
1172 sendDataActivityBroadcast(deviceType, active);
1173 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001174 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001175
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001176 /**
1177 * Used to notice when the calling process dies so we can self-expire
1178 *
1179 * Also used to know if the process has cleaned up after itself when
1180 * our auto-expire timer goes off. The timer has a link to an object.
1181 *
1182 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001183 private class FeatureUser implements IBinder.DeathRecipient {
1184 int mNetworkType;
1185 String mFeature;
1186 IBinder mBinder;
1187 int mPid;
1188 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001189 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001190
1191 FeatureUser(int type, String feature, IBinder binder) {
1192 super();
1193 mNetworkType = type;
1194 mFeature = feature;
1195 mBinder = binder;
1196 mPid = getCallingPid();
1197 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001198 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001199
Robert Greenwalt2034b912009-08-12 16:08:25 -07001200 try {
1201 mBinder.linkToDeath(this, 0);
1202 } catch (RemoteException e) {
1203 binderDied();
1204 }
1205 }
1206
1207 void unlinkDeathRecipient() {
1208 mBinder.unlinkToDeath(this, 0);
1209 }
1210
1211 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001212 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001213 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1214 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001215 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001216 }
1217
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001218 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001219 if (VDBG) {
1220 log("ConnectivityService FeatureUser expire(" +
1221 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1222 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1223 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001224 stopUsingNetworkFeature(this, false);
1225 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001226
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001227 public boolean isSameUser(FeatureUser u) {
1228 if (u == null) return false;
1229
1230 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1231 }
1232
1233 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1234 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1235 TextUtils.equals(mFeature, feature)) {
1236 return true;
1237 }
1238 return false;
1239 }
1240
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001241 public String toString() {
1242 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1243 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1244 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001245 }
1246
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001247 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001248 public int startUsingNetworkFeature(int networkType, String feature,
1249 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001250 long startTime = 0;
1251 if (DBG) {
1252 startTime = SystemClock.elapsedRealtime();
1253 }
Wink Savillea7d56572011-09-21 11:05:43 -07001254 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001255 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1256 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001257 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001258 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001259 try {
1260 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1261 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001262 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001263 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001264
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001265 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001266
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001267 // TODO - move this into individual networktrackers
1268 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001269
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001270 if (mLockdownEnabled) {
1271 // Since carrier APNs usually aren't available from VPN
1272 // endpoint, mark them as unavailable.
1273 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1274 }
1275
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001276 if (mProtectedNetworks.contains(usedNetworkType)) {
1277 enforceConnectivityInternalPermission();
1278 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001279
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001280 // if UID is restricted, don't allow them to bring up metered APNs
1281 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1282 final int uidRules;
1283 synchronized (mRulesLock) {
1284 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1285 }
1286 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001287 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001288 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001289
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001290 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1291 if (network != null) {
1292 Integer currentPid = new Integer(getCallingPid());
1293 if (usedNetworkType != networkType) {
1294 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001295
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001296 if (ni.isAvailable() == false) {
1297 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1298 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001299 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001300 } else {
1301 // else make the attempt anyway - probably giving REQUEST_STARTED below
1302 if (DBG) {
1303 log("special network not available, but try anyway ni=" +
1304 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001305 }
1306 }
1307 }
1308
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001309 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001310
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001311 synchronized(this) {
1312 boolean addToList = true;
1313 if (restoreTimer < 0) {
1314 // In case there is no timer is specified for the feature,
1315 // make sure we don't add duplicate entry with the same request.
1316 for (FeatureUser u : mFeatureUsers) {
1317 if (u.isSameUser(f)) {
1318 // Duplicate user is found. Do not add.
1319 addToList = false;
1320 break;
1321 }
1322 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001323 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001324
1325 if (addToList) mFeatureUsers.add(f);
1326 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1327 // this gets used for per-pid dns when connected
1328 mNetRequestersPids[usedNetworkType].add(currentPid);
1329 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001330 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001331
1332 if (restoreTimer >= 0) {
1333 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1334 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1335 }
1336
1337 if ((ni.isConnectedOrConnecting() == true) &&
1338 !network.isTeardownRequested()) {
1339 if (ni.isConnected() == true) {
1340 final long token = Binder.clearCallingIdentity();
1341 try {
1342 // add the pid-specific dns
1343 handleDnsConfigurationChange(usedNetworkType);
1344 if (VDBG) log("special network already active");
1345 } finally {
1346 Binder.restoreCallingIdentity(token);
1347 }
Wink Saville64e3f782012-07-10 12:37:54 -07001348 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001349 }
1350 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001351 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001352 }
1353
1354 // check if the radio in play can make another contact
1355 // assume if cannot for now
1356
1357 if (DBG) {
1358 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1359 feature);
1360 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001361 if (network.reconnect()) {
Wink Saville89c87b92013-08-29 08:55:16 -07001362 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001363 return PhoneConstants.APN_REQUEST_STARTED;
1364 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07001365 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001366 return PhoneConstants.APN_REQUEST_FAILED;
1367 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001368 } else {
1369 // need to remember this unsupported request so we respond appropriately on stop
1370 synchronized(this) {
1371 mFeatureUsers.add(f);
1372 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1373 // this gets used for per-pid dns when connected
1374 mNetRequestersPids[usedNetworkType].add(currentPid);
1375 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001376 }
Wink Saville89c87b92013-08-29 08:55:16 -07001377 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001378 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001379 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001380 }
Wink Saville89c87b92013-08-29 08:55:16 -07001381 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001382 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001383 } finally {
1384 if (DBG) {
1385 final long execTime = SystemClock.elapsedRealtime() - startTime;
1386 if (execTime > 250) {
1387 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1388 } else {
1389 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1390 }
1391 }
1392 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001393 }
1394
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001396 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001397 enforceChangePermission();
1398
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001399 int pid = getCallingPid();
1400 int uid = getCallingUid();
1401
1402 FeatureUser u = null;
1403 boolean found = false;
1404
1405 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001406 for (FeatureUser x : mFeatureUsers) {
1407 if (x.isSameUser(pid, uid, networkType, feature)) {
1408 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001409 found = true;
1410 break;
1411 }
1412 }
1413 }
1414 if (found && u != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07001415 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001416 // stop regardless of how many other time this proc had called start
1417 return stopUsingNetworkFeature(u, true);
1418 } else {
1419 // none found!
Wink Saville89c87b92013-08-29 08:55:16 -07001420 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001421 return 1;
1422 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001423 }
1424
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001425 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1426 int networkType = u.mNetworkType;
1427 String feature = u.mFeature;
1428 int pid = u.mPid;
1429 int uid = u.mUid;
1430
1431 NetworkStateTracker tracker = null;
1432 boolean callTeardown = false; // used to carry our decision outside of sync block
1433
Wink Savillea7d56572011-09-21 11:05:43 -07001434 if (VDBG) {
1435 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001436 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001437
The Android Open Source Project28527d22009-03-03 19:31:44 -08001438 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001439 if (DBG) {
1440 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1441 ", net is invalid");
1442 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001443 return -1;
1444 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001445
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001446 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1447 // sync block
1448 synchronized(this) {
1449 // check if this process still has an outstanding start request
1450 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001451 if (VDBG) {
1452 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1453 ", ignoring");
1454 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001455 return 1;
1456 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001457 u.unlinkDeathRecipient();
1458 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1459 // If we care about duplicate requests, check for that here.
1460 //
1461 // This is done to support the extension of a request - the app
1462 // can request we start the network feature again and renew the
1463 // auto-shutoff delay. Normal "stop" calls from the app though
1464 // do not pay attention to duplicate requests - in effect the
1465 // API does not refcount and a single stop will counter multiple starts.
1466 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001467 for (FeatureUser x : mFeatureUsers) {
1468 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001469 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001470 return 1;
1471 }
1472 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001473 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001474
repo syncf5de5572011-07-29 23:55:49 -07001475 // TODO - move to individual network trackers
1476 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1477
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001478 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001479 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001480 if (DBG) {
1481 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1482 " no known tracker for used net type " + usedNetworkType);
1483 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001484 return -1;
1485 }
1486 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001487 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001488 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001489
1490 final long token = Binder.clearCallingIdentity();
1491 try {
1492 reassessPidDns(pid, true);
1493 } finally {
1494 Binder.restoreCallingIdentity(token);
1495 }
Mattias Falkdc919012011-08-23 14:15:13 +02001496 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001497 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001498 if (VDBG) {
1499 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1500 " others still using it");
1501 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001502 return 1;
1503 }
1504 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001505 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001506 if (DBG) {
1507 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1508 " not a known feature - dropping");
1509 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001510 }
1511 }
Wink Savillea7d56572011-09-21 11:05:43 -07001512
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001513 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001514 if (DBG) {
1515 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1516 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001517 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001518 return 1;
1519 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001520 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001521 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001522 }
1523
1524 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001525 * @deprecated use requestRouteToHostAddress instead
1526 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527 * Ensure that a network route exists to deliver traffic to the specified
1528 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001529 * @param networkType the type of the network over which traffic to the
1530 * specified host is to be routed
1531 * @param hostAddress the IP address of the host to which the route is
1532 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001533 * @return {@code true} on success, {@code false} on failure
1534 */
1535 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001536 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1537
1538 if (inetAddress == null) {
1539 return false;
1540 }
1541
1542 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1543 }
1544
1545 /**
1546 * Ensure that a network route exists to deliver traffic to the specified
1547 * host via the specified network interface.
1548 * @param networkType the type of the network over which traffic to the
1549 * specified host is to be routed
1550 * @param hostAddress the IP address of the host to which the route is
1551 * desired
1552 * @return {@code true} on success, {@code false} on failure
1553 */
1554 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001556 if (mProtectedNetworks.contains(networkType)) {
1557 enforceConnectivityInternalPermission();
1558 }
1559
The Android Open Source Project28527d22009-03-03 19:31:44 -08001560 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001561 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001562 return false;
1563 }
1564 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001565 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001566
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001567 if (tracker == null || (netState != DetailedState.CONNECTED &&
1568 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001569 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001570 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001571 log("requestRouteToHostAddress on down network "
1572 + "(" + networkType + ") - dropped"
1573 + " tracker=" + tracker
1574 + " netState=" + netState
1575 + " isTeardownRequested="
1576 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001577 }
1578 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001579 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001580 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001581 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001582 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001583 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker78850f32013-07-15 16:34:04 -07001584 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville690cb182013-06-29 21:10:57 -07001585 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1586 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001587 } catch (UnknownHostException e) {
1588 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1589 } finally {
1590 Binder.restoreCallingIdentity(token);
1591 }
Wink Saville690cb182013-06-29 21:10:57 -07001592 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001593 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001594 }
1595
Chad Brubaker78850f32013-07-15 16:34:04 -07001596 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1597 boolean exempt) {
1598 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001599 }
1600
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001601 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001602 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001603 }
1604
Chad Brubaker78850f32013-07-15 16:34:04 -07001605 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1606 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001607 }
1608
1609 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001610 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001611 }
1612
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001613 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001614 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001615 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001616 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001617 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001618 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001619 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001620 if (bestRoute.getGateway().equals(addr)) {
1621 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001622 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001623 } else {
1624 // if we will connect to this through another route, add a direct route
1625 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001626 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001627 }
1628 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001629 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001630 }
1631
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001632 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001633 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001634 if ((lp == null) || (r == null)) {
1635 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001636 return false;
1637 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001638
1639 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001640 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001641 return false;
1642 }
1643
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001644 String ifaceName = r.getInterface();
1645 if(ifaceName == null) {
1646 loge("Error modifying route - no interface name");
1647 return false;
1648 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001649 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001650 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001651 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001652 if (bestRoute.getGateway().equals(r.getGateway())) {
1653 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001654 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001655 } else {
1656 // if we will connect to our gateway through another route, add a direct
1657 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001658 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1659 bestRoute.getGateway(),
1660 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001661 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001662 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001663 }
1664 }
1665 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001666 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001667 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001668 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001669 synchronized (mRoutesLock) {
1670 // only track default table - only one apps can effect
1671 mAddedRoutes.add(r);
1672 mNetd.addRoute(ifaceName, r);
1673 if (exempt) {
1674 LinkAddress dest = r.getDestination();
1675 if (!mExemptAddresses.contains(dest)) {
1676 mNetd.setHostExemption(dest);
1677 mExemptAddresses.add(dest);
1678 }
1679 }
1680 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001681 } else {
1682 mNetd.addSecondaryRoute(ifaceName, r);
1683 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001684 } catch (Exception e) {
1685 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001686 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001687 return false;
1688 }
1689 } else {
1690 // if we remove this one and there are no more like it, then refcount==0 and
1691 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001692 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001693 synchronized (mRoutesLock) {
1694 mAddedRoutes.remove(r);
1695 if (mAddedRoutes.contains(r) == false) {
1696 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1697 try {
1698 mNetd.removeRoute(ifaceName, r);
1699 LinkAddress dest = r.getDestination();
1700 if (mExemptAddresses.contains(dest)) {
1701 mNetd.clearHostExemption(dest);
1702 mExemptAddresses.remove(dest);
1703 }
1704 } catch (Exception e) {
1705 // never crash - catch them all
1706 if (VDBG) loge("Exception trying to remove a route: " + e);
1707 return false;
1708 }
1709 } else {
1710 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001711 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001712 }
1713 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001714 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001715 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001716 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001717 } catch (Exception e) {
1718 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001719 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001720 return false;
1721 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001722 }
1723 }
1724 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001725 }
1726
1727 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001728 * @see ConnectivityManager#getMobileDataEnabled()
1729 */
1730 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001731 // TODO: This detail should probably be in DataConnectionTracker's
1732 // which is where we store the value and maybe make this
1733 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001734 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001735 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1736 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001737 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001738 return retVal;
1739 }
1740
Robert Greenwalt34848c02011-03-25 13:09:25 -07001741 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001742 enforceConnectivityInternalPermission();
1743
Robert Greenwalt34848c02011-03-25 13:09:25 -07001744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1745 (met ? ENABLED : DISABLED), networkType));
1746 }
1747
1748 private void handleSetDependencyMet(int networkType, boolean met) {
1749 if (mNetTrackers[networkType] != null) {
1750 if (DBG) {
1751 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1752 }
1753 mNetTrackers[networkType].setDependencyMet(met);
1754 }
1755 }
1756
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001757 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1758 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001759 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001760 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001761 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001762 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001763 }
1764
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001765 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001766 // skip update when we've already applied rules
1767 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1768 if (oldRules == uidRules) return;
1769
1770 mUidRules.put(uid, uidRules);
1771 }
1772
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001773 // TODO: notify UID when it has requested targeted updates
1774 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001775
1776 @Override
1777 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001778 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001779 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001780 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001781 }
1782
1783 synchronized (mRulesLock) {
1784 mMeteredIfaces.clear();
1785 for (String iface : meteredIfaces) {
1786 mMeteredIfaces.add(iface);
1787 }
1788 }
1789 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001790
1791 @Override
1792 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1793 // caller is NPMS, since we only register with them
1794 if (LOGD_RULES) {
1795 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1796 }
1797
1798 // kick off connectivity change broadcast for active network, since
1799 // global background policy change is radical.
1800 final int networkType = mActiveDefaultNetwork;
1801 if (isNetworkTypeValid(networkType)) {
1802 final NetworkStateTracker tracker = mNetTrackers[networkType];
1803 if (tracker != null) {
1804 final NetworkInfo info = tracker.getNetworkInfo();
1805 if (info != null && info.isConnected()) {
1806 sendConnectedBroadcast(info);
1807 }
1808 }
1809 }
1810 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001811 };
1812
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001813 /**
1814 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1815 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001816 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001817 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001818 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001819
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001821 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001822 }
1823
1824 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001825 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001826 if (VDBG) {
1827 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001828 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001829 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1830 }
tk.mun5eee1042012-01-06 10:43:52 +09001831 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1832 if (VDBG) {
1833 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1834 }
1835 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1836 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001837 }
1838
1839 @Override
1840 public void setPolicyDataEnable(int networkType, boolean enabled) {
1841 // only someone like NPMS should only be calling us
1842 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1843
1844 mHandler.sendMessage(mHandler.obtainMessage(
1845 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1846 }
1847
1848 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1849 if (isNetworkTypeValid(networkType)) {
1850 final NetworkStateTracker tracker = mNetTrackers[networkType];
1851 if (tracker != null) {
1852 tracker.setPolicyDataEnable(enabled);
1853 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001854 }
1855 }
1856
The Android Open Source Project28527d22009-03-03 19:31:44 -08001857 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001858 mContext.enforceCallingOrSelfPermission(
1859 android.Manifest.permission.ACCESS_NETWORK_STATE,
1860 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 }
1862
1863 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001864 mContext.enforceCallingOrSelfPermission(
1865 android.Manifest.permission.CHANGE_NETWORK_STATE,
1866 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001867 }
1868
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001869 // TODO Make this a special check when it goes public
1870 private void enforceTetherChangePermission() {
1871 mContext.enforceCallingOrSelfPermission(
1872 android.Manifest.permission.CHANGE_NETWORK_STATE,
1873 "ConnectivityService");
1874 }
1875
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001876 private void enforceTetherAccessPermission() {
1877 mContext.enforceCallingOrSelfPermission(
1878 android.Manifest.permission.ACCESS_NETWORK_STATE,
1879 "ConnectivityService");
1880 }
1881
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001882 private void enforceConnectivityInternalPermission() {
1883 mContext.enforceCallingOrSelfPermission(
1884 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1885 "ConnectivityService");
1886 }
1887
Chad Brubaker31de0b62013-07-11 13:29:30 -07001888 private void enforceMarkNetworkSocketPermission() {
1889 //Media server special case
1890 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1891 return;
1892 }
1893 mContext.enforceCallingOrSelfPermission(
1894 android.Manifest.permission.MARK_NETWORK_SOCKET,
1895 "ConnectivityService");
1896 }
1897
The Android Open Source Project28527d22009-03-03 19:31:44 -08001898 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001899 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1900 * network, we ignore it. If it is for the active network, we send out a
1901 * broadcast. But first, we check whether it might be possible to connect
1902 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 * @param info the {@code NetworkInfo} for the network
1904 */
1905 private void handleDisconnect(NetworkInfo info) {
1906
Robert Greenwalt2034b912009-08-12 16:08:25 -07001907 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908
Robert Greenwalt2034b912009-08-12 16:08:25 -07001909 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001910
1911 // Remove idletimer previously setup in {@code handleConnect}
1912 removeDataActivityTracking(prevNetType);
1913
The Android Open Source Project28527d22009-03-03 19:31:44 -08001914 /*
1915 * If the disconnected network is not the active one, then don't report
1916 * this as a loss of connectivity. What probably happened is that we're
1917 * getting the disconnect for a network that we explicitly disabled
1918 * in accordance with network preference policies.
1919 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001920 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001921 List<Integer> pids = mNetRequestersPids[prevNetType];
1922 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001923 // will remove them because the net's no longer connected
1924 // need to do this now as only now do we know the pids and
1925 // can properly null things that are no longer referenced.
1926 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001927 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001928 }
1929
The Android Open Source Project28527d22009-03-03 19:31:44 -08001930 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001931 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001932 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 if (info.isFailover()) {
1934 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1935 info.setFailover(false);
1936 }
1937 if (info.getReason() != null) {
1938 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1939 }
1940 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001941 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1942 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001943 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001944
Robert Greenwalt34848c02011-03-25 13:09:25 -07001945 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001946 tryFailover(prevNetType);
1947 if (mActiveDefaultNetwork != -1) {
1948 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001949 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1950 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001951 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001952 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1953 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001954 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001955 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001956
1957 // Reset interface if no other connections are using the same interface
1958 boolean doReset = true;
1959 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1960 if (linkProperties != null) {
1961 String oldIface = linkProperties.getInterfaceName();
1962 if (TextUtils.isEmpty(oldIface) == false) {
1963 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1964 if (networkStateTracker == null) continue;
1965 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1966 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1967 LinkProperties l = networkStateTracker.getLinkProperties();
1968 if (l == null) continue;
1969 if (oldIface.equals(l.getInterfaceName())) {
1970 doReset = false;
1971 break;
1972 }
1973 }
1974 }
1975 }
1976 }
1977
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001978 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001979 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001980
Jeff Sharkey971cd162011-08-29 16:02:57 -07001981 final Intent immediateIntent = new Intent(intent);
1982 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1983 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001984 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001985 /*
1986 * If the failover network is already connected, then immediately send
1987 * out a followup broadcast indicating successful failover
1988 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001989 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001990 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1991 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001992 }
1993 }
1994
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001995 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001996 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001997 * If this is a default network, check if other defaults are available.
1998 * Try to reconnect on all available and let them hash it out when
1999 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07002000 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07002001 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002002 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville89c87b92013-08-29 08:55:16 -07002003 if (DBG) {
2004 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2005 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002006 mActiveDefaultNetwork = -1;
2007 }
2008
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002009 // don't signal a reconnect for anything lower or equal priority than our
2010 // current connected default
2011 // TODO - don't filter by priority now - nice optimization but risky
2012// int currentPriority = -1;
2013// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002014// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002015// }
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002016
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002017 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002018 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002019 if (mNetConfigs[checkType] == null) continue;
2020 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002021 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002022
2023// Enabling the isAvailable() optimization caused mobile to not get
2024// selected if it was in the middle of error handling. Specifically
2025// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2026// would not be available and we wouldn't get connected to anything.
2027// So removing the isAvailable() optimization below for now. TODO: This
2028// optimization should work and we need to investigate why it doesn't work.
2029// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2030// complete before it is really complete.
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002031
Wink Saville72a95b92011-01-26 15:43:49 -08002032// if (!mNetTrackers[checkType].isAvailable()) continue;
2033
Robert Greenwalt34848c02011-03-25 13:09:25 -07002034// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002035
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002036 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2037 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2038 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2039 checkInfo.setFailover(true);
2040 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002041 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002042 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002043 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002044 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002045 }
2046
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002047 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002048 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002049 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2050 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002051 }
2052
Wink Saville4f0de1e2011-08-04 15:01:58 -07002053 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002054 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2055 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002056 }
2057
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002058 private void sendInetConditionBroadcast(NetworkInfo info) {
2059 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2060 }
2061
Wink Saville4f0de1e2011-08-04 15:01:58 -07002062 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002063 if (mLockdownTracker != null) {
2064 info = mLockdownTracker.augmentNetworkInfo(info);
2065 }
2066
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002067 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002068 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002069 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002070 if (info.isFailover()) {
2071 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2072 info.setFailover(false);
2073 }
2074 if (info.getReason() != null) {
2075 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2076 }
2077 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002078 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2079 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002080 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002081 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002082 return intent;
2083 }
2084
2085 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2086 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2087 }
2088
2089 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2090 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002091 }
2092
Haoyu Baib5da5752012-06-20 14:29:57 -07002093 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2094 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2095 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2096 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002097 final long ident = Binder.clearCallingIdentity();
2098 try {
2099 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2100 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002104 }
2105
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 /**
2107 * Called when an attempt to fail over to another network has failed.
2108 * @param info the {@link NetworkInfo} for the failed network
2109 */
2110 private void handleConnectionFailure(NetworkInfo info) {
2111 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002112
Robert Greenwalt2034b912009-08-12 16:08:25 -07002113 String reason = info.getReason();
2114 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002115
Robert Greenwalte981bc52010-10-08 16:35:52 -07002116 String reasonText;
2117 if (reason == null) {
2118 reasonText = ".";
2119 } else {
2120 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002121 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002122 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002123
2124 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002125 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002126 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002127 if (getActiveNetworkInfo() == null) {
2128 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2129 }
2130 if (reason != null) {
2131 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2132 }
2133 if (extraInfo != null) {
2134 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2135 }
2136 if (info.isFailover()) {
2137 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2138 info.setFailover(false);
2139 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002140
Robert Greenwalt34848c02011-03-25 13:09:25 -07002141 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002142 tryFailover(info.getType());
2143 if (mActiveDefaultNetwork != -1) {
2144 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002145 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2146 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002147 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002148 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2149 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002150 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002151
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002152 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002153
2154 final Intent immediateIntent = new Intent(intent);
2155 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2156 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002157 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002158 /*
2159 * If the failover network is already connected, then immediately send
2160 * out a followup broadcast indicating successful failover
2161 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002162 if (mActiveDefaultNetwork != -1) {
2163 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002164 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002165 }
2166
2167 private void sendStickyBroadcast(Intent intent) {
2168 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002169 if (!mSystemReady) {
2170 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002171 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002172 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002173 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002174 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002175 }
2176
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002177 final long ident = Binder.clearCallingIdentity();
2178 try {
2179 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2180 } finally {
2181 Binder.restoreCallingIdentity(ident);
2182 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002183 }
2184 }
2185
Wink Saville4f0de1e2011-08-04 15:01:58 -07002186 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2187 if (delayMs <= 0) {
2188 sendStickyBroadcast(intent);
2189 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002190 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002191 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2192 + intent.getAction());
2193 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002194 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2195 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2196 }
2197 }
2198
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002199 void systemReady() {
Wink Saville89c87b92013-08-29 08:55:16 -07002200 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2201 loadGlobalProxy();
2202
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002203 synchronized(this) {
2204 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002205 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002206 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002207 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002208 }
2209 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002210 // load the global proxy at startup
2211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002212
2213 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2214 // for user to unlock device.
2215 if (!updateLockdownVpn()) {
2216 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2217 mContext.registerReceiver(mUserPresentReceiver, filter);
2218 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002219 }
2220
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002221 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2222 @Override
2223 public void onReceive(Context context, Intent intent) {
2224 // Try creating lockdown tracker, since user present usually means
2225 // unlocked keystore.
2226 if (updateLockdownVpn()) {
2227 mContext.unregisterReceiver(this);
2228 }
2229 }
2230 };
2231
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002232 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville89c87b92013-08-29 08:55:16 -07002233 if (((type != mNetworkPreference)
2234 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2235 || (mNetworkPreference == mActiveDefaultNetwork)) {
2236 return false;
2237 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002238 return true;
2239 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002240
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002241 private void handleConnect(NetworkInfo info) {
2242 final int newNetType = info.getType();
2243
2244 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002245
The Android Open Source Project28527d22009-03-03 19:31:44 -08002246 // snapshot isFailover, because sendConnectedBroadcast() resets it
2247 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002248 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002249 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002250
Wink Saville89c87b92013-08-29 08:55:16 -07002251 if (VDBG) {
2252 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2253 + " isFailover" + isFailover);
2254 }
2255
Robert Greenwalt2034b912009-08-12 16:08:25 -07002256 // if this is a default net and other default is running
2257 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002258 if (mNetConfigs[newNetType].isDefault()) {
2259 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2260 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002261 // tear down the other
2262 NetworkStateTracker otherNet =
2263 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002264 if (DBG) {
2265 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002266 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002267 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002268 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002269 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002270 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002271 return;
2272 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002273 } else {
2274 // don't accept this one
2275 if (VDBG) {
2276 log("Not broadcasting CONNECT_ACTION " +
2277 "to torn down network " + info.getTypeName());
2278 }
2279 teardown(thisNet);
2280 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002281 }
2282 }
2283 synchronized (ConnectivityService.this) {
2284 // have a new default network, release the transition wakelock in a second
2285 // if it's held. The second pause is to allow apps to reconnect over the
2286 // new network
2287 if (mNetTransitionWakeLock.isHeld()) {
2288 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002289 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002290 mNetTransitionWakeLockSerialNumber, 0),
2291 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002292 }
2293 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002294 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002295 // this will cause us to come up initially as unconnected and switching
2296 // to connected after our normal pause unless somebody reports us as reall
2297 // disconnected
2298 mDefaultInetConditionPublished = 0;
2299 mDefaultConnectionSequence++;
2300 mInetConditionChangeInFlight = false;
2301 // Don't do this - if we never sign in stay, grey
2302 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002303 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002304 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002305 updateNetworkSettings(thisNet);
sy.yun30043282013-09-02 05:24:09 +09002306 updateMtuSizeSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002307 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002308 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002309
2310 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002311 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002312 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002313 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002314 } catch (RemoteException e) {
2315 // ignored; service lives in system_server
2316 }
2317 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002318 }
2319
Wink Savilleffdadd62013-08-07 16:22:47 -07002320 /** @hide */
2321 @Override
2322 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2323 enforceConnectivityInternalPermission();
2324 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2325 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2326 }
2327
The Android Open Source Project28527d22009-03-03 19:31:44 -08002328 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002329 * Setup data activity tracking for the given network interface.
2330 *
2331 * Every {@code setupDataActivityTracking} should be paired with a
2332 * {@link removeDataActivityTracking} for cleanup.
2333 */
2334 private void setupDataActivityTracking(int type) {
2335 final NetworkStateTracker thisNet = mNetTrackers[type];
2336 final String iface = thisNet.getLinkProperties().getInterfaceName();
2337
2338 final int timeout;
2339
2340 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002341 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2342 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002343 0);
2344 // Canonicalize mobile network type
2345 type = ConnectivityManager.TYPE_MOBILE;
2346 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002347 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2348 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002349 0);
2350 } else {
2351 // do not track any other networks
2352 timeout = 0;
2353 }
2354
2355 if (timeout > 0 && iface != null) {
2356 try {
2357 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2358 } catch (RemoteException e) {
2359 }
2360 }
2361 }
2362
2363 /**
2364 * Remove data activity tracking when network disconnects.
2365 */
2366 private void removeDataActivityTracking(int type) {
2367 final NetworkStateTracker net = mNetTrackers[type];
2368 final String iface = net.getLinkProperties().getInterfaceName();
2369
2370 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2371 ConnectivityManager.TYPE_WIFI == type)) {
2372 try {
2373 // the call fails silently if no idletimer setup for this interface
2374 mNetd.removeIdleTimer(iface);
2375 } catch (RemoteException e) {
2376 }
2377 }
2378 }
2379
2380 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002381 * After a change in the connectivity state of a network. We're mainly
2382 * concerned with making sure that the list of DNS servers is set up
2383 * according to which networks are connected, and ensuring that the
2384 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002385 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002386 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002387 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker78850f32013-07-15 16:34:04 -07002388 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville89c87b92013-08-29 08:55:16 -07002389 if (VDBG) {
2390 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2391 + " resetMask=" + resetMask);
2392 }
Wink Saville051a6642011-07-13 13:44:13 -07002393
The Android Open Source Project28527d22009-03-03 19:31:44 -08002394 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002395 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002396 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002397 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002398 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002399
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002400 LinkProperties curLp = mCurrentLinkProperties[netType];
2401 LinkProperties newLp = null;
2402
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002403 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002404 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002405 if (VDBG) {
2406 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2407 " doReset=" + doReset + " resetMask=" + resetMask +
2408 "\n curLp=" + curLp +
2409 "\n newLp=" + newLp);
2410 }
2411
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002412 if (curLp != null) {
2413 if (curLp.isIdenticalInterfaceName(newLp)) {
2414 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2415 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2416 for (LinkAddress linkAddr : car.removed) {
2417 if (linkAddr.getAddress() instanceof Inet4Address) {
2418 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2419 }
2420 if (linkAddr.getAddress() instanceof Inet6Address) {
2421 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2422 }
Wink Saville051a6642011-07-13 13:44:13 -07002423 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002424 if (DBG) {
2425 log("handleConnectivityChange: addresses changed" +
2426 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2427 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002428 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002429 } else {
2430 if (DBG) {
2431 log("handleConnectivityChange: address are the same reset per doReset" +
2432 " linkProperty[" + netType + "]:" +
2433 " resetMask=" + resetMask);
2434 }
Wink Saville051a6642011-07-13 13:44:13 -07002435 }
2436 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002437 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002438 if (DBG) {
2439 log("handleConnectivityChange: interface not not equivalent reset both" +
2440 " linkProperty[" + netType + "]:" +
2441 " resetMask=" + resetMask);
2442 }
Wink Saville051a6642011-07-13 13:44:13 -07002443 }
Wink Saville051a6642011-07-13 13:44:13 -07002444 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002445 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002446 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002447 }
2448 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002449 if (VDBG) {
2450 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2451 " doReset=" + doReset + " resetMask=" + resetMask +
2452 "\n curLp=" + curLp +
2453 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002454 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002455 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002456 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker78850f32013-07-15 16:34:04 -07002457 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002458
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002459 if (resetMask != 0 || resetDns) {
Wink Saville89c87b92013-08-29 08:55:16 -07002460 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002461 if (curLp != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07002462 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002463 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002464 if (TextUtils.isEmpty(iface) == false) {
2465 if (resetMask != 0) {
2466 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2467 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002468
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002469 // Tell VPN the interface is down. It is a temporary
2470 // but effective fix to make VPN aware of the change.
2471 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002472 synchronized(mVpns) {
2473 for (int i = 0; i < mVpns.size(); i++) {
2474 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2475 }
2476 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002477 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002478 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002479 if (resetDns) {
2480 flushVmDnsCache();
2481 if (VDBG) log("resetting DNS cache for " + iface);
2482 try {
2483 mNetd.flushInterfaceDnsCache(iface);
2484 } catch (Exception e) {
2485 // never crash - catch them all
2486 if (DBG) loge("Exception resetting dns cache: " + e);
2487 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002488 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002489 } else {
2490 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002491 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002492 }
2493 }
2494 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002495
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002496 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002497 NetworkStateTracker tracker = mNetTrackers[netType];
2498 if (mClat.requiresClat(netType, tracker)) {
Wink Saville89c87b92013-08-29 08:55:16 -07002499
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002500 // If the connection was previously using clat, but is not using it now, stop the clat
2501 // daemon. Normally, this happens automatically when the connection disconnects, but if
2502 // the disconnect is not reported, or if the connection's LinkProperties changed for
2503 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2504 // still be running. If it's not running, then stopping it is a no-op.
2505 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2506 mClat.stopClat();
2507 }
2508 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002509 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2510 mClat.startClat(tracker);
2511 } else {
2512 mClat.stopClat();
2513 }
2514 }
2515
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002516 // TODO: Temporary notifying upstread change to Tethering.
2517 // @see bug/4455071
2518 /** Notify TetheringService if interface name has been changed. */
2519 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002520 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002521 if (isTetheringSupported()) {
2522 mTethering.handleTetherIfaceChange();
2523 }
2524 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002525 }
2526
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002527 /**
2528 * Add and remove routes using the old properties (null if not previously connected),
2529 * new properties (null if becoming disconnected). May even be double null, which
2530 * is a noop.
2531 * Uses isLinkDefault to determine if default routes should be set or conversely if
2532 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002533 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002534 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002535 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker78850f32013-07-15 16:34:04 -07002536 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002537 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002538 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2539 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002540 if (curLp != null) {
2541 // check for the delta between the current set and the new
Lorenzo Colitti43553b62013-07-31 23:23:21 +09002542 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002543 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002544 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002545 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002546 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002547 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002548
Robert Greenwalt8d777252011-08-15 12:31:55 -07002549 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2550
Robert Greenwalt98107422011-07-22 11:55:33 -07002551 for (RouteInfo r : routeDiff.removed) {
2552 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002553 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002554 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2555 }
2556 if (isLinkDefault == false) {
2557 // remove from a secondary route table
2558 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002559 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002560 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002561
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002562 if (!isLinkDefault) {
2563 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002564 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002565 // routes changed - remove all old dns entries and add new
2566 if (curLp != null) {
2567 for (InetAddress oldDns : curLp.getDnses()) {
2568 removeRouteToAddress(curLp, oldDns);
2569 }
2570 }
2571 if (newLp != null) {
2572 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002573 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002574 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002575 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002576 } else {
2577 // no change in routes, check for change in dns themselves
2578 for (InetAddress oldDns : dnsDiff.removed) {
2579 removeRouteToAddress(curLp, oldDns);
2580 }
2581 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002582 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002583 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002584 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002585 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002586
2587 for (RouteInfo r : routeDiff.added) {
2588 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002589 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002590 } else {
2591 // add to a secondary route table
Chad Brubaker78850f32013-07-15 16:34:04 -07002592 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002593
2594 // many radios add a default route even when we don't want one.
2595 // remove the default route unless somebody else has asked for it
2596 String ifaceName = newLp.getInterfaceName();
Chad Brubaker78850f32013-07-15 16:34:04 -07002597 synchronized (mRoutesLock) {
2598 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2599 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2600 try {
2601 mNetd.removeRoute(ifaceName, r);
2602 } catch (Exception e) {
2603 // never crash - catch them all
2604 if (DBG) loge("Exception trying to remove a route: " + e);
2605 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002606 }
2607 }
2608 }
2609 }
2610
Robert Greenwalt8d777252011-08-15 12:31:55 -07002611 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002612 }
2613
sy.yun30043282013-09-02 05:24:09 +09002614 /**
2615 * Reads the network specific MTU size from reources.
2616 * and set it on it's iface.
2617 */
2618 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2619 final String iface = nt.getLinkProperties().getInterfaceName();
2620 final int mtu = nt.getLinkProperties().getMtu();
2621
2622 if (mtu < 68 || mtu > 10000) {
2623 loge("Unexpected mtu value: " + nt);
2624 return;
2625 }
2626
2627 try {
2628 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2629 mNetd.setMtu(iface, mtu);
2630 } catch (Exception e) {
2631 Slog.e(TAG, "exception in setMtu()" + e);
2632 }
2633 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002634
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002635 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002636 * Reads the network specific TCP buffer sizes from SystemProperties
2637 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2638 * wide use
2639 */
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002640 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002641 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002642 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002643
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002644 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002645 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002646
2647 // Setting to default values so we won't be stuck to previous values
2648 key = "net.tcp.buffersize.default";
2649 bufferSizes = SystemProperties.get(key);
2650 }
2651
2652 // Set values in kernel
2653 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002654 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002655 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002656 + "] which comes from [" + key + "]");
2657 }
2658 setBufferSize(bufferSizes);
2659 }
2660 }
2661
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002662 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002663 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2664 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2665 *
2666 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2667 * writeMin, writeInitial, writeMax"
2668 */
2669 private void setBufferSize(String bufferSizes) {
2670 try {
2671 String[] values = bufferSizes.split(",");
2672
2673 if (values.length == 6) {
2674 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002675 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2676 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2677 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2678 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2679 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2680 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002681 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002682 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002683 }
2684 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002685 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002686 }
2687 }
2688
Robert Greenwalt2034b912009-08-12 16:08:25 -07002689 /**
2690 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2691 * on the highest priority active net which this process requested.
2692 * If there aren't any, clear it out
2693 */
Mattias Falkdc919012011-08-23 14:15:13 +02002694 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002695 {
Mattias Falkdc919012011-08-23 14:15:13 +02002696 if (VDBG) log("reassessPidDns for pid " + pid);
2697 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002698 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002699 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002700 continue;
2701 }
2702 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002703 if (nt.getNetworkInfo().isConnected() &&
2704 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002705 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002706 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002707 if (mNetRequestersPids[i].contains(myPid)) {
2708 try {
2709 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2710 } catch (Exception e) {
2711 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002712 }
Mattias Falkdc919012011-08-23 14:15:13 +02002713 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002714 }
2715 }
2716 }
2717 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002718 try {
2719 mNetd.clearDnsInterfaceForPid(pid);
2720 } catch (Exception e) {
2721 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002722 }
2723 }
2724
Mattias Falkdc919012011-08-23 14:15:13 +02002725 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002726 /*
2727 * Tell the VMs to toss their DNS caches
2728 */
2729 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2730 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002731 /*
2732 * Connectivity events can happen before boot has completed ...
2733 */
2734 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002735 final long ident = Binder.clearCallingIdentity();
2736 try {
2737 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2738 } finally {
2739 Binder.restoreCallingIdentity(ident);
2740 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002741 }
2742
Chia-chi Yehcc844502011-07-14 18:01:57 -07002743 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002744 private void updateDnsLocked(String network, String iface,
Chad Brubaker45e721f2013-07-23 17:13:36 -07002745 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002746 int last = 0;
2747 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002748 dnses = new ArrayList();
2749 dnses.add(mDefaultDns);
2750 if (DBG) {
2751 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002752 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002753 }
2754
Mattias Falkdc919012011-08-23 14:15:13 +02002755 try {
2756 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker45e721f2013-07-23 17:13:36 -07002757 if (defaultDns) {
2758 mNetd.setDefaultInterfaceForDns(iface);
2759 }
2760
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002761 for (InetAddress dns : dnses) {
2762 ++last;
2763 String key = "net.dns" + last;
2764 String value = dns.getHostAddress();
2765 SystemProperties.set(key, value);
2766 }
2767 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2768 String key = "net.dns" + i;
2769 SystemProperties.set(key, "");
2770 }
2771 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002772 } catch (Exception e) {
Robert Greenwalt68534c82013-09-24 11:05:57 -07002773 loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002774 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002775 }
2776
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002777 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002778 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002779 NetworkStateTracker nt = mNetTrackers[netType];
2780 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002781 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002782 if (p == null) return;
2783 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002784 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002785 String network = nt.getNetworkInfo().getTypeName();
2786 synchronized (mDnsLock) {
Chad Brubakera8e81122013-07-23 17:44:41 -07002787 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002788 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002789 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002790 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002791 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002792 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002793 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002794 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002795 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002796 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002797 List<Integer> pids = mNetRequestersPids[netType];
2798 for (Integer pid : pids) {
2799 try {
2800 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2801 } catch (Exception e) {
2802 Slog.e(TAG, "exception setting interface for pid: " + e);
2803 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002804 }
2805 }
Mattias Falkdc919012011-08-23 14:15:13 +02002806 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002807 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002808 }
2809
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002810 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002811 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2812 NETWORK_RESTORE_DELAY_PROP_NAME);
2813 if(restoreDefaultNetworkDelayStr != null &&
2814 restoreDefaultNetworkDelayStr.length() != 0) {
2815 try {
2816 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2817 } catch (NumberFormatException e) {
2818 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002819 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002820 // if the system property isn't set, use the value for the apn type
2821 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2822
2823 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2824 (mNetConfigs[networkType] != null)) {
2825 ret = mNetConfigs[networkType].restoreTime;
2826 }
2827 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002828 }
2829
2830 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002831 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2832 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002833 if (mContext.checkCallingOrSelfPermission(
2834 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002835 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002836 pw.println("Permission Denial: can't dump ConnectivityService " +
2837 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2838 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002839 return;
2840 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002841
2842 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002843 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002844 for (int i = 0; i < mNetTrackers.length; i++) {
2845 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002846 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002847 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2848 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002849 if (nst.getNetworkInfo().isConnected()) {
2850 pw.println("Active network: " + nst.getNetworkInfo().
2851 getTypeName());
2852 }
2853 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002854 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002855 pw.println(nst);
2856 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002857 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002858 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002859 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002860
2861 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002862 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002863 for (int net : mPriorityList) {
2864 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002865 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002866 pidString = pidString + pid.toString() + ", ";
2867 }
2868 pw.println(pidString);
2869 }
2870 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002871 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002872
2873 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002874 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002875 for (Object requester : mFeatureUsers) {
2876 pw.println(requester.toString());
2877 }
2878 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002879 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002880
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002881 synchronized (this) {
2882 pw.println("NetworkTranstionWakeLock is currently " +
2883 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2884 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2885 }
2886 pw.println();
2887
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002888 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002889
2890 if (mInetLog != null) {
2891 pw.println();
2892 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002893 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002894 for(int i = 0; i < mInetLog.size(); i++) {
2895 pw.println(mInetLog.get(i));
2896 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002897 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002898 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002899 }
2900
Robert Greenwalt2034b912009-08-12 16:08:25 -07002901 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002902 private class NetworkStateTrackerHandler extends Handler {
2903 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002904 super(looper);
2905 }
2906
The Android Open Source Project28527d22009-03-03 19:31:44 -08002907 @Override
2908 public void handleMessage(Message msg) {
2909 NetworkInfo info;
2910 switch (msg.what) {
Wink Saville89c87b92013-08-29 08:55:16 -07002911 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002912 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002913 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002914
Wink Savillea7d56572011-09-21 11:05:43 -07002915 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville860f5282013-09-05 12:02:25 -07002916 (state == NetworkInfo.State.DISCONNECTED) ||
2917 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002918 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002919 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002920 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002921 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002922
Wink Saville89c87b92013-08-29 08:55:16 -07002923 // Since mobile has the notion of a network/apn that can be used for
2924 // provisioning we need to check every time we're connected as
2925 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2926 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2927 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2928 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2929 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Saville9564f2b2013-07-16 17:16:37 -07002930 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2931 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleab773a72013-09-14 09:04:53 -07002932 && (((state == NetworkInfo.State.CONNECTED)
2933 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2934 || info.isConnectedToProvisioningNetwork())) {
2935 log("ConnectivityChange checkMobileProvisioning for"
2936 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville89c87b92013-08-29 08:55:16 -07002937 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Saville9564f2b2013-07-16 17:16:37 -07002938 }
2939
Jeff Sharkeybde32692012-11-09 15:57:02 -08002940 EventLogTags.writeConnectivityStateChanged(
2941 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002942
2943 if (info.getDetailedState() ==
2944 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002945 handleConnectionFailure(info);
Wink Saville860f5282013-09-05 12:02:25 -07002946 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002947 /**
2948 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2949 * for now its an in between network, its a network that
2950 * is actually a default network but we don't want it to be
2951 * announced as such to keep background applications from
2952 * trying to use it. It turns out that some still try so we
2953 * take the additional step of clearing any default routes
2954 * to the link that may have incorrectly setup by the lower
2955 * levels.
2956 */
2957 LinkProperties lp = getLinkProperties(info.getType());
2958 if (DBG) {
2959 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2960 }
2961
2962 // Clear any default routes setup by the radio so
2963 // any activity by applications trying to use this
2964 // connection will fail until the provisioning network
2965 // is enabled.
2966 for (RouteInfo r : lp.getRoutes()) {
2967 removeRoute(lp, r, TO_DEFAULT_TABLE);
2968 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002969 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002970 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002971 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002972 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002973 // the logic here is, handle SUSPENDED the same as
2974 // DISCONNECTED. The only difference being we are
2975 // broadcasting an intent with NetworkInfo that's
2976 // suspended. This allows the applications an
2977 // opportunity to handle DISCONNECTED and SUSPENDED
2978 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002979 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002980 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002981 handleConnect(info);
2982 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002983 if (mLockdownTracker != null) {
2984 mLockdownTracker.onNetworkInfoChanged(info);
2985 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002986 break;
Wink Saville89c87b92013-08-29 08:55:16 -07002987 }
2988 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002989 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002990 // TODO: Temporary allowing network configuration
2991 // change not resetting sockets.
2992 // @see bug/4455071
2993 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002994 break;
Wink Saville89c87b92013-08-29 08:55:16 -07002995 }
2996 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07002997 info = (NetworkInfo) msg.obj;
Wink Saville89c87b92013-08-29 08:55:16 -07002998 int type = info.getType();
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07002999 updateNetworkSettings(mNetTrackers[type]);
3000 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003001 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003002 }
3003 }
3004 }
3005
3006 private class InternalHandler extends Handler {
3007 public InternalHandler(Looper looper) {
3008 super(looper);
3009 }
3010
3011 @Override
3012 public void handleMessage(Message msg) {
3013 NetworkInfo info;
3014 switch (msg.what) {
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003015 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003016 String causedBy = null;
3017 synchronized (ConnectivityService.this) {
3018 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3019 mNetTransitionWakeLock.isHeld()) {
3020 mNetTransitionWakeLock.release();
3021 causedBy = mNetTransitionWakeLockCausedBy;
3022 }
3023 }
3024 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003025 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003026 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003027 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003028 }
3029 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003030 FeatureUser u = (FeatureUser)msg.obj;
3031 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003032 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003033 }
3034 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003035 int netType = msg.arg1;
3036 int condition = msg.arg2;
3037 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003038 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003039 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003040 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003041 int netType = msg.arg1;
3042 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00003043 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003044 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003045 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003046 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003047 int preference = msg.arg1;
3048 handleSetNetworkPreference(preference);
3049 break;
3050 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003051 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003052 boolean enabled = (msg.arg1 == ENABLED);
3053 handleSetMobileData(enabled);
3054 break;
3055 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003056 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003057 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003058 break;
3059 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003060 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003061 boolean met = (msg.arg1 == ENABLED);
3062 handleSetDependencyMet(msg.arg2, met);
3063 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003064 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003065 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003066 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003067 sendStickyBroadcast(intent);
3068 break;
3069 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003070 case EVENT_SET_POLICY_DATA_ENABLE: {
3071 final int networkType = msg.arg1;
3072 final boolean enabled = msg.arg2 == ENABLED;
3073 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003074 break;
3075 }
3076 case EVENT_VPN_STATE_CHANGED: {
3077 if (mLockdownTracker != null) {
3078 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3079 }
3080 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003081 }
Wink Saville690cb182013-06-29 21:10:57 -07003082 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3083 int tag = mEnableFailFastMobileDataTag.get();
3084 if (msg.arg1 == tag) {
3085 MobileDataStateTracker mobileDst =
3086 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3087 if (mobileDst != null) {
3088 mobileDst.setEnableFailFastMobileData(msg.arg2);
3089 }
3090 } else {
3091 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3092 + " != tag:" + tag);
3093 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003094 break;
Wink Saville690cb182013-06-29 21:10:57 -07003095 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003096 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07003097 handleNetworkSamplingTimeout();
3098 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003099 }
Jason Monk445cea82013-10-10 14:02:51 -04003100 case EVENT_PROXY_HAS_CHANGED: {
3101 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3102 break;
3103 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003104 }
3105 }
3106 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003107
3108 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003109 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003110 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003111
3112 if (isTetheringSupported()) {
3113 return mTethering.tether(iface);
3114 } else {
3115 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3116 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003117 }
3118
3119 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003120 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003121 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003122
3123 if (isTetheringSupported()) {
3124 return mTethering.untether(iface);
3125 } else {
3126 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3127 }
3128 }
3129
3130 // javadoc from interface
3131 public int getLastTetherError(String iface) {
3132 enforceTetherAccessPermission();
3133
3134 if (isTetheringSupported()) {
3135 return mTethering.getLastTetherError(iface);
3136 } else {
3137 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3138 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003139 }
3140
3141 // TODO - proper iface API for selection by property, inspection, etc
3142 public String[] getTetherableUsbRegexs() {
3143 enforceTetherAccessPermission();
3144 if (isTetheringSupported()) {
3145 return mTethering.getTetherableUsbRegexs();
3146 } else {
3147 return new String[0];
3148 }
3149 }
3150
3151 public String[] getTetherableWifiRegexs() {
3152 enforceTetherAccessPermission();
3153 if (isTetheringSupported()) {
3154 return mTethering.getTetherableWifiRegexs();
3155 } else {
3156 return new String[0];
3157 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003158 }
3159
Danica Chang96567052010-08-11 14:54:43 -07003160 public String[] getTetherableBluetoothRegexs() {
3161 enforceTetherAccessPermission();
3162 if (isTetheringSupported()) {
3163 return mTethering.getTetherableBluetoothRegexs();
3164 } else {
3165 return new String[0];
3166 }
3167 }
3168
Mike Lockwooded4a1742011-07-19 13:04:47 -07003169 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08003170 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003171 if (isTetheringSupported()) {
3172 return mTethering.setUsbTethering(enable);
3173 } else {
3174 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3175 }
3176 }
3177
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003178 // TODO - move iface listing, queries, etc to new module
3179 // javadoc from interface
3180 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003181 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003182 return mTethering.getTetherableIfaces();
3183 }
3184
3185 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003186 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003187 return mTethering.getTetheredIfaces();
3188 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003189
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003190 public String[] getTetheringErroredIfaces() {
3191 enforceTetherAccessPermission();
3192 return mTethering.getErroredIfaces();
3193 }
3194
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003195 // if ro.tether.denied = true we default to no tethering
3196 // gservices could set the secure setting to 1 though to enable it on a build where it
3197 // had previously been turned off.
3198 public boolean isTetheringSupported() {
3199 enforceTetherAccessPermission();
3200 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003201 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3202 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003203 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3204 mTethering.getTetherableWifiRegexs().length != 0 ||
3205 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3206 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003207 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003208
3209 // An API NetworkStateTrackers can call when they lose their network.
3210 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3211 // whichever happens first. The timer is started by the first caller and not
3212 // restarted by subsequent callers.
3213 public void requestNetworkTransitionWakelock(String forWhom) {
3214 enforceConnectivityInternalPermission();
3215 synchronized (this) {
3216 if (mNetTransitionWakeLock.isHeld()) return;
3217 mNetTransitionWakeLockSerialNumber++;
3218 mNetTransitionWakeLock.acquire();
3219 mNetTransitionWakeLockCausedBy = forWhom;
3220 }
3221 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003222 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003223 mNetTransitionWakeLockSerialNumber, 0),
3224 mNetTransitionWakeLockTimeout);
3225 return;
3226 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003227
Robert Greenwalt986c7412010-09-08 15:24:47 -07003228 // 100 percent is full good, 0 is full bad.
3229 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003230 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003231 mContext.enforceCallingOrSelfPermission(
3232 android.Manifest.permission.STATUS_BAR,
3233 "ConnectivityService");
3234
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003235 if (DBG) {
3236 int pid = getCallingPid();
3237 int uid = getCallingUid();
3238 String s = pid + "(" + uid + ") reports inet is " +
3239 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3240 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3241 mInetLog.add(s);
3242 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3243 mInetLog.remove(0);
3244 }
3245 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003246 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003247 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3248 }
3249
3250 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003251 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003252 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003253 return;
3254 }
3255 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003256 if (DBG) log("handleInetConditionChange: net=" + netType +
3257 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003258 return;
3259 }
Wink Savillea7d56572011-09-21 11:05:43 -07003260 if (VDBG) {
3261 log("handleInetConditionChange: net=" +
3262 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003263 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003264 }
Wink Saville3e866722013-01-31 00:30:13 +00003265 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003266 int delay;
3267 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003268 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003269 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003270 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003271 delay = Settings.Global.getInt(mContext.getContentResolver(),
3272 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003273 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003274 delay = Settings.Global.getInt(mContext.getContentResolver(),
3275 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003276 }
3277 mInetConditionChangeInFlight = true;
3278 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003279 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003280 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003281 // we've set the new condition, when this hold ends that will get picked up
3282 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003283 }
3284 }
3285
Wink Saville3e866722013-01-31 00:30:13 +00003286 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003287 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003288 log("handleInetConditionHoldEnd: net=" + netType +
3289 ", condition=" + mDefaultInetCondition +
3290 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003291 }
3292 mInetConditionChangeInFlight = false;
3293
3294 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003295 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003296 return;
3297 }
3298 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003299 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003300 return;
3301 }
Wink Saville3e866722013-01-31 00:30:13 +00003302 // TODO: Figure out why this optimization sometimes causes a
3303 // change in mDefaultInetCondition to be missed and the
3304 // UI to not be updated.
3305 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3306 // if (DBG) log("no change in condition - aborting");
3307 // return;
3308 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003309 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3310 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003311 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003312 return;
3313 }
Wink Saville3e866722013-01-31 00:30:13 +00003314 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003315 sendInetConditionBroadcast(networkInfo);
3316 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003317 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003318
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003319 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003320 // this information is already available as a world read/writable jvm property
3321 // so this API change wouldn't have a benifit. It also breaks the passing
3322 // of proxy info to all the JVMs.
3323 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003324 synchronized (mProxyLock) {
Jason Monk43324ee2013-07-03 17:04:33 -04003325 ProxyProperties ret = mGlobalProxy;
3326 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3327 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003328 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003329 }
3330
3331 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003332 enforceConnectivityInternalPermission();
Jason Monk43324ee2013-07-03 17:04:33 -04003333
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003334 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003335 if (proxyProperties == mGlobalProxy) return;
3336 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3337 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3338
3339 String host = "";
3340 int port = 0;
3341 String exclList = "";
Jason Monk43324ee2013-07-03 17:04:33 -04003342 String pacFileUrl = "";
3343 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3344 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003345 mGlobalProxy = new ProxyProperties(proxyProperties);
3346 host = mGlobalProxy.getHost();
3347 port = mGlobalProxy.getPort();
3348 exclList = mGlobalProxy.getExclusionList();
Jason Monk43324ee2013-07-03 17:04:33 -04003349 if (proxyProperties.getPacFileUrl() != null) {
3350 pacFileUrl = proxyProperties.getPacFileUrl();
3351 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003352 } else {
3353 mGlobalProxy = null;
3354 }
3355 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003356 final long token = Binder.clearCallingIdentity();
3357 try {
3358 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3359 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3360 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3361 exclList);
Jason Monk43324ee2013-07-03 17:04:33 -04003362 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003363 } finally {
3364 Binder.restoreCallingIdentity(token);
3365 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003366 }
3367
3368 if (mGlobalProxy == null) {
3369 proxyProperties = mDefaultProxy;
3370 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003371 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003372 }
3373
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003374 private void loadGlobalProxy() {
3375 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003376 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3377 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3378 String exclList = Settings.Global.getString(res,
3379 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk43324ee2013-07-03 17:04:33 -04003380 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3381 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3382 ProxyProperties proxyProperties;
3383 if (!TextUtils.isEmpty(pacFileUrl)) {
3384 proxyProperties = new ProxyProperties(pacFileUrl);
3385 } else {
3386 proxyProperties = new ProxyProperties(host, port, exclList);
3387 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003388 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003389 mGlobalProxy = proxyProperties;
3390 }
3391 }
3392 }
3393
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003394 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003395 // this information is already available as a world read/writable jvm property
3396 // so this API change wouldn't have a benifit. It also breaks the passing
3397 // of proxy info to all the JVMs.
3398 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003399 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003400 return mGlobalProxy;
3401 }
3402 }
3403
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003404 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04003405 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3406 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003407 proxy = null;
3408 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003409 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003410 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003411 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003412 mDefaultProxy = proxy;
3413
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003414 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003415 if (!mDefaultProxyDisabled) {
3416 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003417 }
3418 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003419 }
3420
3421 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003422 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3423 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003424 if (!TextUtils.isEmpty(proxy)) {
3425 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003426 if (data.length == 0) {
3427 return;
3428 }
3429
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003430 String proxyHost = data[0];
3431 int proxyPort = 8080;
3432 if (data.length > 1) {
3433 try {
3434 proxyPort = Integer.parseInt(data[1]);
3435 } catch (NumberFormatException e) {
3436 return;
3437 }
3438 }
3439 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3440 setGlobalProxy(p);
3441 }
3442 }
3443
3444 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003445 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monkaf9ded02013-08-23 19:21:25 -04003446 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003447 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003448 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003449 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3450 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003451 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003452 final long ident = Binder.clearCallingIdentity();
3453 try {
3454 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3455 } finally {
3456 Binder.restoreCallingIdentity(ident);
3457 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003458 }
3459
3460 private static class SettingsObserver extends ContentObserver {
3461 private int mWhat;
3462 private Handler mHandler;
3463 SettingsObserver(Handler handler, int what) {
3464 super(handler);
3465 mHandler = handler;
3466 mWhat = what;
3467 }
3468
3469 void observe(Context context) {
3470 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003471 resolver.registerContentObserver(Settings.Global.getUriFor(
3472 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003473 }
3474
3475 @Override
3476 public void onChange(boolean selfChange) {
3477 mHandler.obtainMessage(mWhat).sendToTarget();
3478 }
3479 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003480
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003481 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003482 Slog.d(TAG, s);
3483 }
3484
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003485 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003486 Slog.e(TAG, s);
3487 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003488
repo syncf5de5572011-07-29 23:55:49 -07003489 int convertFeatureToNetworkType(int networkType, String feature) {
3490 int usedNetworkType = networkType;
3491
3492 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3493 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3494 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3495 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3496 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3497 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3498 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3499 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3500 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3501 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3502 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3503 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3504 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3505 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3506 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3507 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3508 } else {
3509 Slog.e(TAG, "Can't match any mobile netTracker!");
3510 }
3511 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3512 if (TextUtils.equals(feature, "p2p")) {
3513 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3514 } else {
3515 Slog.e(TAG, "Can't match any wifi netTracker!");
3516 }
3517 } else {
3518 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003519 }
repo syncf5de5572011-07-29 23:55:49 -07003520 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003521 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003522
3523 private static <T> T checkNotNull(T value, String message) {
3524 if (value == null) {
3525 throw new NullPointerException(message);
3526 }
3527 return value;
3528 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003529
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003530 /**
3531 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003532 * VpnBuilder and not available in ConnectivityManager. Permissions
3533 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003534 * @hide
3535 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003536 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003537 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003538 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003539 try {
3540 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003541 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003542 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003543 synchronized(mVpns) {
3544 mVpns.get(user).protect(socket,
3545 mNetTrackers[type].getLinkProperties().getInterfaceName());
3546 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003547 return true;
3548 }
3549 } catch (Exception e) {
3550 // ignore
3551 } finally {
3552 try {
3553 socket.close();
3554 } catch (Exception e) {
3555 // ignore
3556 }
3557 }
3558 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003559 }
3560
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003561 /**
3562 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003563 * and not available in ConnectivityManager. Permissions are checked
3564 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003565 * @hide
3566 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003567 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003568 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003569 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003570 int user = UserHandle.getUserId(Binder.getCallingUid());
3571 synchronized(mVpns) {
3572 return mVpns.get(user).prepare(oldPackage, newPackage);
3573 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003574 }
3575
Chad Brubaker31de0b62013-07-11 13:29:30 -07003576 @Override
3577 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3578 enforceMarkNetworkSocketPermission();
3579 final long token = Binder.clearCallingIdentity();
3580 try {
3581 int mark = mNetd.getMarkForUid(uid);
3582 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3583 if (mark == -1) {
3584 mark = 0;
3585 }
3586 NetworkUtils.markSocket(socket.getFd(), mark);
3587 } catch (RemoteException e) {
3588 } finally {
3589 Binder.restoreCallingIdentity(token);
3590 }
3591 }
3592
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003593 /**
3594 * Configure a TUN interface and return its file descriptor. Parameters
3595 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003596 * and not available in ConnectivityManager. Permissions are checked in
3597 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003598 * @hide
3599 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003600 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003601 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003602 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003603 int user = UserHandle.getUserId(Binder.getCallingUid());
3604 synchronized(mVpns) {
3605 return mVpns.get(user).establish(config);
3606 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003607 }
3608
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003609 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003610 * Start legacy VPN, controlling native daemons as needed. Creates a
3611 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003612 */
3613 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003614 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003615 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003616 final LinkProperties egress = getActiveLinkProperties();
3617 if (egress == null) {
3618 throw new IllegalStateException("Missing active network connection");
3619 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003620 int user = UserHandle.getUserId(Binder.getCallingUid());
3621 synchronized(mVpns) {
3622 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3623 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003624 }
3625
3626 /**
3627 * Return the information of the ongoing legacy VPN. This method is used
3628 * by VpnSettings and not available in ConnectivityManager. Permissions
3629 * are checked in Vpn class.
3630 * @hide
3631 */
3632 @Override
3633 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003634 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003635 int user = UserHandle.getUserId(Binder.getCallingUid());
3636 synchronized(mVpns) {
3637 return mVpns.get(user).getLegacyVpnInfo();
3638 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003639 }
3640
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003641 /**
Chad Brubaker7dcfa2a2013-07-16 18:59:12 -07003642 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3643 * not available in ConnectivityManager.
3644 * Permissions are checked in Vpn class.
3645 * @hide
3646 */
3647 @Override
3648 public VpnConfig getVpnConfig() {
3649 int user = UserHandle.getUserId(Binder.getCallingUid());
3650 synchronized(mVpns) {
3651 return mVpns.get(user).getVpnConfig();
3652 }
3653 }
3654
3655 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003656 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3657 * through NetworkStateTracker since it works differently. For example, it
3658 * needs to override DNS servers but never takes the default routes. It
3659 * relies on another data network, and it could keep existing connections
3660 * alive after reconnecting, switching between networks, or even resuming
3661 * from deep sleep. Calls from applications should be done synchronously
3662 * to avoid race conditions. As these are all hidden APIs, refactoring can
3663 * be done whenever a better abstraction is developed.
3664 */
3665 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003666 private VpnCallback() {
3667 }
3668
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003669 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003670 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003671 }
3672
Chad Brubakerccae0d32013-06-14 11:16:51 -07003673 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003674 if (dnsServers == null) {
3675 restore();
3676 return;
3677 }
3678
3679 // Convert DNS servers into addresses.
3680 List<InetAddress> addresses = new ArrayList<InetAddress>();
3681 for (String address : dnsServers) {
3682 // Double check the addresses and remove invalid ones.
3683 try {
3684 addresses.add(InetAddress.parseNumericAddress(address));
3685 } catch (Exception e) {
3686 // ignore
3687 }
3688 }
3689 if (addresses.isEmpty()) {
3690 restore();
3691 return;
3692 }
3693
3694 // Concatenate search domains into a string.
3695 StringBuilder buffer = new StringBuilder();
3696 if (searchDomains != null) {
3697 for (String domain : searchDomains) {
3698 buffer.append(domain).append(' ');
3699 }
3700 }
3701 String domains = buffer.toString().trim();
3702
3703 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003704 synchronized (mDnsLock) {
Chad Brubaker45e721f2013-07-23 17:13:36 -07003705 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003706 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003707
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003708 // Temporarily disable the default proxy (not global).
3709 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003710 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003711 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003712 sendProxyBroadcast(null);
3713 }
3714 }
3715
3716 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003717 }
3718
Chia-chi Yehcc844502011-07-14 18:01:57 -07003719 public void restore() {
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003720 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003721 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003722 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003723 sendProxyBroadcast(mDefaultProxy);
3724 }
3725 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003726 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003727
3728 public void protect(ParcelFileDescriptor socket) {
3729 try {
3730 final int mark = mNetd.getMarkForProtect();
3731 NetworkUtils.markSocket(socket.getFd(), mark);
3732 } catch (RemoteException e) {
3733 }
3734 }
3735
3736 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3737 for (RouteInfo route : routes) {
3738 try {
3739 mNetd.setMarkedForwardingRoute(interfaze, route);
3740 } catch (RemoteException e) {
3741 }
3742 }
3743 }
3744
3745 public void setMarkedForwarding(String interfaze) {
3746 try {
3747 mNetd.setMarkedForwarding(interfaze);
3748 } catch (RemoteException e) {
3749 }
3750 }
3751
3752 public void clearMarkedForwarding(String interfaze) {
3753 try {
3754 mNetd.clearMarkedForwarding(interfaze);
3755 } catch (RemoteException e) {
3756 }
3757 }
3758
Robert Greenwalt68534c82013-09-24 11:05:57 -07003759 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003760 int uidStart = uid * UserHandle.PER_USER_RANGE;
3761 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003762 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003763 }
3764
Robert Greenwalt68534c82013-09-24 11:05:57 -07003765 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003766 int uidStart = uid * UserHandle.PER_USER_RANGE;
3767 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003768 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003769 }
3770
Robert Greenwalt68534c82013-09-24 11:05:57 -07003771 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3772 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003773 try {
3774 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003775 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003776 } catch (RemoteException e) {
3777 }
3778
3779 }
3780
Robert Greenwalt68534c82013-09-24 11:05:57 -07003781 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3782 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003783 try {
3784 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003785 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003786 } catch (RemoteException e) {
3787 }
3788
3789 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003790 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003791
3792 @Override
3793 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003794 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3795 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3796 return false;
3797 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003798
3799 // Tear down existing lockdown if profile was removed
3800 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3801 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003802 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003803 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3804 return false;
3805 }
3806
3807 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3808 final VpnProfile profile = VpnProfile.decode(
3809 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerccae0d32013-06-14 11:16:51 -07003810 int user = UserHandle.getUserId(Binder.getCallingUid());
3811 synchronized(mVpns) {
3812 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3813 profile));
3814 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003815 } else {
3816 setLockdownTracker(null);
3817 }
3818
3819 return true;
3820 }
3821
3822 /**
3823 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3824 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3825 */
3826 private void setLockdownTracker(LockdownVpnTracker tracker) {
3827 // Shutdown any existing tracker
3828 final LockdownVpnTracker existing = mLockdownTracker;
3829 mLockdownTracker = null;
3830 if (existing != null) {
3831 existing.shutdown();
3832 }
3833
3834 try {
3835 if (tracker != null) {
3836 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003837 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003838 mLockdownTracker = tracker;
3839 mLockdownTracker.init();
3840 } else {
3841 mNetd.setFirewallEnabled(false);
3842 }
3843 } catch (RemoteException e) {
3844 // ignored; NMS lives inside system_server
3845 }
3846 }
3847
3848 private void throwIfLockdownEnabled() {
3849 if (mLockdownEnabled) {
3850 throw new IllegalStateException("Unavailable in lockdown mode");
3851 }
3852 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003853
3854 public void supplyMessenger(int networkType, Messenger messenger) {
3855 enforceConnectivityInternalPermission();
3856
3857 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3858 mNetTrackers[networkType].supplyMessenger(messenger);
3859 }
3860 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003861
3862 public int findConnectionTypeForIface(String iface) {
3863 enforceConnectivityInternalPermission();
3864
3865 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3866 for (NetworkStateTracker tracker : mNetTrackers) {
3867 if (tracker != null) {
3868 LinkProperties lp = tracker.getLinkProperties();
3869 if (lp != null && iface.equals(lp.getInterfaceName())) {
3870 return tracker.getNetworkInfo().getType();
3871 }
3872 }
3873 }
3874 return ConnectivityManager.TYPE_NONE;
3875 }
Wink Saville690cb182013-06-29 21:10:57 -07003876
3877 /**
3878 * Have mobile data fail fast if enabled.
3879 *
3880 * @param enabled DctConstants.ENABLED/DISABLED
3881 */
3882 private void setEnableFailFastMobileData(int enabled) {
3883 int tag;
3884
3885 if (enabled == DctConstants.ENABLED) {
3886 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3887 } else {
3888 tag = mEnableFailFastMobileDataTag.get();
3889 }
3890 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3891 enabled));
3892 }
3893
Wink Savillebc588402013-08-16 17:17:28 -07003894 private boolean isMobileDataStateTrackerReady() {
3895 MobileDataStateTracker mdst =
Wink Saville89c87b92013-08-29 08:55:16 -07003896 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savillebc588402013-08-16 17:17:28 -07003897 return (mdst != null) && (mdst.isReady());
3898 }
3899
Wink Saville89c87b92013-08-29 08:55:16 -07003900 /**
3901 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3902 */
3903
3904 /**
3905 * No connection was possible to the network.
Wink Savillea3041492013-09-06 09:53:08 -07003906 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003907 */
Wink Savillea3041492013-09-06 09:53:08 -07003908 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville89c87b92013-08-29 08:55:16 -07003909
3910 /**
3911 * A connection was made to the internet, all is well.
Wink Savillea3041492013-09-06 09:53:08 -07003912 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003913 */
Wink Savillea3041492013-09-06 09:53:08 -07003914 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville89c87b92013-08-29 08:55:16 -07003915
3916 /**
3917 * A connection was made but no dns server was available to resolve a name to address.
Wink Savillea3041492013-09-06 09:53:08 -07003918 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003919 */
Wink Savillea3041492013-09-06 09:53:08 -07003920 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville89c87b92013-08-29 08:55:16 -07003921
3922 /**
3923 * A connection was made but could not open a TCP connection.
Wink Savillea3041492013-09-06 09:53:08 -07003924 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003925 */
Wink Savillea3041492013-09-06 09:53:08 -07003926 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3927
3928 /**
3929 * A connection was made but there was a redirection, we appear to be in walled garden.
3930 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3931 */
3932 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville89c87b92013-08-29 08:55:16 -07003933
3934 /**
3935 * The mobile network is a provisioning network.
Wink Savillea3041492013-09-06 09:53:08 -07003936 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville89c87b92013-08-29 08:55:16 -07003937 */
Wink Savillea3041492013-09-06 09:53:08 -07003938 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville89c87b92013-08-29 08:55:16 -07003939
Wink Savillea3041492013-09-06 09:53:08 -07003940 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville89c87b92013-08-29 08:55:16 -07003941
Wink Saville690cb182013-06-29 21:10:57 -07003942 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07003943 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3944 int timeOutMs = -1;
3945 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3946 enforceConnectivityInternalPermission();
Wink Savillefdb84862013-07-02 10:55:14 -07003947
Wink Saville690cb182013-06-29 21:10:57 -07003948 final long token = Binder.clearCallingIdentity();
3949 try {
Wink Saville89c87b92013-08-29 08:55:16 -07003950 timeOutMs = suggestedTimeOutMs;
3951 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3952 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3953 }
3954
3955 // Check that mobile networks are supported
3956 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3957 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3958 if (DBG) log("checkMobileProvisioning: X no mobile network");
3959 return timeOutMs;
3960 }
3961
3962 // If we're already checking don't do it again
3963 // TODO: Add a queue of results...
3964 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3965 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3966 return timeOutMs;
3967 }
3968
Wink Savillea65f4732013-10-03 08:34:46 -07003969 // Start off with mobile notification off
3970 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07003971
Wink Saville690cb182013-06-29 21:10:57 -07003972 CheckMp checkMp = new CheckMp(mContext, this);
3973 CheckMp.CallBack cb = new CheckMp.CallBack() {
3974 @Override
3975 void onComplete(Integer result) {
Wink Saville89c87b92013-08-29 08:55:16 -07003976 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07003977 NetworkInfo ni =
3978 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3979 switch(result) {
Wink Saville89c87b92013-08-29 08:55:16 -07003980 case CMP_RESULT_CODE_CONNECTABLE:
Wink Savillea3041492013-09-06 09:53:08 -07003981 case CMP_RESULT_CODE_NO_CONNECTION:
3982 case CMP_RESULT_CODE_NO_DNS:
3983 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville89c87b92013-08-29 08:55:16 -07003984 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville690cb182013-06-29 21:10:57 -07003985 break;
3986 }
Wink Saville89c87b92013-08-29 08:55:16 -07003987 case CMP_RESULT_CODE_REDIRECTED: {
3988 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07003989 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07003990 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07003991 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07003992 }
3993 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07003994 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07003995 setProvNotificationVisible(true,
3996 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07003997 url);
Wink Saville690cb182013-06-29 21:10:57 -07003998 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07003999 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004000 }
4001 break;
4002 }
Wink Savillea3041492013-09-06 09:53:08 -07004003 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004004 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004005 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004006 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004007 setProvNotificationVisible(true,
4008 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004009 url);
Wink Saville690cb182013-06-29 21:10:57 -07004010 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004011 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004012 }
4013 break;
4014 }
4015 default: {
4016 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4017 break;
4018 }
4019 }
Wink Saville89c87b92013-08-29 08:55:16 -07004020 mIsCheckingMobileProvisioning.set(false);
Wink Saville690cb182013-06-29 21:10:57 -07004021 }
4022 };
4023 CheckMp.Params params =
4024 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville89c87b92013-08-29 08:55:16 -07004025 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville690cb182013-06-29 21:10:57 -07004026 checkMp.execute(params);
4027 } finally {
4028 Binder.restoreCallingIdentity(token);
Wink Saville89c87b92013-08-29 08:55:16 -07004029 if (DBG) log("checkMobileProvisioning: X");
Wink Saville690cb182013-06-29 21:10:57 -07004030 }
4031 return timeOutMs;
4032 }
4033
4034 static class CheckMp extends
4035 AsyncTask<CheckMp.Params, Void, Integer> {
4036 private static final String CHECKMP_TAG = "CheckMp";
4037 public static final int MAX_TIMEOUT_MS = 60000;
4038 private static final int SOCKET_TIMEOUT_MS = 5000;
4039 private Context mContext;
4040 private ConnectivityService mCs;
4041 private TelephonyManager mTm;
4042 private Params mParams;
4043
4044 /**
4045 * Parameters for AsyncTask.execute
4046 */
4047 static class Params {
4048 private String mUrl;
4049 private long mTimeOutMs;
4050 private CallBack mCb;
4051
4052 Params(String url, long timeOutMs, CallBack cb) {
4053 mUrl = url;
4054 mTimeOutMs = timeOutMs;
4055 mCb = cb;
4056 }
4057
4058 @Override
4059 public String toString() {
4060 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4061 }
4062 }
4063
4064 /**
4065 * The call back object passed in Params. onComplete will be called
4066 * on the main thread.
4067 */
4068 abstract static class CallBack {
4069 // Called on the main thread.
4070 abstract void onComplete(Integer result);
4071 }
4072
4073 public CheckMp(Context context, ConnectivityService cs) {
4074 mContext = context;
4075 mCs = cs;
4076
4077 // Setup access to TelephonyService we'll be using.
4078 mTm = (TelephonyManager) mContext.getSystemService(
4079 Context.TELEPHONY_SERVICE);
4080 }
4081
4082 /**
4083 * Get the default url to use for the test.
4084 */
4085 public String getDefaultUrl() {
4086 // See http://go/clientsdns for usage approval
4087 String server = Settings.Global.getString(mContext.getContentResolver(),
4088 Settings.Global.CAPTIVE_PORTAL_SERVER);
4089 if (server == null) {
4090 server = "clients3.google.com";
4091 }
4092 return "http://" + server + "/generate_204";
4093 }
4094
4095 /**
4096 * Detect if its possible to connect to the http url. DNS based detection techniques
4097 * do not work at all hotspots. The best way to check is to perform a request to
4098 * a known address that fetches the data we expect.
4099 */
4100 private synchronized Integer isMobileOk(Params params) {
Wink Saville89c87b92013-08-29 08:55:16 -07004101 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004102 Uri orgUri = Uri.parse(params.mUrl);
4103 Random rand = new Random();
4104 mParams = params;
4105
Wink Saville37e73122013-08-13 12:41:06 -07004106 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004107 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville39856712013-09-13 12:40:11 -07004108 log("isMobileOk: X not mobile capable result=" + result);
4109 return result;
4110 }
4111
4112 // See if we've already determined we've got a provisioning connection,
4113 // if so we don't need to do anything active.
4114 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4115 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4116 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4117 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4118
4119 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4120 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4121 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4122 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4123
4124 if (isDefaultProvisioning || isHipriProvisioning) {
4125 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4126 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville37e73122013-08-13 12:41:06 -07004127 return result;
4128 }
Wink Saville690cb182013-06-29 21:10:57 -07004129
Wink Saville37e73122013-08-13 12:41:06 -07004130 try {
Wink Saville690cb182013-06-29 21:10:57 -07004131 // Continue trying to connect until time has run out
4132 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville4a165bb2013-08-07 11:02:57 -07004133
Wink Savillebc588402013-08-16 17:17:28 -07004134 if (!mCs.isMobileDataStateTrackerReady()) {
4135 // Wait for MobileDataStateTracker to be ready.
4136 if (DBG) log("isMobileOk: mdst is not ready");
4137 while(SystemClock.elapsedRealtime() < endTime) {
4138 if (mCs.isMobileDataStateTrackerReady()) {
4139 // Enable fail fast as we'll do retries here and use a
4140 // hipri connection so the default connection stays active.
4141 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4142 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4143 break;
4144 }
4145 sleep(1);
4146 }
4147 }
4148
4149 log("isMobileOk: start hipri url=" + params.mUrl);
4150
Wink Saville4a165bb2013-08-07 11:02:57 -07004151 // First wait until we can start using hipri
4152 Binder binder = new Binder();
4153 while(SystemClock.elapsedRealtime() < endTime) {
4154 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4155 Phone.FEATURE_ENABLE_HIPRI, binder);
4156 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4157 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4158 log("isMobileOk: hipri started");
4159 break;
4160 }
4161 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville89c87b92013-08-29 08:55:16 -07004162 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville4a165bb2013-08-07 11:02:57 -07004163 sleep(1);
4164 }
4165
4166 // Continue trying to connect until time has run out
Wink Saville690cb182013-06-29 21:10:57 -07004167 while(SystemClock.elapsedRealtime() < endTime) {
4168 try {
4169 // Wait for hipri to connect.
4170 // TODO: Don't poll and handle situation where hipri fails
4171 // because default is retrying. See b/9569540
4172 NetworkInfo.State state = mCs
4173 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4174 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville89c87b92013-08-29 08:55:16 -07004175 if (true/*VDBG*/) {
Wink Saville27f92732013-07-31 15:49:04 -07004176 log("isMobileOk: not connected ni=" +
Wink Saville690cb182013-06-29 21:10:57 -07004177 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville27f92732013-07-31 15:49:04 -07004178 }
Wink Saville690cb182013-06-29 21:10:57 -07004179 sleep(1);
Wink Saville89c87b92013-08-29 08:55:16 -07004180 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004181 continue;
4182 }
4183
Wink Saville89c87b92013-08-29 08:55:16 -07004184 // Hipri has started check if this is a provisioning url
4185 MobileDataStateTracker mdst = (MobileDataStateTracker)
4186 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4187 if (mdst.isProvisioningNetwork()) {
Wink Savillea3041492013-09-06 09:53:08 -07004188 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville39856712013-09-13 12:40:11 -07004189 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville89c87b92013-08-29 08:55:16 -07004190 return result;
4191 } else {
4192 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4193 }
4194
Wink Saville690cb182013-06-29 21:10:57 -07004195 // Get of the addresses associated with the url host. We need to use the
4196 // address otherwise HttpURLConnection object will use the name to get
4197 // the addresses and is will try every address but that will bypass the
4198 // route to host we setup and the connection could succeed as the default
4199 // interface might be connected to the internet via wifi or other interface.
4200 InetAddress[] addresses;
4201 try {
4202 addresses = InetAddress.getAllByName(orgUri.getHost());
4203 } catch (UnknownHostException e) {
Wink Saville89c87b92013-08-29 08:55:16 -07004204 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville39856712013-09-13 12:40:11 -07004205 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004206 return result;
4207 }
4208 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4209
4210 // Get the type of addresses supported by this link
4211 LinkProperties lp = mCs.getLinkProperties(
4212 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti662b96c2013-08-08 11:00:12 +09004213 boolean linkHasIpv4 = lp.hasIPv4Address();
4214 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville690cb182013-06-29 21:10:57 -07004215 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4216 + " linkHasIpv6=" + linkHasIpv6);
4217
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004218 final ArrayList<InetAddress> validAddresses =
4219 new ArrayList<InetAddress>(addresses.length);
Wink Saville690cb182013-06-29 21:10:57 -07004220
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004221 for (InetAddress addr : addresses) {
4222 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4223 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4224 validAddresses.add(addr);
Wink Saville690cb182013-06-29 21:10:57 -07004225 }
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004226 }
4227
4228 if (validAddresses.size() == 0) {
4229 return CMP_RESULT_CODE_NO_CONNECTION;
4230 }
4231
4232 int addrTried = 0;
4233 while (true) {
4234 // Loop through at most 3 valid addresses or until
4235 // we run out of time
4236 if (addrTried++ >= 3) {
4237 log("too many loops tried - giving up");
4238 break;
4239 }
4240 if (SystemClock.elapsedRealtime() >= endTime) {
4241 log("spend too much time - giving up");
4242 break;
4243 }
4244
4245 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4246 validAddresses.size()));
Wink Saville690cb182013-06-29 21:10:57 -07004247
4248 // Make a route to host so we check the specific interface.
4249 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4250 hostAddr.getAddress())) {
4251 // Wait a short time to be sure the route is established ??
4252 log("isMobileOk:"
4253 + " wait to establish route to hostAddr=" + hostAddr);
4254 sleep(3);
4255 } else {
4256 log("isMobileOk:"
4257 + " could not establish route to hostAddr=" + hostAddr);
4258 continue;
4259 }
4260
4261 // Rewrite the url to have numeric address to use the specific route.
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004262 // Add a pointless random query param to fool proxies into not caching.
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004263 URL newUrl = new URL(orgUri.getScheme(),
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004264 hostAddr.getHostAddress(),
4265 orgUri.getPath() + "?q=" + rand.nextInt(Integer.MAX_VALUE));
Wink Saville690cb182013-06-29 21:10:57 -07004266 log("isMobileOk: newUrl=" + newUrl);
4267
4268 HttpURLConnection urlConn = null;
4269 try {
4270 // Open the connection set the request header and get the response
4271 urlConn = (HttpURLConnection) newUrl.openConnection(
4272 java.net.Proxy.NO_PROXY);
4273 urlConn.setInstanceFollowRedirects(false);
4274 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4275 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4276 urlConn.setUseCaches(false);
4277 urlConn.setAllowUserInteraction(false);
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004278 // Set the "Connection" to "Close" as by default "Keep-Alive"
4279 // is used which is useless in this case.
Wink Saville690cb182013-06-29 21:10:57 -07004280 urlConn.setRequestProperty("Connection", "close");
4281 int responseCode = urlConn.getResponseCode();
Wink Savillea3041492013-09-06 09:53:08 -07004282
4283 // For debug display the headers
4284 Map<String, List<String>> headers = urlConn.getHeaderFields();
4285 log("isMobileOk: headers=" + headers);
4286
4287 // Close the connection
Wink Saville690cb182013-06-29 21:10:57 -07004288 urlConn.disconnect();
4289 urlConn = null;
Wink Savillea3041492013-09-06 09:53:08 -07004290
4291 if (responseCode == 204) {
4292 // Return
Wink Savillea3041492013-09-06 09:53:08 -07004293 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville39856712013-09-13 12:40:11 -07004294 log("isMobileOk: X expected responseCode=" + responseCode
4295 + " result=" + result);
Wink Savillea3041492013-09-06 09:53:08 -07004296 return result;
4297 } else {
4298 // Retry to be sure this was redirected, we've gotten
4299 // occasions where a server returned 200 even though
4300 // the device didn't have a "warm" sim.
4301 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004302 // TODO - it would be nice in the single-address case to do
4303 // another DNS resolve here, but flushing the cache is a bit
4304 // heavy-handed.
Wink Savillea3041492013-09-06 09:53:08 -07004305 result = CMP_RESULT_CODE_REDIRECTED;
4306 }
Wink Saville690cb182013-06-29 21:10:57 -07004307 } catch (Exception e) {
4308 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Savillea3041492013-09-06 09:53:08 -07004309 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004310 if (urlConn != null) {
4311 urlConn.disconnect();
4312 urlConn = null;
4313 }
4314 }
4315 }
Wink Saville39856712013-09-13 12:40:11 -07004316 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004317 return result;
4318 } catch (Exception e) {
4319 log("isMobileOk: Exception e=" + e);
4320 continue;
4321 }
4322 }
4323 log("isMobileOk: timed out");
4324 } finally {
4325 log("isMobileOk: F stop hipri");
4326 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4327 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4328 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville89c87b92013-08-29 08:55:16 -07004329
4330 // Wait for hipri to disconnect.
4331 long endTime = SystemClock.elapsedRealtime() + 5000;
4332
4333 while(SystemClock.elapsedRealtime() < endTime) {
4334 NetworkInfo.State state = mCs
4335 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4336 if (state != NetworkInfo.State.DISCONNECTED) {
4337 if (VDBG) {
4338 log("isMobileOk: connected ni=" +
4339 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4340 }
4341 sleep(1);
4342 continue;
4343 }
4344 }
4345
Wink Saville690cb182013-06-29 21:10:57 -07004346 log("isMobileOk: X result=" + result);
4347 }
4348 return result;
4349 }
4350
4351 @Override
4352 protected Integer doInBackground(Params... params) {
4353 return isMobileOk(params[0]);
4354 }
4355
4356 @Override
4357 protected void onPostExecute(Integer result) {
4358 log("onPostExecute: result=" + result);
4359 if ((mParams != null) && (mParams.mCb != null)) {
4360 mParams.mCb.onComplete(result);
4361 }
4362 }
4363
4364 private String inetAddressesToString(InetAddress[] addresses) {
4365 StringBuffer sb = new StringBuffer();
4366 boolean firstTime = true;
4367 for(InetAddress addr : addresses) {
4368 if (firstTime) {
4369 firstTime = false;
4370 } else {
4371 sb.append(",");
4372 }
4373 sb.append(addr);
4374 }
4375 return sb.toString();
4376 }
4377
4378 private void printNetworkInfo() {
4379 boolean hasIccCard = mTm.hasIccCard();
4380 int simState = mTm.getSimState();
4381 log("hasIccCard=" + hasIccCard
4382 + " simState=" + simState);
4383 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4384 if (ni != null) {
4385 log("ni.length=" + ni.length);
4386 for (NetworkInfo netInfo: ni) {
4387 log("netInfo=" + netInfo.toString());
4388 }
4389 } else {
4390 log("no network info ni=null");
4391 }
4392 }
4393
4394 /**
4395 * Sleep for a few seconds then return.
4396 * @param seconds
4397 */
4398 private static void sleep(int seconds) {
4399 try {
4400 Thread.sleep(seconds * 1000);
4401 } catch (InterruptedException e) {
4402 e.printStackTrace();
4403 }
4404 }
4405
Wink Saville690cb182013-06-29 21:10:57 -07004406 private void log(String s) {
4407 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4408 }
4409 }
4410
Wink Saville89c87b92013-08-29 08:55:16 -07004411 // TODO: Move to ConnectivityManager and make public?
4412 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4413 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville690cb182013-06-29 21:10:57 -07004414
Wink Saville89c87b92013-08-29 08:55:16 -07004415 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4416 @Override
4417 public void onReceive(Context context, Intent intent) {
4418 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4419 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4420 }
4421 }
4422 };
4423
4424 private void handleMobileProvisioningAction(String url) {
4425 // Notication mark notification as not visible
Wink Savillea65f4732013-10-03 08:34:46 -07004426 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004427
4428 // If provisioning network handle as a special case,
4429 // otherwise launch browser with the intent directly.
4430 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville860f5282013-09-05 12:02:25 -07004431 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07004432 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4433 MobileDataStateTracker mdst = (MobileDataStateTracker)
4434 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4435 mdst.enableMobileProvisioning(url);
4436 } else {
4437 if (DBG) log("handleMobileProvisioningAction: on default network");
Andrew Flynn2f158282013-10-11 10:16:31 -07004438 // Check for apps that can handle provisioning first
4439 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
4440 provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
4441 + mTelephonyManager.getSimOperator());
4442 if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
4443 != null) {
4444 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4445 Intent.FLAG_ACTIVITY_NEW_TASK);
4446 mContext.startActivity(provisioningIntent);
4447 } else {
4448 // If no apps exist, use standard URL ACTION_VIEW method
4449 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4450 Intent.CATEGORY_APP_BROWSER);
4451 newIntent.setData(Uri.parse(url));
4452 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4453 Intent.FLAG_ACTIVITY_NEW_TASK);
4454 try {
4455 mContext.startActivity(newIntent);
4456 } catch (ActivityNotFoundException e) {
4457 loge("handleMobileProvisioningAction: startActivity failed" + e);
4458 }
Wink Saville89c87b92013-08-29 08:55:16 -07004459 }
4460 }
4461 }
4462
4463 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4464 private volatile boolean mIsNotificationVisible = false;
4465
4466 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4467 String url) {
4468 if (DBG) {
4469 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4470 + " extraInfo=" + extraInfo + " url=" + url);
4471 }
Wink Saville690cb182013-06-29 21:10:57 -07004472
4473 Resources r = Resources.getSystem();
4474 NotificationManager notificationManager = (NotificationManager) mContext
4475 .getSystemService(Context.NOTIFICATION_SERVICE);
4476
4477 if (visible) {
4478 CharSequence title;
4479 CharSequence details;
4480 int icon;
Wink Saville89c87b92013-08-29 08:55:16 -07004481 Intent intent;
4482 Notification notification = new Notification();
4483 switch (networkType) {
Wink Saville690cb182013-06-29 21:10:57 -07004484 case ConnectivityManager.TYPE_WIFI:
Wink Saville690cb182013-06-29 21:10:57 -07004485 title = r.getString(R.string.wifi_available_sign_in, 0);
4486 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004487 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004488 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004489 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4490 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4491 Intent.FLAG_ACTIVITY_NEW_TASK);
4492 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004493 break;
4494 case ConnectivityManager.TYPE_MOBILE:
4495 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville690cb182013-06-29 21:10:57 -07004496 title = r.getString(R.string.network_available_sign_in, 0);
4497 // TODO: Change this to pull from NetworkInfo once a printable
4498 // name has been added to it
4499 details = mTelephonyManager.getNetworkOperatorName();
4500 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004501 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4502 intent.putExtra("EXTRA_URL", url);
4503 intent.setFlags(0);
4504 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004505 break;
4506 default:
Wink Saville690cb182013-06-29 21:10:57 -07004507 title = r.getString(R.string.network_available_sign_in, 0);
4508 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004509 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004510 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004511 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4512 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4513 Intent.FLAG_ACTIVITY_NEW_TASK);
4514 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004515 break;
4516 }
4517
Wink Saville690cb182013-06-29 21:10:57 -07004518 notification.when = 0;
4519 notification.icon = icon;
4520 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville690cb182013-06-29 21:10:57 -07004521 notification.tickerText = title;
4522 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4523
Wink Saville89c87b92013-08-29 08:55:16 -07004524 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004525 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville89c87b92013-08-29 08:55:16 -07004526 } catch (NullPointerException npe) {
4527 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4528 npe.printStackTrace();
4529 }
Wink Saville690cb182013-06-29 21:10:57 -07004530 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004531 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004532 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville89c87b92013-08-29 08:55:16 -07004533 } catch (NullPointerException npe) {
4534 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4535 npe.printStackTrace();
4536 }
Wink Saville690cb182013-06-29 21:10:57 -07004537 }
Wink Saville89c87b92013-08-29 08:55:16 -07004538 mIsNotificationVisible = visible;
Wink Saville690cb182013-06-29 21:10:57 -07004539 }
4540
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004541 /** Location to an updatable file listing carrier provisioning urls.
4542 * An example:
4543 *
4544 * <?xml version="1.0" encoding="utf-8"?>
4545 * <provisioningUrls>
4546 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4547 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4548 * </provisioningUrls>
4549 */
4550 private static final String PROVISIONING_URL_PATH =
4551 "/data/misc/radio/provisioning_urls.xml";
4552 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004553
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004554 /** XML tag for root element. */
4555 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4556 /** XML tag for individual url */
4557 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4558 /** XML tag for redirected url */
4559 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4560 /** XML attribute for mcc */
4561 private static final String ATTR_MCC = "mcc";
4562 /** XML attribute for mnc */
4563 private static final String ATTR_MNC = "mnc";
4564
4565 private static final int REDIRECTED_PROVISIONING = 1;
4566 private static final int PROVISIONING = 2;
4567
4568 private String getProvisioningUrlBaseFromFile(int type) {
4569 FileReader fileReader = null;
4570 XmlPullParser parser = null;
4571 Configuration config = mContext.getResources().getConfiguration();
4572 String tagType;
4573
4574 switch (type) {
4575 case PROVISIONING:
4576 tagType = TAG_PROVISIONING_URL;
4577 break;
4578 case REDIRECTED_PROVISIONING:
4579 tagType = TAG_REDIRECTED_URL;
4580 break;
4581 default:
4582 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4583 type);
4584 }
4585
4586 try {
4587 fileReader = new FileReader(mProvisioningUrlFile);
4588 parser = Xml.newPullParser();
4589 parser.setInput(fileReader);
4590 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4591
4592 while (true) {
4593 XmlUtils.nextElement(parser);
4594
4595 String element = parser.getName();
4596 if (element == null) break;
4597
4598 if (element.equals(tagType)) {
4599 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4600 try {
4601 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4602 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4603 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4604 parser.next();
4605 if (parser.getEventType() == XmlPullParser.TEXT) {
4606 return parser.getText();
4607 }
4608 }
4609 }
4610 } catch (NumberFormatException e) {
4611 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4612 }
4613 }
4614 }
4615 return null;
4616 } catch (FileNotFoundException e) {
4617 loge("Carrier Provisioning Urls file not found");
4618 } catch (XmlPullParserException e) {
4619 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4620 } catch (IOException e) {
4621 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4622 } finally {
4623 if (fileReader != null) {
4624 try {
4625 fileReader.close();
4626 } catch (IOException e) {}
4627 }
4628 }
4629 return null;
4630 }
4631
Wink Savillef714b7f2013-07-20 20:31:59 -07004632 @Override
4633 public String getMobileRedirectedProvisioningUrl() {
4634 enforceConnectivityInternalPermission();
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004635 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4636 if (TextUtils.isEmpty(url)) {
4637 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4638 }
4639 return url;
4640 }
4641
Wink Savillef714b7f2013-07-20 20:31:59 -07004642 @Override
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004643 public String getMobileProvisioningUrl() {
4644 enforceConnectivityInternalPermission();
4645 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4646 if (TextUtils.isEmpty(url)) {
4647 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillef714b7f2013-07-20 20:31:59 -07004648 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004649 } else {
Wink Savillef714b7f2013-07-20 20:31:59 -07004650 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004651 }
Wink Savilledfabd992013-07-10 23:00:07 -07004652 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004653 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004654 String phoneNumber = mTelephonyManager.getLine1Number();
4655 if (TextUtils.isEmpty(phoneNumber)) {
4656 phoneNumber = "0000000000";
4657 }
Wink Saville690cb182013-06-29 21:10:57 -07004658 url = String.format(url,
4659 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4660 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004661 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004662 }
4663
Wink Saville690cb182013-06-29 21:10:57 -07004664 return url;
4665 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004666
Wink Saville89c87b92013-08-29 08:55:16 -07004667 @Override
4668 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4669 String extraInfo, String url) {
4670 enforceConnectivityInternalPermission();
4671 setProvNotificationVisible(visible, networkType, extraInfo, url);
4672 }
Wink Saville3ade4872013-08-29 14:57:08 -07004673
Yuhao Zheng15019892013-09-09 17:00:04 -07004674 @Override
4675 public void setAirplaneMode(boolean enable) {
4676 enforceConnectivityInternalPermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07004677 final long ident = Binder.clearCallingIdentity();
4678 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07004679 final ContentResolver cr = mContext.getContentResolver();
4680 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4681 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4682 intent.putExtra("state", enable);
Yuhao Zheng15019892013-09-09 17:00:04 -07004683 mContext.sendBroadcast(intent);
4684 } finally {
4685 Binder.restoreCallingIdentity(ident);
4686 }
4687 }
4688
Chad Brubakerccae0d32013-06-14 11:16:51 -07004689 private void onUserStart(int userId) {
4690 synchronized(mVpns) {
4691 Vpn userVpn = mVpns.get(userId);
4692 if (userVpn != null) {
4693 loge("Starting user already has a VPN");
4694 return;
4695 }
4696 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4697 mVpns.put(userId, userVpn);
4698 userVpn.startMonitoring(mContext, mTrackerHandler);
4699 }
4700 }
4701
4702 private void onUserStop(int userId) {
4703 synchronized(mVpns) {
4704 Vpn userVpn = mVpns.get(userId);
4705 if (userVpn == null) {
4706 loge("Stopping user has no VPN");
4707 return;
4708 }
4709 mVpns.delete(userId);
4710 }
4711 }
4712
4713 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4714 @Override
4715 public void onReceive(Context context, Intent intent) {
4716 final String action = intent.getAction();
4717 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4718 if (userId == UserHandle.USER_NULL) return;
4719
4720 if (Intent.ACTION_USER_STARTING.equals(action)) {
4721 onUserStart(userId);
4722 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4723 onUserStop(userId);
4724 }
4725 }
4726 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004727
4728 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004729 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004730 enforceAccessPermission();
4731 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004732 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004733 } else {
4734 return null;
4735 }
4736 }
4737
4738 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004739 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004740 enforceAccessPermission();
4741 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004742 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004743 } else {
4744 return null;
4745 }
4746 }
4747
4748 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004749 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004750 enforceAccessPermission();
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004751 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004752 for (NetworkStateTracker tracker : mNetTrackers) {
4753 if (tracker != null) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004754 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004755 if (li != null) {
4756 result.add(li);
4757 }
4758 }
4759 }
4760
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004761 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004762 }
4763
4764 /* Infrastructure for network sampling */
4765
4766 private void handleNetworkSamplingTimeout() {
4767
4768 log("Sampling interval elapsed, updating statistics ..");
4769
4770 // initialize list of interfaces ..
4771 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4772 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4773 for (NetworkStateTracker tracker : mNetTrackers) {
4774 if (tracker != null) {
4775 String ifaceName = tracker.getNetworkInterfaceName();
4776 if (ifaceName != null) {
4777 mapIfaceToSample.put(ifaceName, null);
4778 }
4779 }
4780 }
4781
4782 // Read samples for all interfaces
4783 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4784
4785 // process samples for all networks
4786 for (NetworkStateTracker tracker : mNetTrackers) {
4787 if (tracker != null) {
4788 String ifaceName = tracker.getNetworkInterfaceName();
4789 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4790 if (ss != null) {
4791 // end the previous sampling cycle
4792 tracker.stopSampling(ss);
4793 // start a new sampling cycle ..
4794 tracker.startSampling(ss);
4795 }
4796 }
4797 }
4798
4799 log("Done.");
4800
4801 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4802 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4803 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4804
4805 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4806
4807 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4808 }
4809
4810 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4811 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4812 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4813 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004814}