blob: a92ceec27f6d5acb575ef5667a9cd8292762d3fb [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyfb878b62012-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 Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070035import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080038import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville948282b2013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090043import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070050import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080052import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080053import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070059import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Jeff Sharkeye4984be2013-09-10 21:03:27 -070062import android.net.LinkQualityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070073import android.net.RouteInfo;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monk602b2322013-07-03 17:04:33 -040075import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090077import android.net.wimax.WimaxManagerConstants;
Wink Savilleab9321d2013-06-29 21:10:57 -070078import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070089import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070091import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070093import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070095import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070097import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070098import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070099import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700100import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800101import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700102import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700108import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700109import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700110import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700111import com.android.internal.telephony.DctConstants;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700112import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -0700113import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700114import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700116import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400117import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900118import com.android.server.connectivity.Nat464Xlat;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.server.connectivity.PacManager;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
tk.mun148c7d02011-10-13 22:51:57 +0900127import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700128
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700129import org.xmlpull.v1.XmlPullParser;
130import org.xmlpull.v1.XmlPullParserException;
131
132import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700134import java.io.FileNotFoundException;
135import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700136import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900138import java.lang.reflect.Constructor;
Wink Savilleab9321d2013-06-29 21:10:57 -0700139import java.net.HttpURLConnection;
Wink Savillec9822c52011-07-14 12:23:28 -0700140import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700141import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700142import java.net.InetAddress;
Wink Savilleab9321d2013-06-29 21:10:57 -0700143import java.net.URL;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700144import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700146import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700147import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700148import java.util.GregorianCalendar;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700149import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700150import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700151import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700152import java.util.Map;
Wink Savilleab9321d2013-06-29 21:10:57 -0700153import java.util.Random;
Wink Saville948282b2013-08-29 08:55:16 -0700154import java.util.concurrent.atomic.AtomicBoolean;
Wink Savilleab9321d2013-06-29 21:10:57 -0700155import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157/**
158 * @hide
159 */
160public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700161 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Robert Greenwaltba175a52010-10-05 19:12:26 -0700163 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700164 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166 private static final boolean LOGD_RULES = false;
167
Jeff Sharkey899223b2012-08-04 15:24:58 -0700168 // TODO: create better separation between radio types and network types
169
Robert Greenwalt42acef32009-08-12 16:08:25 -0700170 // how long to wait before switching back to a radio's default network
171 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
172 // system property that can override the above value
173 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
174 "android.telephony.apn-restore";
175
Wink Savilleab9321d2013-06-29 21:10:57 -0700176 // Default value if FAIL_FAST_TIME_MS is not set
177 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
178 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
179 private static final String FAIL_FAST_TIME_MS =
180 "persist.radio.fail_fast_time_ms";
181
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700182 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
183 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
184
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -0700185 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700186
187 private PendingIntent mSampleIntervalElapsedIntent;
188
189 // Set network sampling interval at 12 minutes, this way, even if the timers get
190 // aggregated, it will fire at around 15 minutes, which should allow us to
191 // aggregate this timer with other timers (specially the socket keep alive timers)
192 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
193
194 // start network sampling a minute after booting ...
195 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
196
197 AlarmManager mAlarmManager;
198
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700199 // used in recursive route setting to add gateways for the host for which
200 // a host route was requested.
201 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
202
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800203 private Tethering mTethering;
204
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700205 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700206
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700207 @GuardedBy("mVpns")
208 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700209 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700210
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700211 private boolean mLockdownEnabled;
212 private LockdownVpnTracker mLockdownTracker;
213
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900214 private Nat464Xlat mClat;
215
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700216 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
217 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700218 /** Currently active network rules by UID. */
219 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700220 /** Set of ifaces that are costly. */
221 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 /**
224 * Sometimes we want to refer to the individual network state
225 * trackers separately, and sometimes we just want to treat them
226 * abstractly.
227 */
228 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700229
Irfan Sheriffda6da092012-08-16 12:49:23 -0700230 /* Handles captive portal check on a network */
231 private CaptivePortalTracker mCaptivePortalTracker;
232
Robert Greenwalt42acef32009-08-12 16:08:25 -0700233 /**
Wink Savillee8222252011-07-13 13:44:13 -0700234 * The link properties that define the current links
235 */
236 private LinkProperties mCurrentLinkProperties[];
237
238 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700239 * A per Net list of the PID's that requested access to the net
240 * used both as a refcount and for per-PID DNS selection
241 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200242 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700243
Robert Greenwalt42acef32009-08-12 16:08:25 -0700244 // priority order of the nettrackers
245 // (excluding dynamically set mNetworkPreference)
246 // TODO - move mNetworkTypePreference into this
247 private int[] mPriorityList;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 private Context mContext;
250 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700251 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700252 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000253 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 private int mDefaultInetConditionPublished = 0;
255 private boolean mInetConditionChangeInFlight = false;
256 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700258 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800259 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
261 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700262 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700264 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700265 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700266
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 private static final int ENABLED = 1;
268 private static final int DISABLED = 0;
269
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700270 private static final boolean ADD = true;
271 private static final boolean REMOVE = false;
272
273 private static final boolean TO_DEFAULT_TABLE = true;
274 private static final boolean TO_SECONDARY_TABLE = false;
275
Chad Brubakerf336d722013-07-15 16:34:04 -0700276 private static final boolean EXEMPT = true;
277 private static final boolean UNEXEMPT = false;
278
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700279 /**
280 * used internally as a delayed event to make us switch back to the
281 * default network
282 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700283 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700284
285 /**
286 * used internally to change our mobile data enabled flag
287 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700288 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700289
290 /**
291 * used internally to change our network preference setting
292 * arg1 = networkType to prefer
293 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700295
296 /**
297 * used internally to synchronize inet condition reports
298 * arg1 = networkType
299 * arg2 = condition (0 bad, 100 good)
300 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700301 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700302
303 /**
304 * used internally to mark the end of inet condition hold periods
305 * arg1 = networkType
306 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700307 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700308
309 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700310 * used internally to set enable/disable cellular data
311 * arg1 = ENBALED or DISABLED
312 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700313 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700314
Robert Greenwaltf3331232010-09-24 14:32:21 -0700315 /**
316 * used internally to clear a wakelock when transitioning
317 * from one net to another
318 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700319 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700320
Robert Greenwalt434203a2010-10-11 16:00:27 -0700321 /**
322 * used internally to reload global proxy settings
323 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700324 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700325
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700326 /**
327 * used internally to set external dependency met/unmet
328 * arg1 = ENABLED (met) or DISABLED (unmet)
329 * arg2 = NetworkType
330 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700331 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700332
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700333 /**
Wink Saville628b0852011-08-04 15:01:58 -0700334 * used internally to send a sticky broadcast delayed.
335 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700336 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700337
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700338 /**
339 * Used internally to
340 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
341 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700342 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700343
Chad Brubakerb98703e2013-07-23 17:44:41 -0700344 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700345
Wink Savilleab9321d2013-06-29 21:10:57 -0700346 /**
347 * Used internally to disable fail fast of mobile data
348 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700349 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Savilleab9321d2013-06-29 21:10:57 -0700350
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700351 /**
352 * user internally to indicate that data sampling interval is up
353 */
354 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
355
Jason Monkdecd2952013-10-10 14:02:51 -0400356 /**
357 * PAC manager has received new port.
358 */
359 private static final int EVENT_PROXY_HAS_CHANGED = 16;
360
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700361 /** Handler used for internal events. */
362 private InternalHandler mHandler;
363 /** Handler used for incoming {@link NetworkStateTracker} events. */
364 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700365
366 // list of DeathRecipients used to make sure features are turned off when
367 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500368 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700369
Mike Lockwood0f79b542009-08-14 14:18:49 -0400370 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800371 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400372
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700373 private PowerManager.WakeLock mNetTransitionWakeLock;
374 private String mNetTransitionWakeLockCausedBy = "";
375 private int mNetTransitionWakeLockSerialNumber;
376 private int mNetTransitionWakeLockTimeout;
377
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700378 private InetAddress mDefaultDns;
379
Chad Brubakerf336d722013-07-15 16:34:04 -0700380 // Lock for protecting access to mAddedRoutes and mExemptAddresses
381 private final Object mRoutesLock = new Object();
382
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700383 // this collection is used to refcount the added routes - if there are none left
384 // it's time to remove the route from the route table
Chad Brubakerf336d722013-07-15 16:34:04 -0700385 @GuardedBy("mRoutesLock")
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700386 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
387
Chad Brubakerf336d722013-07-15 16:34:04 -0700388 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
389 // used to handle cleanup of exempt rules
390 @GuardedBy("mRoutesLock")
391 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
392
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700393 // used in DBG mode to track inet condition reports
394 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
395 private ArrayList mInetLog;
396
Robert Greenwalt434203a2010-10-11 16:00:27 -0700397 // track the current default http proxy - tell the world if we get a new one (real change)
398 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700399 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700400 private boolean mDefaultProxyDisabled = false;
401
Robert Greenwalt434203a2010-10-11 16:00:27 -0700402 // track the global proxy.
403 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700404
Jason Monk602b2322013-07-03 17:04:33 -0400405 private PacManager mPacManager = null;
406
Robert Greenwalt434203a2010-10-11 16:00:27 -0700407 private SettingsObserver mSettingsObserver;
408
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700409 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700410 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411
Robert Greenwalt511288a2009-12-07 11:33:18 -0800412 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700413 public int mSimultaneity;
414 public int mType;
415 public RadioAttributes(String init) {
416 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700417 mType = Integer.parseInt(fragments[0]);
418 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700419 }
420 }
421 RadioAttributes[] mRadioAttributes;
422
Robert Greenwalt50393202011-06-21 17:26:14 -0700423 // the set of network types that can only be enabled by system/sig apps
424 List mProtectedNetworks;
425
John Spurlockbf991a82013-06-24 14:20:23 -0400426 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700427
Wink Savilleab9321d2013-06-29 21:10:57 -0700428 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
429
430 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400431
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700432 public ConnectivityService(Context context, INetworkManagementService netd,
433 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700434 // Currently, omitting a NetworkFactory will create one internally
435 // TODO: create here when we have cleaner WiMAX support
436 this(context, netd, statsService, policyManager, null);
437 }
438
Jeff Sharkey899223b2012-08-04 15:24:58 -0700439 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700440 INetworkStatsService statsService, INetworkPolicyManager policyManager,
441 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800442 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800443
Wink Savillebb08caf2010-09-02 19:23:52 -0700444 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
445 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700446 mHandler = new InternalHandler(handlerThread.getLooper());
447 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700448
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700449 if (netFactory == null) {
450 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
451 }
452
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800453 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800454 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
455 String id = Settings.Secure.getString(context.getContentResolver(),
456 Settings.Secure.ANDROID_ID);
457 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700458 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800459 SystemProperties.set("net.hostname", name);
460 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800461 }
462
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700463 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700464 String dns = Settings.Global.getString(context.getContentResolver(),
465 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700466 if (dns == null || dns.length() == 0) {
467 dns = context.getResources().getString(
468 com.android.internal.R.string.config_default_dns_server);
469 }
470 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800471 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
472 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800473 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700474 }
475
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700476 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700477 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700478 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700479 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700480 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700481
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700482 try {
483 mPolicyManager.registerListener(mPolicyListener);
484 } catch (RemoteException e) {
485 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700486 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700487 }
488
489 final PowerManager powerManager = (PowerManager) context.getSystemService(
490 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700491 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
492 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
493 com.android.internal.R.integer.config_networkTransitionTimeout);
494
Robert Greenwalt42acef32009-08-12 16:08:25 -0700495 mNetTrackers = new NetworkStateTracker[
496 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700497 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700498
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700499 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700500 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700501
Robert Greenwalt42acef32009-08-12 16:08:25 -0700502 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700503 String[] raStrings = context.getResources().getStringArray(
504 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700505 for (String raString : raStrings) {
506 RadioAttributes r = new RadioAttributes(raString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700507 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700508 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800509 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700510 continue;
511 }
512 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800513 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700514 r.mType);
515 continue;
516 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517 mRadioAttributes[r.mType] = r;
518 }
519
Wink Saville51f456f2013-04-23 14:26:51 -0700520 // TODO: What is the "correct" way to do determine if this is a wifi only device?
521 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
522 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700523 String[] naStrings = context.getResources().getStringArray(
524 com.android.internal.R.array.networkAttributes);
525 for (String naString : naStrings) {
526 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700527 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700528 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700529 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800530 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700531 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700532 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700533 }
Wink Saville51f456f2013-04-23 14:26:51 -0700534 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
535 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
536 n.type);
537 continue;
538 }
Wink Saville975c8482011-04-07 14:23:45 -0700539 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800540 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700541 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700542 continue;
543 }
Wink Saville975c8482011-04-07 14:23:45 -0700544 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800545 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700546 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700547 continue;
548 }
Wink Saville975c8482011-04-07 14:23:45 -0700549 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700550 mNetworksDefined++;
551 } catch(Exception e) {
552 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700553 }
554 }
Wink Saville5e56bc52013-07-29 15:00:57 -0700555 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700556
Robert Greenwalt50393202011-06-21 17:26:14 -0700557 mProtectedNetworks = new ArrayList<Integer>();
558 int[] protectedNetworks = context.getResources().getIntArray(
559 com.android.internal.R.array.config_protectedNetworks);
560 for (int p : protectedNetworks) {
561 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
562 mProtectedNetworks.add(p);
563 } else {
564 if (DBG) loge("Ignoring protectedNetwork " + p);
565 }
566 }
567
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700568 // high priority first
569 mPriorityList = new int[mNetworksDefined];
570 {
571 int insertionPoint = mNetworksDefined-1;
572 int currentLowest = 0;
573 int nextLowest = 0;
574 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700575 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700576 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700577 if (na.priority < currentLowest) continue;
578 if (na.priority > currentLowest) {
579 if (na.priority < nextLowest || nextLowest == 0) {
580 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700581 }
582 continue;
583 }
Wink Saville975c8482011-04-07 14:23:45 -0700584 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700585 }
586 currentLowest = nextLowest;
587 nextLowest = 0;
588 }
589 }
590
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800591 // Update mNetworkPreference according to user mannually first then overlay config.xml
592 mNetworkPreference = getPersistedNetworkPreference();
593 if (mNetworkPreference == -1) {
594 for (int n : mPriorityList) {
595 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
596 mNetworkPreference = n;
597 break;
598 }
599 }
600 if (mNetworkPreference == -1) {
601 throw new IllegalStateException(
602 "You should set at least one default Network in config.xml!");
603 }
604 }
605
Mattias Falk8b47b362011-08-23 14:15:13 +0200606 mNetRequestersPids =
607 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700608 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200609 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700610 }
611
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500612 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700613
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700614 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
615 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700616
617 // Create and start trackers for hard-coded networks
618 for (int targetNetworkType : mPriorityList) {
619 final NetworkConfig config = mNetConfigs[targetNetworkType];
620 final NetworkStateTracker tracker;
621 try {
622 tracker = netFactory.createTracker(targetNetworkType, config);
623 mNetTrackers[targetNetworkType] = tracker;
624 } catch (IllegalArgumentException e) {
625 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
626 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700627 continue;
628 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700629
630 tracker.startMonitoring(context, mTrackerHandler);
631 if (config.isDefault()) {
632 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800633 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700634 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800635
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700636 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800637
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700638 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700639 IntentFilter intentFilter = new IntentFilter();
640 intentFilter.addAction(Intent.ACTION_USER_STARTING);
641 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
642 mContext.registerReceiverAsUser(
643 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900644 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
645
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700646 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700647 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700648 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900649 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700650 } catch (RemoteException e) {
651 loge("Error registering observer :" + e);
652 }
653
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700654 if (DBG) {
655 mInetLog = new ArrayList();
656 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700657
658 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
659 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800660
John Spurlockbf991a82013-06-24 14:20:23 -0400661 mDataConnectionStats = new DataConnectionStats(mContext);
662 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400663
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700664 // start network sampling ..
665 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
666 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -0700667 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700668
669 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
670 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
671
672 IntentFilter filter = new IntentFilter();
673 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
674 mContext.registerReceiver(
675 new BroadcastReceiver() {
676 @Override
677 public void onReceive(Context context, Intent intent) {
678 String action = intent.getAction();
679 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
680 mHandler.sendMessage(mHandler.obtainMessage
681 (EVENT_SAMPLE_INTERVAL_ELAPSED));
682 }
683 }
684 },
685 new IntentFilter(filter));
686
Jason Monkdecd2952013-10-10 14:02:51 -0400687 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700688
689 filter = new IntentFilter();
Wink Saville948282b2013-08-29 08:55:16 -0700690 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
691 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700693
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700694 /**
695 * Factory that creates {@link NetworkStateTracker} instances using given
696 * {@link NetworkConfig}.
697 */
698 public interface NetworkFactory {
699 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
700 }
701
702 private static class DefaultNetworkFactory implements NetworkFactory {
703 private final Context mContext;
704 private final Handler mTrackerHandler;
705
706 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
707 mContext = context;
708 mTrackerHandler = trackerHandler;
709 }
710
711 @Override
712 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
713 switch (config.radio) {
714 case TYPE_WIFI:
715 return new WifiStateTracker(targetNetworkType, config.name);
716 case TYPE_MOBILE:
717 return new MobileDataStateTracker(targetNetworkType, config.name);
718 case TYPE_DUMMY:
719 return new DummyDataStateTracker(targetNetworkType, config.name);
720 case TYPE_BLUETOOTH:
721 return BluetoothTetheringDataTracker.getInstance();
722 case TYPE_WIMAX:
723 return makeWimaxStateTracker(mContext, mTrackerHandler);
724 case TYPE_ETHERNET:
725 return EthernetDataTracker.getInstance();
726 default:
727 throw new IllegalArgumentException(
728 "Trying to create a NetworkStateTracker for an unknown radio type: "
729 + config.radio);
730 }
731 }
732 }
733
734 /**
735 * Loads external WiMAX library and registers as system service, returning a
736 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
737 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
738 */
739 private static NetworkStateTracker makeWimaxStateTracker(
740 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700741 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900742 DexClassLoader wimaxClassLoader;
743 Class wimaxStateTrackerClass = null;
744 Class wimaxServiceClass = null;
745 Class wimaxManagerClass;
746 String wimaxJarLocation;
747 String wimaxLibLocation;
748 String wimaxManagerClassName;
749 String wimaxServiceClassName;
750 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
tk.mun148c7d02011-10-13 22:51:57 +0900752 NetworkStateTracker wimaxStateTracker = null;
753
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700754 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900755 com.android.internal.R.bool.config_wimaxEnabled);
756
757 if (isWimaxEnabled) {
758 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700759 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900760 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700761 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900762 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700763 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900764 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700765 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900766 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700767 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900768 com.android.internal.R.string.config_wimaxStateTrackerClassname);
769
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800770 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900771 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700772 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900773 wimaxLibLocation, ClassLoader.getSystemClassLoader());
774
775 try {
776 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
777 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
778 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
779 } catch (ClassNotFoundException ex) {
780 loge("Exception finding Wimax classes: " + ex.toString());
781 return null;
782 }
783 } catch(Resources.NotFoundException ex) {
784 loge("Wimax Resources does not exist!!! ");
785 return null;
786 }
787
788 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800789 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900790
791 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
792 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700793 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
794 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900795
796 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
797 (new Class[] {Context.class, wimaxStateTrackerClass});
798 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700799 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900800 wmxSrvConst.setAccessible(false);
801
802 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
803
804 } catch(Exception ex) {
805 loge("Exception creating Wimax classes: " + ex.toString());
806 return null;
807 }
808 } else {
809 loge("Wimax is not enabled or not added to the network attributes!!! ");
810 return null;
811 }
812
813 return wimaxStateTracker;
814 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700817 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 * @param preference the new preference
819 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700820 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700822
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700823 mHandler.sendMessage(
824 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826
827 public int getNetworkPreference() {
828 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700829 int preference;
830 synchronized(this) {
831 preference = mNetworkPreference;
832 }
833 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700836 private void handleSetNetworkPreference(int preference) {
837 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700838 mNetConfigs[preference] != null &&
839 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700840 if (mNetworkPreference != preference) {
841 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700842 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700843 synchronized(this) {
844 mNetworkPreference = preference;
845 }
846 enforcePreference();
847 }
848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700850
Wink Saville628b0852011-08-04 15:01:58 -0700851 private int getConnectivityChangeDelay() {
852 final ContentResolver cr = mContext.getContentResolver();
853
854 /** Check system properties for the default value then use secure settings value, if any. */
855 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700856 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
857 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
858 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700859 defaultDelay);
860 }
861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 private int getPersistedNetworkPreference() {
863 final ContentResolver cr = mContext.getContentResolver();
864
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700865 final int networkPrefSetting = Settings.Global
866 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800868 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700872 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 * In this method, we only tear down a non-preferred network. Establishing
874 * a connection to the preferred network is taken care of when we handle
875 * the disconnect event from the non-preferred network
876 * (see {@link #handleDisconnect(NetworkInfo)}).
877 */
878 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700879 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 return;
881
Robert Greenwalt42acef32009-08-12 16:08:25 -0700882 if (!mNetTrackers[mNetworkPreference].isAvailable())
883 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884
Robert Greenwalt42acef32009-08-12 16:08:25 -0700885 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700886 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700887 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700888 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800889 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700890 " in enforcePreference");
891 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894 }
895 }
896
897 private boolean teardown(NetworkStateTracker netTracker) {
898 if (netTracker.teardown()) {
899 netTracker.setTeardownRequested(true);
900 return true;
901 } else {
902 return false;
903 }
904 }
905
906 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700907 * Check if UID should be blocked from using the network represented by the
908 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700909 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700910 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
911 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700912
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700913 final boolean networkCostly;
914 final int uidRules;
915 synchronized (mRulesLock) {
916 networkCostly = mMeteredIfaces.contains(iface);
917 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700918 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700919
920 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
921 return true;
922 }
923
924 // no restrictive rules; network is visible
925 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700926 }
927
928 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700929 * Return a filtered {@link NetworkInfo}, potentially marked
930 * {@link DetailedState#BLOCKED} based on
931 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700933 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
934 NetworkInfo info = tracker.getNetworkInfo();
935 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700936 // network is blocked; clone and override state
937 info = new NetworkInfo(info);
938 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700939 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700940 if (mLockdownTracker != null) {
941 info = mLockdownTracker.augmentNetworkInfo(info);
942 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700943 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700944 }
945
946 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 * Return NetworkInfo for the active (i.e., connected) network interface.
948 * It is assumed that at most one network is active at a time. If more
949 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700950 * @return the info for the active network, or {@code null} if none is
951 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700953 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700955 enforceAccessPermission();
956 final int uid = Binder.getCallingUid();
957 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959
Wink Saville948282b2013-08-29 08:55:16 -0700960 /**
961 * Find the first Provisioning network.
962 *
963 * @return NetworkInfo or null if none.
964 */
965 private NetworkInfo getProvisioningNetworkInfo() {
966 enforceAccessPermission();
967
968 // Find the first Provisioning Network
969 NetworkInfo provNi = null;
970 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700971 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700972 provNi = ni;
973 break;
974 }
975 }
976 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
977 return provNi;
978 }
979
980 /**
981 * Find the first Provisioning network or the ActiveDefaultNetwork
982 * if there is no Provisioning network
983 *
984 * @return NetworkInfo or null if none.
985 */
986 @Override
987 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
988 enforceAccessPermission();
989
990 NetworkInfo provNi = getProvisioningNetworkInfo();
991 if (provNi == null) {
992 final int uid = Binder.getCallingUid();
993 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
994 }
995 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
996 return provNi;
997 }
998
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700999 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1000 enforceAccessPermission();
1001 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1002 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1003 if (tracker != null) {
1004 return tracker.getNetworkInfo();
1005 }
1006 }
1007 return null;
1008 }
1009
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001010 @Override
1011 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1012 enforceConnectivityInternalPermission();
1013 return getNetworkInfo(mActiveDefaultNetwork, uid);
1014 }
1015
1016 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 public NetworkInfo getNetworkInfo(int networkType) {
1018 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 final int uid = Binder.getCallingUid();
1020 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001023 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1024 NetworkInfo info = null;
1025 if (isNetworkTypeValid(networkType)) {
1026 final NetworkStateTracker tracker = mNetTrackers[networkType];
1027 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001028 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001029 }
1030 }
1031 return info;
1032 }
1033
1034 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 public NetworkInfo[] getAllNetworkInfo() {
1036 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001037 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001038 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001039 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 for (NetworkStateTracker tracker : mNetTrackers) {
1041 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001042 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 }
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001046 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001049 @Override
1050 public boolean isNetworkSupported(int networkType) {
1051 enforceAccessPermission();
1052 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1053 }
1054
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001055 /**
1056 * Return LinkProperties for the active (i.e., connected) default
1057 * network interface. It is assumed that at most one default network
1058 * is active at a time. If more than one is active, it is indeterminate
1059 * which will be returned.
1060 * @return the ip properties for the active network, or {@code null} if
1061 * none is active
1062 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001064 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -07001065 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001066 }
1067
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001069 public LinkProperties getLinkProperties(int networkType) {
1070 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 if (isNetworkTypeValid(networkType)) {
1072 final NetworkStateTracker tracker = mNetTrackers[networkType];
1073 if (tracker != null) {
1074 return tracker.getLinkProperties();
1075 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001076 }
1077 return null;
1078 }
1079
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001080 @Override
1081 public NetworkState[] getAllNetworkState() {
1082 enforceAccessPermission();
1083 final int uid = Binder.getCallingUid();
1084 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001085 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001086 for (NetworkStateTracker tracker : mNetTrackers) {
1087 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001088 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001089 result.add(new NetworkState(
1090 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1091 }
1092 }
1093 }
1094 return result.toArray(new NetworkState[result.size()]);
1095 }
1096
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001097 private NetworkState getNetworkStateUnchecked(int networkType) {
1098 if (isNetworkTypeValid(networkType)) {
1099 final NetworkStateTracker tracker = mNetTrackers[networkType];
1100 if (tracker != null) {
1101 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1102 tracker.getLinkCapabilities());
1103 }
1104 }
1105 return null;
1106 }
1107
1108 @Override
1109 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1110 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001111
1112 final long token = Binder.clearCallingIdentity();
1113 try {
1114 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1115 if (state != null) {
1116 try {
1117 return mPolicyManager.getNetworkQuotaInfo(state);
1118 } catch (RemoteException e) {
1119 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001120 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001121 return null;
1122 } finally {
1123 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001124 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001125 }
1126
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001127 @Override
1128 public boolean isActiveNetworkMetered() {
1129 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001130 final long token = Binder.clearCallingIdentity();
1131 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001132 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001133 } finally {
1134 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001135 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001136 }
1137
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001138 private boolean isNetworkMeteredUnchecked(int networkType) {
1139 final NetworkState state = getNetworkStateUnchecked(networkType);
1140 if (state != null) {
1141 try {
1142 return mPolicyManager.isNetworkMetered(state);
1143 } catch (RemoteException e) {
1144 }
1145 }
1146 return false;
1147 }
1148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 public boolean setRadios(boolean turnOn) {
1150 boolean result = true;
1151 enforceChangePermission();
1152 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001153 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155 return result;
1156 }
1157
1158 public boolean setRadio(int netType, boolean turnOn) {
1159 enforceChangePermission();
1160 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1161 return false;
1162 }
1163 NetworkStateTracker tracker = mNetTrackers[netType];
1164 return tracker != null && tracker.setRadio(turnOn);
1165 }
1166
Jeff Sharkey216c1812012-08-05 14:29:23 -07001167 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1168 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001169 public void interfaceClassDataActivityChanged(String label, boolean active) {
1170 int deviceType = Integer.parseInt(label);
1171 sendDataActivityBroadcast(deviceType, active);
1172 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001173 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001174
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001175 /**
1176 * Used to notice when the calling process dies so we can self-expire
1177 *
1178 * Also used to know if the process has cleaned up after itself when
1179 * our auto-expire timer goes off. The timer has a link to an object.
1180 *
1181 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001182 private class FeatureUser implements IBinder.DeathRecipient {
1183 int mNetworkType;
1184 String mFeature;
1185 IBinder mBinder;
1186 int mPid;
1187 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001188 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001189
1190 FeatureUser(int type, String feature, IBinder binder) {
1191 super();
1192 mNetworkType = type;
1193 mFeature = feature;
1194 mBinder = binder;
1195 mPid = getCallingPid();
1196 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001197 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001198
Robert Greenwalt42acef32009-08-12 16:08:25 -07001199 try {
1200 mBinder.linkToDeath(this, 0);
1201 } catch (RemoteException e) {
1202 binderDied();
1203 }
1204 }
1205
1206 void unlinkDeathRecipient() {
1207 mBinder.unlinkToDeath(this, 0);
1208 }
1209
1210 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001211 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001212 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1213 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001214 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001215 }
1216
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001217 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001218 if (VDBG) {
1219 log("ConnectivityService FeatureUser expire(" +
1220 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1221 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1222 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001223 stopUsingNetworkFeature(this, false);
1224 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001225
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001226 public boolean isSameUser(FeatureUser u) {
1227 if (u == null) return false;
1228
1229 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1230 }
1231
1232 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1233 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1234 TextUtils.equals(mFeature, feature)) {
1235 return true;
1236 }
1237 return false;
1238 }
1239
Robert Greenwaltb9285352009-12-21 18:24:07 -08001240 public String toString() {
1241 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1242 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1243 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001244 }
1245
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001246 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001247 public int startUsingNetworkFeature(int networkType, String feature,
1248 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001249 long startTime = 0;
1250 if (DBG) {
1251 startTime = SystemClock.elapsedRealtime();
1252 }
Wink Savillec9acde92011-09-21 11:05:43 -07001253 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001254 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1255 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001258 try {
1259 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1260 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001261 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001262 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001263
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001264 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001265
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001266 // TODO - move this into individual networktrackers
1267 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001268
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001269 if (mLockdownEnabled) {
1270 // Since carrier APNs usually aren't available from VPN
1271 // endpoint, mark them as unavailable.
1272 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1273 }
1274
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001275 if (mProtectedNetworks.contains(usedNetworkType)) {
1276 enforceConnectivityInternalPermission();
1277 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001278
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001279 // if UID is restricted, don't allow them to bring up metered APNs
1280 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1281 final int uidRules;
1282 synchronized (mRulesLock) {
1283 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1284 }
1285 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001286 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001287 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001288
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001289 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1290 if (network != null) {
1291 Integer currentPid = new Integer(getCallingPid());
1292 if (usedNetworkType != networkType) {
1293 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001294
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001295 if (ni.isAvailable() == false) {
1296 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1297 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001298 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001299 } else {
1300 // else make the attempt anyway - probably giving REQUEST_STARTED below
1301 if (DBG) {
1302 log("special network not available, but try anyway ni=" +
1303 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001304 }
1305 }
1306 }
1307
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001308 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001309
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001310 synchronized(this) {
1311 boolean addToList = true;
1312 if (restoreTimer < 0) {
1313 // In case there is no timer is specified for the feature,
1314 // make sure we don't add duplicate entry with the same request.
1315 for (FeatureUser u : mFeatureUsers) {
1316 if (u.isSameUser(f)) {
1317 // Duplicate user is found. Do not add.
1318 addToList = false;
1319 break;
1320 }
1321 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001322 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001323
1324 if (addToList) mFeatureUsers.add(f);
1325 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1326 // this gets used for per-pid dns when connected
1327 mNetRequestersPids[usedNetworkType].add(currentPid);
1328 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001329 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001330
1331 if (restoreTimer >= 0) {
1332 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1333 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1334 }
1335
1336 if ((ni.isConnectedOrConnecting() == true) &&
1337 !network.isTeardownRequested()) {
1338 if (ni.isConnected() == true) {
1339 final long token = Binder.clearCallingIdentity();
1340 try {
1341 // add the pid-specific dns
1342 handleDnsConfigurationChange(usedNetworkType);
1343 if (VDBG) log("special network already active");
1344 } finally {
1345 Binder.restoreCallingIdentity(token);
1346 }
Wink Savillea639b312012-07-10 12:37:54 -07001347 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001348 }
1349 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001350 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001351 }
1352
1353 // check if the radio in play can make another contact
1354 // assume if cannot for now
1355
1356 if (DBG) {
1357 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1358 feature);
1359 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001360 if (network.reconnect()) {
Wink Saville948282b2013-08-29 08:55:16 -07001361 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001362 return PhoneConstants.APN_REQUEST_STARTED;
1363 } else {
Wink Saville948282b2013-08-29 08:55:16 -07001364 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001365 return PhoneConstants.APN_REQUEST_FAILED;
1366 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001367 } else {
1368 // need to remember this unsupported request so we respond appropriately on stop
1369 synchronized(this) {
1370 mFeatureUsers.add(f);
1371 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1372 // this gets used for per-pid dns when connected
1373 mNetRequestersPids[usedNetworkType].add(currentPid);
1374 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001375 }
Wink Saville948282b2013-08-29 08:55:16 -07001376 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001377 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001378 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001379 }
Wink Saville948282b2013-08-29 08:55:16 -07001380 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Savillea639b312012-07-10 12:37:54 -07001381 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001382 } finally {
1383 if (DBG) {
1384 final long execTime = SystemClock.elapsedRealtime() - startTime;
1385 if (execTime > 250) {
1386 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1387 } else {
1388 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1389 }
1390 }
1391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001394 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001396 enforceChangePermission();
1397
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001398 int pid = getCallingPid();
1399 int uid = getCallingUid();
1400
1401 FeatureUser u = null;
1402 boolean found = false;
1403
1404 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001405 for (FeatureUser x : mFeatureUsers) {
1406 if (x.isSameUser(pid, uid, networkType, feature)) {
1407 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001408 found = true;
1409 break;
1410 }
1411 }
1412 }
1413 if (found && u != null) {
Wink Saville948282b2013-08-29 08:55:16 -07001414 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001415 // stop regardless of how many other time this proc had called start
1416 return stopUsingNetworkFeature(u, true);
1417 } else {
1418 // none found!
Wink Saville948282b2013-08-29 08:55:16 -07001419 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001420 return 1;
1421 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001422 }
1423
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001424 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1425 int networkType = u.mNetworkType;
1426 String feature = u.mFeature;
1427 int pid = u.mPid;
1428 int uid = u.mUid;
1429
1430 NetworkStateTracker tracker = null;
1431 boolean callTeardown = false; // used to carry our decision outside of sync block
1432
Wink Savillec9acde92011-09-21 11:05:43 -07001433 if (VDBG) {
1434 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001435 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001438 if (DBG) {
1439 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1440 ", net is invalid");
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 return -1;
1443 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001444
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001445 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1446 // sync block
1447 synchronized(this) {
1448 // check if this process still has an outstanding start request
1449 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001450 if (VDBG) {
1451 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1452 ", ignoring");
1453 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001454 return 1;
1455 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001456 u.unlinkDeathRecipient();
1457 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1458 // If we care about duplicate requests, check for that here.
1459 //
1460 // This is done to support the extension of a request - the app
1461 // can request we start the network feature again and renew the
1462 // auto-shutoff delay. Normal "stop" calls from the app though
1463 // do not pay attention to duplicate requests - in effect the
1464 // API does not refcount and a single stop will counter multiple starts.
1465 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001466 for (FeatureUser x : mFeatureUsers) {
1467 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001468 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001469 return 1;
1470 }
1471 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001472 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001473
repo syncaea743a2011-07-29 23:55:49 -07001474 // TODO - move to individual network trackers
1475 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1476
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001477 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001478 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001479 if (DBG) {
1480 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1481 " no known tracker for used net type " + usedNetworkType);
1482 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001483 return -1;
1484 }
1485 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001486 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001487 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001488
1489 final long token = Binder.clearCallingIdentity();
1490 try {
1491 reassessPidDns(pid, true);
1492 } finally {
1493 Binder.restoreCallingIdentity(token);
1494 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001495 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001496 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001497 if (VDBG) {
1498 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1499 " others still using it");
1500 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001501 return 1;
1502 }
1503 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001504 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001505 if (DBG) {
1506 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1507 " not a known feature - dropping");
1508 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001509 }
1510 }
Wink Savillec9acde92011-09-21 11:05:43 -07001511
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001512 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001513 if (DBG) {
1514 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1515 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001516 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001517 return 1;
1518 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001519 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
1523 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001524 * @deprecated use requestRouteToHostAddress instead
1525 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 * Ensure that a network route exists to deliver traffic to the specified
1527 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001528 * @param networkType the type of the network over which traffic to the
1529 * specified host is to be routed
1530 * @param hostAddress the IP address of the host to which the route is
1531 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 * @return {@code true} on success, {@code false} on failure
1533 */
1534 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001535 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1536
1537 if (inetAddress == null) {
1538 return false;
1539 }
1540
1541 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1542 }
1543
1544 /**
1545 * Ensure that a network route exists to deliver traffic to the specified
1546 * host via the specified network interface.
1547 * @param networkType the type of the network over which traffic to the
1548 * specified host is to be routed
1549 * @param hostAddress the IP address of the host to which the route is
1550 * desired
1551 * @return {@code true} on success, {@code false} on failure
1552 */
1553 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001555 if (mProtectedNetworks.contains(networkType)) {
1556 enforceConnectivityInternalPermission();
1557 }
1558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001560 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 return false;
1562 }
1563 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001564 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001565
Irfan Sheriffda6da092012-08-16 12:49:23 -07001566 if (tracker == null || (netState != DetailedState.CONNECTED &&
1567 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001568 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001569 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001570 log("requestRouteToHostAddress on down network "
1571 + "(" + networkType + ") - dropped"
1572 + " tracker=" + tracker
1573 + " netState=" + netState
1574 + " isTeardownRequested="
1575 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001576 }
1577 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001579 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001580 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001581 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001582 LinkProperties lp = tracker.getLinkProperties();
Chad Brubakerf336d722013-07-15 16:34:04 -07001583 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Savilleab9321d2013-06-29 21:10:57 -07001584 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1585 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001586 } catch (UnknownHostException e) {
1587 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1588 } finally {
1589 Binder.restoreCallingIdentity(token);
1590 }
Wink Savilleab9321d2013-06-29 21:10:57 -07001591 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001592 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001593 }
1594
Chad Brubakerf336d722013-07-15 16:34:04 -07001595 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1596 boolean exempt) {
1597 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001598 }
1599
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001600 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001601 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001602 }
1603
Chad Brubakerf336d722013-07-15 16:34:04 -07001604 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1605 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001606 }
1607
1608 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001609 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001610 }
1611
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001612 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubakerf336d722013-07-15 16:34:04 -07001613 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001614 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001615 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001616 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001617 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001618 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001619 if (bestRoute.getGateway().equals(addr)) {
1620 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001621 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001622 } else {
1623 // if we will connect to this through another route, add a direct route
1624 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001625 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001626 }
1627 }
Chad Brubakerf336d722013-07-15 16:34:04 -07001628 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001629 }
1630
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001631 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubakerf336d722013-07-15 16:34:04 -07001632 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001633 if ((lp == null) || (r == null)) {
1634 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001635 return false;
1636 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001637
1638 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001639 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001640 return false;
1641 }
1642
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001643 String ifaceName = r.getInterface();
1644 if(ifaceName == null) {
1645 loge("Error modifying route - no interface name");
1646 return false;
1647 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001648 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001649 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001650 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001651 if (bestRoute.getGateway().equals(r.getGateway())) {
1652 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001653 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001654 } else {
1655 // if we will connect to our gateway through another route, add a direct
1656 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001657 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1658 bestRoute.getGateway(),
1659 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001660 }
Chad Brubakerf336d722013-07-15 16:34:04 -07001661 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001662 }
1663 }
1664 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001665 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001666 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001667 if (toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001668 synchronized (mRoutesLock) {
1669 // only track default table - only one apps can effect
1670 mAddedRoutes.add(r);
1671 mNetd.addRoute(ifaceName, r);
1672 if (exempt) {
1673 LinkAddress dest = r.getDestination();
1674 if (!mExemptAddresses.contains(dest)) {
1675 mNetd.setHostExemption(dest);
1676 mExemptAddresses.add(dest);
1677 }
1678 }
1679 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001680 } else {
1681 mNetd.addSecondaryRoute(ifaceName, r);
1682 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001683 } catch (Exception e) {
1684 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001685 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001686 return false;
1687 }
1688 } else {
1689 // if we remove this one and there are no more like it, then refcount==0 and
1690 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001691 if (toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001692 synchronized (mRoutesLock) {
1693 mAddedRoutes.remove(r);
1694 if (mAddedRoutes.contains(r) == false) {
1695 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1696 try {
1697 mNetd.removeRoute(ifaceName, r);
1698 LinkAddress dest = r.getDestination();
1699 if (mExemptAddresses.contains(dest)) {
1700 mNetd.clearHostExemption(dest);
1701 mExemptAddresses.remove(dest);
1702 }
1703 } catch (Exception e) {
1704 // never crash - catch them all
1705 if (VDBG) loge("Exception trying to remove a route: " + e);
1706 return false;
1707 }
1708 } else {
1709 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001710 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001711 }
1712 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001713 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001714 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001715 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001716 } catch (Exception e) {
1717 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001718 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001719 return false;
1720 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001721 }
1722 }
1723 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
1725
1726 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001727 * @see ConnectivityManager#getMobileDataEnabled()
1728 */
1729 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001730 // TODO: This detail should probably be in DataConnectionTracker's
1731 // which is where we store the value and maybe make this
1732 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001733 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001734 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1735 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001736 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001737 return retVal;
1738 }
1739
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001740 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001741 enforceConnectivityInternalPermission();
1742
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1744 (met ? ENABLED : DISABLED), networkType));
1745 }
1746
1747 private void handleSetDependencyMet(int networkType, boolean met) {
1748 if (mNetTrackers[networkType] != null) {
1749 if (DBG) {
1750 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1751 }
1752 mNetTrackers[networkType].setDependencyMet(met);
1753 }
1754 }
1755
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001756 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1757 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001758 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001759 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001760 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001761 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001762 }
1763
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001764 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001765 // skip update when we've already applied rules
1766 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1767 if (oldRules == uidRules) return;
1768
1769 mUidRules.put(uid, uidRules);
1770 }
1771
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001772 // TODO: notify UID when it has requested targeted updates
1773 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001774
1775 @Override
1776 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001777 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001778 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001779 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001780 }
1781
1782 synchronized (mRulesLock) {
1783 mMeteredIfaces.clear();
1784 for (String iface : meteredIfaces) {
1785 mMeteredIfaces.add(iface);
1786 }
1787 }
1788 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001789
1790 @Override
1791 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1792 // caller is NPMS, since we only register with them
1793 if (LOGD_RULES) {
1794 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1795 }
1796
1797 // kick off connectivity change broadcast for active network, since
1798 // global background policy change is radical.
1799 final int networkType = mActiveDefaultNetwork;
1800 if (isNetworkTypeValid(networkType)) {
1801 final NetworkStateTracker tracker = mNetTrackers[networkType];
1802 if (tracker != null) {
1803 final NetworkInfo info = tracker.getNetworkInfo();
1804 if (info != null && info.isConnected()) {
1805 sendConnectedBroadcast(info);
1806 }
1807 }
1808 }
1809 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001810 };
1811
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001812 /**
1813 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1814 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001815 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001816 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001817 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001818
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001819 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001820 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001821 }
1822
1823 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001824 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001825 if (VDBG) {
1826 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001827 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001828 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1829 }
tk.munb97d34c2012-01-06 10:43:52 +09001830 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1831 if (VDBG) {
1832 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1833 }
1834 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1835 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001836 }
1837
1838 @Override
1839 public void setPolicyDataEnable(int networkType, boolean enabled) {
1840 // only someone like NPMS should only be calling us
1841 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1842
1843 mHandler.sendMessage(mHandler.obtainMessage(
1844 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1845 }
1846
1847 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1848 if (isNetworkTypeValid(networkType)) {
1849 final NetworkStateTracker tracker = mNetTrackers[networkType];
1850 if (tracker != null) {
1851 tracker.setPolicyDataEnable(enabled);
1852 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001853 }
1854 }
1855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001857 mContext.enforceCallingOrSelfPermission(
1858 android.Manifest.permission.ACCESS_NETWORK_STATE,
1859 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861
1862 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001863 mContext.enforceCallingOrSelfPermission(
1864 android.Manifest.permission.CHANGE_NETWORK_STATE,
1865 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001868 // TODO Make this a special check when it goes public
1869 private void enforceTetherChangePermission() {
1870 mContext.enforceCallingOrSelfPermission(
1871 android.Manifest.permission.CHANGE_NETWORK_STATE,
1872 "ConnectivityService");
1873 }
1874
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001875 private void enforceTetherAccessPermission() {
1876 mContext.enforceCallingOrSelfPermission(
1877 android.Manifest.permission.ACCESS_NETWORK_STATE,
1878 "ConnectivityService");
1879 }
1880
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001881 private void enforceConnectivityInternalPermission() {
1882 mContext.enforceCallingOrSelfPermission(
1883 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1884 "ConnectivityService");
1885 }
1886
Chad Brubakerd475c702013-07-11 13:29:30 -07001887 private void enforceMarkNetworkSocketPermission() {
1888 //Media server special case
1889 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1890 return;
1891 }
1892 mContext.enforceCallingOrSelfPermission(
1893 android.Manifest.permission.MARK_NETWORK_SOCKET,
1894 "ConnectivityService");
1895 }
1896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001898 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1899 * network, we ignore it. If it is for the active network, we send out a
1900 * broadcast. But first, we check whether it might be possible to connect
1901 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 * @param info the {@code NetworkInfo} for the network
1903 */
1904 private void handleDisconnect(NetworkInfo info) {
1905
Robert Greenwalt42acef32009-08-12 16:08:25 -07001906 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907
Robert Greenwalt42acef32009-08-12 16:08:25 -07001908 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001909
1910 // Remove idletimer previously setup in {@code handleConnect}
1911 removeDataActivityTracking(prevNetType);
1912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 /*
1914 * If the disconnected network is not the active one, then don't report
1915 * this as a loss of connectivity. What probably happened is that we're
1916 * getting the disconnect for a network that we explicitly disabled
1917 * in accordance with network preference policies.
1918 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001919 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001920 List<Integer> pids = mNetRequestersPids[prevNetType];
1921 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001922 // will remove them because the net's no longer connected
1923 // need to do this now as only now do we know the pids and
1924 // can properly null things that are no longer referenced.
1925 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001930 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001931 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 if (info.isFailover()) {
1933 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1934 info.setFailover(false);
1935 }
1936 if (info.getReason() != null) {
1937 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1938 }
1939 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001940 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1941 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001943
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001944 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001945 tryFailover(prevNetType);
1946 if (mActiveDefaultNetwork != -1) {
1947 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001948 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1949 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001950 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001951 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1952 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001953 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001954 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001955
1956 // Reset interface if no other connections are using the same interface
1957 boolean doReset = true;
1958 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1959 if (linkProperties != null) {
1960 String oldIface = linkProperties.getInterfaceName();
1961 if (TextUtils.isEmpty(oldIface) == false) {
1962 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1963 if (networkStateTracker == null) continue;
1964 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1965 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1966 LinkProperties l = networkStateTracker.getLinkProperties();
1967 if (l == null) continue;
1968 if (oldIface.equals(l.getInterfaceName())) {
1969 doReset = false;
1970 break;
1971 }
1972 }
1973 }
1974 }
1975 }
1976
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001977 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001978 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001979
Jeff Sharkey961e3042011-08-29 16:02:57 -07001980 final Intent immediateIntent = new Intent(intent);
1981 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1982 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001983 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001984 /*
1985 * If the failover network is already connected, then immediately send
1986 * out a followup broadcast indicating successful failover
1987 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001988 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001989 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1990 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001991 }
1992 }
1993
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001994 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001995 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001996 * If this is a default network, check if other defaults are available.
1997 * Try to reconnect on all available and let them hash it out when
1998 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001999 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002000 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002001 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville948282b2013-08-29 08:55:16 -07002002 if (DBG) {
2003 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2004 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002005 mActiveDefaultNetwork = -1;
2006 }
2007
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002008 // don't signal a reconnect for anything lower or equal priority than our
2009 // current connected default
2010 // TODO - don't filter by priority now - nice optimization but risky
2011// int currentPriority = -1;
2012// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002013// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002014// }
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002015
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002016 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07002017 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002018 if (mNetConfigs[checkType] == null) continue;
2019 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08002020 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08002021
2022// Enabling the isAvailable() optimization caused mobile to not get
2023// selected if it was in the middle of error handling. Specifically
2024// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2025// would not be available and we wouldn't get connected to anything.
2026// So removing the isAvailable() optimization below for now. TODO: This
2027// optimization should work and we need to investigate why it doesn't work.
2028// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2029// complete before it is really complete.
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002030
Wink Saville9f7a0b22011-01-26 15:43:49 -08002031// if (!mNetTrackers[checkType].isAvailable()) continue;
2032
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002033// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002034
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002035 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2036 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2037 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2038 checkInfo.setFailover(true);
2039 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002040 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002041 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07002042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002046 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002047 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07002048 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2049 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002050 }
2051
Wink Saville628b0852011-08-04 15:01:58 -07002052 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002053 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2054 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07002055 }
2056
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002057 private void sendInetConditionBroadcast(NetworkInfo info) {
2058 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2059 }
2060
Wink Saville628b0852011-08-04 15:01:58 -07002061 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002062 if (mLockdownTracker != null) {
2063 info = mLockdownTracker.augmentNetworkInfo(info);
2064 }
2065
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002066 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002067 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002068 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 if (info.isFailover()) {
2070 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2071 info.setFailover(false);
2072 }
2073 if (info.getReason() != null) {
2074 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2075 }
2076 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002077 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2078 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002080 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002081 return intent;
2082 }
2083
2084 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2085 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2086 }
2087
2088 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2089 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091
Haoyu Baidb3c8672012-06-20 14:29:57 -07002092 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2093 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2094 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2095 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002096 final long ident = Binder.clearCallingIdentity();
2097 try {
2098 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2099 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2100 } finally {
2101 Binder.restoreCallingIdentity(ident);
2102 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002103 }
2104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 /**
2106 * Called when an attempt to fail over to another network has failed.
2107 * @param info the {@link NetworkInfo} for the failed network
2108 */
2109 private void handleConnectionFailure(NetworkInfo info) {
2110 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111
Robert Greenwalt42acef32009-08-12 16:08:25 -07002112 String reason = info.getReason();
2113 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002114
Robert Greenwalt572172b2010-10-08 16:35:52 -07002115 String reasonText;
2116 if (reason == null) {
2117 reasonText = ".";
2118 } else {
2119 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002121 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002122
2123 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002124 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002125 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07002126 if (getActiveNetworkInfo() == null) {
2127 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2128 }
2129 if (reason != null) {
2130 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2131 }
2132 if (extraInfo != null) {
2133 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2134 }
2135 if (info.isFailover()) {
2136 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2137 info.setFailover(false);
2138 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002139
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002140 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002141 tryFailover(info.getType());
2142 if (mActiveDefaultNetwork != -1) {
2143 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002144 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2145 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07002146 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002147 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2148 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002149 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002150
Robert Greenwalt029be812010-09-20 18:01:43 -07002151 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07002152
2153 final Intent immediateIntent = new Intent(intent);
2154 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2155 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002156 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002157 /*
2158 * If the failover network is already connected, then immediately send
2159 * out a followup broadcast indicating successful failover
2160 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002161 if (mActiveDefaultNetwork != -1) {
2162 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002163 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002164 }
2165
2166 private void sendStickyBroadcast(Intent intent) {
2167 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002168 if (!mSystemReady) {
2169 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002170 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002171 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07002172 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002173 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002174 }
2175
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002176 final long ident = Binder.clearCallingIdentity();
2177 try {
2178 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2179 } finally {
2180 Binder.restoreCallingIdentity(ident);
2181 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002182 }
2183 }
2184
Wink Saville628b0852011-08-04 15:01:58 -07002185 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2186 if (delayMs <= 0) {
2187 sendStickyBroadcast(intent);
2188 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002189 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002190 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2191 + intent.getAction());
2192 }
Wink Saville628b0852011-08-04 15:01:58 -07002193 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2194 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2195 }
2196 }
2197
Mike Lockwood0f79b542009-08-14 14:18:49 -04002198 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07002199 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2200 loadGlobalProxy();
2201
Mike Lockwood0f79b542009-08-14 14:18:49 -04002202 synchronized(this) {
2203 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002204 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002205 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002206 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002207 }
2208 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002209 // load the global proxy at startup
2210 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002211
2212 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2213 // for user to unlock device.
2214 if (!updateLockdownVpn()) {
2215 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2216 mContext.registerReceiver(mUserPresentReceiver, filter);
2217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
2219
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002220 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2221 @Override
2222 public void onReceive(Context context, Intent intent) {
2223 // Try creating lockdown tracker, since user present usually means
2224 // unlocked keystore.
2225 if (updateLockdownVpn()) {
2226 mContext.unregisterReceiver(this);
2227 }
2228 }
2229 };
2230
Irfan Sheriffda6da092012-08-16 12:49:23 -07002231 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville948282b2013-08-29 08:55:16 -07002232 if (((type != mNetworkPreference)
2233 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2234 || (mNetworkPreference == mActiveDefaultNetwork)) {
2235 return false;
2236 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002237 return true;
2238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239
Irfan Sheriffda6da092012-08-16 12:49:23 -07002240 private void handleConnect(NetworkInfo info) {
2241 final int newNetType = info.getType();
2242
2243 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 // snapshot isFailover, because sendConnectedBroadcast() resets it
2246 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002247 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002248 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249
Wink Saville948282b2013-08-29 08:55:16 -07002250 if (VDBG) {
2251 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2252 + " isFailover" + isFailover);
2253 }
2254
Robert Greenwalt42acef32009-08-12 16:08:25 -07002255 // if this is a default net and other default is running
2256 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002257 if (mNetConfigs[newNetType].isDefault()) {
2258 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2259 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002260 // tear down the other
2261 NetworkStateTracker otherNet =
2262 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002263 if (DBG) {
2264 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002265 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002266 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002267 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002268 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002269 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002270 return;
2271 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002272 } else {
2273 // don't accept this one
2274 if (VDBG) {
2275 log("Not broadcasting CONNECT_ACTION " +
2276 "to torn down network " + info.getTypeName());
2277 }
2278 teardown(thisNet);
2279 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002280 }
2281 }
2282 synchronized (ConnectivityService.this) {
2283 // have a new default network, release the transition wakelock in a second
2284 // if it's held. The second pause is to allow apps to reconnect over the
2285 // new network
2286 if (mNetTransitionWakeLock.isHeld()) {
2287 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002288 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002289 mNetTransitionWakeLockSerialNumber, 0),
2290 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002291 }
2292 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002293 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002294 // this will cause us to come up initially as unconnected and switching
2295 // to connected after our normal pause unless somebody reports us as reall
2296 // disconnected
2297 mDefaultInetConditionPublished = 0;
2298 mDefaultConnectionSequence++;
2299 mInetConditionChangeInFlight = false;
2300 // Don't do this - if we never sign in stay, grey
2301 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002304 updateNetworkSettings(thisNet);
sy.yun9d9b74a2013-09-02 05:24:09 +09002305 updateMtuSizeSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002306 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002307 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002308
2309 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002310 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002311 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002312 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002313 } catch (RemoteException e) {
2314 // ignored; service lives in system_server
2315 }
2316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
2318
Irfan Sheriffda6da092012-08-16 12:49:23 -07002319 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2320 if (DBG) log("Captive portal check " + info);
2321 int type = info.getType();
2322 final NetworkStateTracker thisNet = mNetTrackers[type];
2323 if (mNetConfigs[type].isDefault()) {
2324 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2325 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2326 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002327 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002328 return;
2329 } else {
2330 if (DBG) log("Tear down low priority net " + info.getTypeName());
2331 teardown(thisNet);
2332 return;
2333 }
2334 }
2335 }
2336
Wink Savilled747cbc2013-08-07 16:22:47 -07002337 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002338 thisNet.captivePortalCheckComplete();
2339 }
2340
2341 /** @hide */
Wink Savilled747cbc2013-08-07 16:22:47 -07002342 @Override
Irfan Sheriffda6da092012-08-16 12:49:23 -07002343 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002344 enforceConnectivityInternalPermission();
Wink Savilled747cbc2013-08-07 16:22:47 -07002345 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002346 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002347 }
2348
Wink Savilled747cbc2013-08-07 16:22:47 -07002349 /** @hide */
2350 @Override
2351 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2352 enforceConnectivityInternalPermission();
2353 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2354 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2355 }
2356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002358 * Setup data activity tracking for the given network interface.
2359 *
2360 * Every {@code setupDataActivityTracking} should be paired with a
2361 * {@link removeDataActivityTracking} for cleanup.
2362 */
2363 private void setupDataActivityTracking(int type) {
2364 final NetworkStateTracker thisNet = mNetTrackers[type];
2365 final String iface = thisNet.getLinkProperties().getInterfaceName();
2366
2367 final int timeout;
2368
2369 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002370 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2371 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002372 0);
2373 // Canonicalize mobile network type
2374 type = ConnectivityManager.TYPE_MOBILE;
2375 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002376 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2377 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002378 0);
2379 } else {
2380 // do not track any other networks
2381 timeout = 0;
2382 }
2383
2384 if (timeout > 0 && iface != null) {
2385 try {
2386 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2387 } catch (RemoteException e) {
2388 }
2389 }
2390 }
2391
2392 /**
2393 * Remove data activity tracking when network disconnects.
2394 */
2395 private void removeDataActivityTracking(int type) {
2396 final NetworkStateTracker net = mNetTrackers[type];
2397 final String iface = net.getLinkProperties().getInterfaceName();
2398
2399 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2400 ConnectivityManager.TYPE_WIFI == type)) {
2401 try {
2402 // the call fails silently if no idletimer setup for this interface
2403 mNetd.removeIdleTimer(iface);
2404 } catch (RemoteException e) {
2405 }
2406 }
2407 }
2408
2409 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002410 * After a change in the connectivity state of a network. We're mainly
2411 * concerned with making sure that the list of DNS servers is set up
2412 * according to which networks are connected, and ensuring that the
2413 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002415 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002416 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubakerf336d722013-07-15 16:34:04 -07002417 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville948282b2013-08-29 08:55:16 -07002418 if (VDBG) {
2419 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2420 + " resetMask=" + resetMask);
2421 }
Wink Savillee8222252011-07-13 13:44:13 -07002422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002424 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002425 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002427 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002428
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002429 LinkProperties curLp = mCurrentLinkProperties[netType];
2430 LinkProperties newLp = null;
2431
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002432 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002433 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002434 if (VDBG) {
2435 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2436 " doReset=" + doReset + " resetMask=" + resetMask +
2437 "\n curLp=" + curLp +
2438 "\n newLp=" + newLp);
2439 }
2440
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002441 if (curLp != null) {
2442 if (curLp.isIdenticalInterfaceName(newLp)) {
2443 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2444 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2445 for (LinkAddress linkAddr : car.removed) {
2446 if (linkAddr.getAddress() instanceof Inet4Address) {
2447 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2448 }
2449 if (linkAddr.getAddress() instanceof Inet6Address) {
2450 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2451 }
Wink Savillee8222252011-07-13 13:44:13 -07002452 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002453 if (DBG) {
2454 log("handleConnectivityChange: addresses changed" +
2455 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2456 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002457 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002458 } else {
2459 if (DBG) {
2460 log("handleConnectivityChange: address are the same reset per doReset" +
2461 " linkProperty[" + netType + "]:" +
2462 " resetMask=" + resetMask);
2463 }
Wink Savillee8222252011-07-13 13:44:13 -07002464 }
2465 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002466 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002467 if (DBG) {
2468 log("handleConnectivityChange: interface not not equivalent reset both" +
2469 " linkProperty[" + netType + "]:" +
2470 " resetMask=" + resetMask);
2471 }
Wink Savillee8222252011-07-13 13:44:13 -07002472 }
Wink Savillee8222252011-07-13 13:44:13 -07002473 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002474 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002475 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002476 }
2477 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002478 if (VDBG) {
2479 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2480 " doReset=" + doReset + " resetMask=" + resetMask +
2481 "\n curLp=" + curLp +
2482 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002485 mCurrentLinkProperties[netType] = newLp;
Chad Brubakerf336d722013-07-15 16:34:04 -07002486 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwaltec896c62011-06-15 12:22:07 -07002487
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002488 if (resetMask != 0 || resetDns) {
Wink Saville948282b2013-08-29 08:55:16 -07002489 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002490 if (curLp != null) {
Wink Saville948282b2013-08-29 08:55:16 -07002491 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002492 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002493 if (TextUtils.isEmpty(iface) == false) {
2494 if (resetMask != 0) {
2495 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2496 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002497
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002498 // Tell VPN the interface is down. It is a temporary
2499 // but effective fix to make VPN aware of the change.
2500 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002501 synchronized(mVpns) {
2502 for (int i = 0; i < mVpns.size(); i++) {
2503 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2504 }
2505 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002506 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002507 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002508 if (resetDns) {
2509 flushVmDnsCache();
2510 if (VDBG) log("resetting DNS cache for " + iface);
2511 try {
2512 mNetd.flushInterfaceDnsCache(iface);
2513 } catch (Exception e) {
2514 // never crash - catch them all
2515 if (DBG) loge("Exception resetting dns cache: " + e);
2516 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002517 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002518 } else {
2519 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002520 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002521 }
2522 }
2523 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002524
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002525 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002526 NetworkStateTracker tracker = mNetTrackers[netType];
2527 if (mClat.requiresClat(netType, tracker)) {
Wink Saville948282b2013-08-29 08:55:16 -07002528
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002529 // If the connection was previously using clat, but is not using it now, stop the clat
2530 // daemon. Normally, this happens automatically when the connection disconnects, but if
2531 // the disconnect is not reported, or if the connection's LinkProperties changed for
2532 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2533 // still be running. If it's not running, then stopping it is a no-op.
2534 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2535 mClat.stopClat();
2536 }
2537 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002538 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2539 mClat.startClat(tracker);
2540 } else {
2541 mClat.stopClat();
2542 }
2543 }
2544
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002545 // TODO: Temporary notifying upstread change to Tethering.
2546 // @see bug/4455071
2547 /** Notify TetheringService if interface name has been changed. */
2548 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002549 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002550 if (isTetheringSupported()) {
2551 mTethering.handleTetherIfaceChange();
2552 }
2553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
2555
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002556 /**
2557 * Add and remove routes using the old properties (null if not previously connected),
2558 * new properties (null if becoming disconnected). May even be double null, which
2559 * is a noop.
2560 * Uses isLinkDefault to determine if default routes should be set or conversely if
2561 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002562 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002563 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002564 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubakerf336d722013-07-15 16:34:04 -07002565 boolean isLinkDefault, boolean exempt) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002566 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002567 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2568 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002569 if (curLp != null) {
2570 // check for the delta between the current set and the new
Lorenzo Colittid1e0fae2013-07-31 23:23:21 +09002571 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002572 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002573 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002574 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002575 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002576 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002577
Robert Greenwaltf125a092011-08-15 12:31:55 -07002578 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2579
Robert Greenwaltad55d352011-07-22 11:55:33 -07002580 for (RouteInfo r : routeDiff.removed) {
2581 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville948282b2013-08-29 08:55:16 -07002582 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002583 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2584 }
2585 if (isLinkDefault == false) {
2586 // remove from a secondary route table
2587 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002588 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002589 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002590
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002591 if (!isLinkDefault) {
2592 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002593 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002594 // routes changed - remove all old dns entries and add new
2595 if (curLp != null) {
2596 for (InetAddress oldDns : curLp.getDnses()) {
2597 removeRouteToAddress(curLp, oldDns);
2598 }
2599 }
2600 if (newLp != null) {
2601 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002602 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002603 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002604 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002605 } else {
2606 // no change in routes, check for change in dns themselves
2607 for (InetAddress oldDns : dnsDiff.removed) {
2608 removeRouteToAddress(curLp, oldDns);
2609 }
2610 for (InetAddress newDns : dnsDiff.added) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002611 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002612 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002613 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002614 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002615
2616 for (RouteInfo r : routeDiff.added) {
2617 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002618 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002619 } else {
2620 // add to a secondary route table
Chad Brubakerf336d722013-07-15 16:34:04 -07002621 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002622
2623 // many radios add a default route even when we don't want one.
2624 // remove the default route unless somebody else has asked for it
2625 String ifaceName = newLp.getInterfaceName();
Chad Brubakerf336d722013-07-15 16:34:04 -07002626 synchronized (mRoutesLock) {
2627 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2628 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2629 try {
2630 mNetd.removeRoute(ifaceName, r);
2631 } catch (Exception e) {
2632 // never crash - catch them all
2633 if (DBG) loge("Exception trying to remove a route: " + e);
2634 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002635 }
2636 }
2637 }
2638 }
2639
Robert Greenwaltf125a092011-08-15 12:31:55 -07002640 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002641 }
2642
sy.yun9d9b74a2013-09-02 05:24:09 +09002643 /**
2644 * Reads the network specific MTU size from reources.
2645 * and set it on it's iface.
2646 */
2647 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2648 final String iface = nt.getLinkProperties().getInterfaceName();
2649 final int mtu = nt.getLinkProperties().getMtu();
2650
2651 if (mtu < 68 || mtu > 10000) {
2652 loge("Unexpected mtu value: " + nt);
2653 return;
2654 }
2655
2656 try {
2657 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2658 mNetd.setMtu(iface, mtu);
2659 } catch (Exception e) {
2660 Slog.e(TAG, "exception in setMtu()" + e);
2661 }
2662 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002663
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002664 /**
Irfan Sheriffd649c122010-06-09 15:39:36 -07002665 * Reads the network specific TCP buffer sizes from SystemProperties
2666 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2667 * wide use
2668 */
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002669 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002670 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002671 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002672
Jeff Sharkey899223b2012-08-04 15:24:58 -07002673 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002674 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002675
2676 // Setting to default values so we won't be stuck to previous values
2677 key = "net.tcp.buffersize.default";
2678 bufferSizes = SystemProperties.get(key);
2679 }
2680
2681 // Set values in kernel
2682 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002683 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002684 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002685 + "] which comes from [" + key + "]");
2686 }
2687 setBufferSize(bufferSizes);
2688 }
2689 }
2690
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002691 /**
Irfan Sheriffd649c122010-06-09 15:39:36 -07002692 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2693 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2694 *
2695 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2696 * writeMin, writeInitial, writeMax"
2697 */
2698 private void setBufferSize(String bufferSizes) {
2699 try {
2700 String[] values = bufferSizes.split(",");
2701
2702 if (values.length == 6) {
2703 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002704 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2705 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2706 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2707 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2708 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2709 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002710 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002711 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002712 }
2713 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002714 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002715 }
2716 }
2717
Robert Greenwalt42acef32009-08-12 16:08:25 -07002718 /**
2719 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2720 * on the highest priority active net which this process requested.
2721 * If there aren't any, clear it out
2722 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002723 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002724 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002725 if (VDBG) log("reassessPidDns for pid " + pid);
2726 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002727 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002728 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002729 continue;
2730 }
2731 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002732 if (nt.getNetworkInfo().isConnected() &&
2733 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002734 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002735 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002736 if (mNetRequestersPids[i].contains(myPid)) {
2737 try {
2738 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2739 } catch (Exception e) {
2740 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002741 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002742 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002743 }
2744 }
2745 }
2746 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002747 try {
2748 mNetd.clearDnsInterfaceForPid(pid);
2749 } catch (Exception e) {
2750 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002751 }
2752 }
2753
Mattias Falk8b47b362011-08-23 14:15:13 +02002754 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002755 /*
2756 * Tell the VMs to toss their DNS caches
2757 */
2758 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2759 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002760 /*
2761 * Connectivity events can happen before boot has completed ...
2762 */
2763 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002764 final long ident = Binder.clearCallingIdentity();
2765 try {
2766 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002770 }
2771
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002772 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002773 private void updateDnsLocked(String network, String iface,
Chad Brubaker20a7e882013-07-23 17:13:36 -07002774 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002775 int last = 0;
2776 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002777 dnses = new ArrayList();
2778 dnses.add(mDefaultDns);
2779 if (DBG) {
2780 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002781 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002782 }
2783
Mattias Falk8b47b362011-08-23 14:15:13 +02002784 try {
2785 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker20a7e882013-07-23 17:13:36 -07002786 if (defaultDns) {
2787 mNetd.setDefaultInterfaceForDns(iface);
2788 }
2789
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002790 for (InetAddress dns : dnses) {
2791 ++last;
2792 String key = "net.dns" + last;
2793 String value = dns.getHostAddress();
2794 SystemProperties.set(key, value);
2795 }
2796 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2797 String key = "net.dns" + i;
2798 SystemProperties.set(key, "");
2799 }
2800 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002801 } catch (Exception e) {
Robert Greenwalt69887e82013-09-24 11:05:57 -07002802 loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002803 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002804 }
2805
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002806 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002807 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002808 NetworkStateTracker nt = mNetTrackers[netType];
2809 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002810 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002811 if (p == null) return;
2812 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002813 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002814 String network = nt.getNetworkInfo().getTypeName();
2815 synchronized (mDnsLock) {
Chad Brubakerb98703e2013-07-23 17:44:41 -07002816 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002817 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002818 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002819 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002820 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002821 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002822 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002823 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002824 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002825 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002826 List<Integer> pids = mNetRequestersPids[netType];
2827 for (Integer pid : pids) {
2828 try {
2829 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2830 } catch (Exception e) {
2831 Slog.e(TAG, "exception setting interface for pid: " + e);
2832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 }
2834 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002835 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002837 }
2838
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002839 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002840 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2841 NETWORK_RESTORE_DELAY_PROP_NAME);
2842 if(restoreDefaultNetworkDelayStr != null &&
2843 restoreDefaultNetworkDelayStr.length() != 0) {
2844 try {
2845 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2846 } catch (NumberFormatException e) {
2847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002849 // if the system property isn't set, use the value for the apn type
2850 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2851
2852 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2853 (mNetConfigs[networkType] != null)) {
2854 ret = mNetConfigs[networkType].restoreTime;
2855 }
2856 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858
2859 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002860 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2861 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002862 if (mContext.checkCallingOrSelfPermission(
2863 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002865 pw.println("Permission Denial: can't dump ConnectivityService " +
2866 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2867 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 return;
2869 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002870
2871 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002873 for (int i = 0; i < mNetTrackers.length; i++) {
2874 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002875 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002876 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2877 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002878 if (nst.getNetworkInfo().isConnected()) {
2879 pw.println("Active network: " + nst.getNetworkInfo().
2880 getTypeName());
2881 }
2882 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002883 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002884 pw.println(nst);
2885 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002886 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002889
2890 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002891 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002892 for (int net : mPriorityList) {
2893 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002894 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002895 pidString = pidString + pid.toString() + ", ";
2896 }
2897 pw.println(pidString);
2898 }
2899 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002900 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002901
2902 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002903 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002904 for (Object requester : mFeatureUsers) {
2905 pw.println(requester.toString());
2906 }
2907 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002908 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002909
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002910 synchronized (this) {
2911 pw.println("NetworkTranstionWakeLock is currently " +
2912 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2913 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2914 }
2915 pw.println();
2916
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002917 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002918
2919 if (mInetLog != null) {
2920 pw.println();
2921 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002922 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002923 for(int i = 0; i < mInetLog.size(); i++) {
2924 pw.println(mInetLog.get(i));
2925 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002926 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929
Robert Greenwalt42acef32009-08-12 16:08:25 -07002930 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002931 private class NetworkStateTrackerHandler extends Handler {
2932 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002933 super(looper);
2934 }
2935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 @Override
2937 public void handleMessage(Message msg) {
2938 NetworkInfo info;
2939 switch (msg.what) {
Wink Saville948282b2013-08-29 08:55:16 -07002940 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002942 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002943
Wink Savillec9acde92011-09-21 11:05:43 -07002944 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville67c38212013-09-05 12:02:25 -07002945 (state == NetworkInfo.State.DISCONNECTED) ||
2946 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillec9acde92011-09-21 11:05:43 -07002947 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002948 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002949 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951
Wink Saville948282b2013-08-29 08:55:16 -07002952 // Since mobile has the notion of a network/apn that can be used for
2953 // provisioning we need to check every time we're connected as
2954 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2955 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2956 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2957 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2958 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillefde1ac92013-07-16 17:16:37 -07002959 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2960 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Saville127beff2013-09-14 09:04:53 -07002961 && (((state == NetworkInfo.State.CONNECTED)
2962 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2963 || info.isConnectedToProvisioningNetwork())) {
2964 log("ConnectivityChange checkMobileProvisioning for"
2965 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville948282b2013-08-29 08:55:16 -07002966 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillefde1ac92013-07-16 17:16:37 -07002967 }
2968
Jeff Sharkey2528b502012-11-09 15:57:02 -08002969 EventLogTags.writeConnectivityStateChanged(
2970 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002971
2972 if (info.getDetailedState() ==
2973 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002975 } else if (info.getDetailedState() ==
2976 DetailedState.CAPTIVE_PORTAL_CHECK) {
2977 handleCaptivePortalTrackerCheck(info);
Wink Saville67c38212013-09-05 12:02:25 -07002978 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -07002979 /**
2980 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2981 * for now its an in between network, its a network that
2982 * is actually a default network but we don't want it to be
2983 * announced as such to keep background applications from
2984 * trying to use it. It turns out that some still try so we
2985 * take the additional step of clearing any default routes
2986 * to the link that may have incorrectly setup by the lower
2987 * levels.
2988 */
2989 LinkProperties lp = getLinkProperties(info.getType());
2990 if (DBG) {
2991 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2992 }
2993
2994 // Clear any default routes setup by the radio so
2995 // any activity by applications trying to use this
2996 // connection will fail until the provisioning network
2997 // is enabled.
2998 for (RouteInfo r : lp.getRoutes()) {
2999 removeRoute(lp, r, TO_DEFAULT_TABLE);
3000 }
Robert Greenwalt511288a2009-12-07 11:33:18 -08003001 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08003003 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07003005 // the logic here is, handle SUSPENDED the same as
3006 // DISCONNECTED. The only difference being we are
3007 // broadcasting an intent with NetworkInfo that's
3008 // suspended. This allows the applications an
3009 // opportunity to handle DISCONNECTED and SUSPENDED
3010 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08003012 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 handleConnect(info);
3014 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003015 if (mLockdownTracker != null) {
3016 mLockdownTracker.onNetworkInfoChanged(info);
3017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 break;
Wink Saville948282b2013-08-29 08:55:16 -07003019 }
3020 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07003021 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05003022 // TODO: Temporary allowing network configuration
3023 // change not resetting sockets.
3024 // @see bug/4455071
3025 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 break;
Wink Saville948282b2013-08-29 08:55:16 -07003027 }
3028 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltd14e1762012-08-20 11:15:39 -07003029 info = (NetworkInfo) msg.obj;
Wink Saville948282b2013-08-29 08:55:16 -07003030 int type = info.getType();
Robert Greenwaltd14e1762012-08-20 11:15:39 -07003031 updateNetworkSettings(mNetTrackers[type]);
3032 break;
Wink Saville948282b2013-08-29 08:55:16 -07003033 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003034 }
3035 }
3036 }
3037
3038 private class InternalHandler extends Handler {
3039 public InternalHandler(Looper looper) {
3040 super(looper);
3041 }
3042
3043 @Override
3044 public void handleMessage(Message msg) {
3045 NetworkInfo info;
3046 switch (msg.what) {
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003047 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003048 String causedBy = null;
3049 synchronized (ConnectivityService.this) {
3050 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3051 mNetTransitionWakeLock.isHeld()) {
3052 mNetTransitionWakeLock.release();
3053 causedBy = mNetTransitionWakeLockCausedBy;
3054 }
3055 }
3056 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003057 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003058 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003059 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003060 }
3061 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07003062 FeatureUser u = (FeatureUser)msg.obj;
3063 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003064 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003065 }
3066 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003067 int netType = msg.arg1;
3068 int condition = msg.arg2;
3069 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003070 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003071 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003072 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003073 int netType = msg.arg1;
3074 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00003075 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003076 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003077 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003078 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003079 int preference = msg.arg1;
3080 handleSetNetworkPreference(preference);
3081 break;
3082 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003083 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003084 boolean enabled = (msg.arg1 == ENABLED);
3085 handleSetMobileData(enabled);
3086 break;
3087 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003088 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003089 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003090 break;
3091 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003092 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003093 boolean met = (msg.arg1 == ENABLED);
3094 handleSetDependencyMet(msg.arg2, met);
3095 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003096 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003097 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07003098 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07003099 sendStickyBroadcast(intent);
3100 break;
3101 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003102 case EVENT_SET_POLICY_DATA_ENABLE: {
3103 final int networkType = msg.arg1;
3104 final boolean enabled = msg.arg2 == ENABLED;
3105 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003106 break;
3107 }
3108 case EVENT_VPN_STATE_CHANGED: {
3109 if (mLockdownTracker != null) {
3110 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3111 }
3112 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003113 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003114 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3115 int tag = mEnableFailFastMobileDataTag.get();
3116 if (msg.arg1 == tag) {
3117 MobileDataStateTracker mobileDst =
3118 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3119 if (mobileDst != null) {
3120 mobileDst.setEnableFailFastMobileData(msg.arg2);
3121 }
3122 } else {
3123 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3124 + " != tag:" + tag);
3125 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003126 break;
Wink Savilleab9321d2013-06-29 21:10:57 -07003127 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003128 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003129 handleNetworkSamplingTimeout();
3130 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003131 }
Jason Monkdecd2952013-10-10 14:02:51 -04003132 case EVENT_PROXY_HAS_CHANGED: {
3133 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3134 break;
3135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
3137 }
3138 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003139
3140 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08003141 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003142 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08003143
3144 if (isTetheringSupported()) {
3145 return mTethering.tether(iface);
3146 } else {
3147 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3148 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003149 }
3150
3151 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08003152 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003153 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08003154
3155 if (isTetheringSupported()) {
3156 return mTethering.untether(iface);
3157 } else {
3158 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3159 }
3160 }
3161
3162 // javadoc from interface
3163 public int getLastTetherError(String iface) {
3164 enforceTetherAccessPermission();
3165
3166 if (isTetheringSupported()) {
3167 return mTethering.getLastTetherError(iface);
3168 } else {
3169 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3170 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003171 }
3172
3173 // TODO - proper iface API for selection by property, inspection, etc
3174 public String[] getTetherableUsbRegexs() {
3175 enforceTetherAccessPermission();
3176 if (isTetheringSupported()) {
3177 return mTethering.getTetherableUsbRegexs();
3178 } else {
3179 return new String[0];
3180 }
3181 }
3182
3183 public String[] getTetherableWifiRegexs() {
3184 enforceTetherAccessPermission();
3185 if (isTetheringSupported()) {
3186 return mTethering.getTetherableWifiRegexs();
3187 } else {
3188 return new String[0];
3189 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003190 }
3191
Danica Chang6fdd0c62010-08-11 14:54:43 -07003192 public String[] getTetherableBluetoothRegexs() {
3193 enforceTetherAccessPermission();
3194 if (isTetheringSupported()) {
3195 return mTethering.getTetherableBluetoothRegexs();
3196 } else {
3197 return new String[0];
3198 }
3199 }
3200
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003201 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003202 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003203 if (isTetheringSupported()) {
3204 return mTethering.setUsbTethering(enable);
3205 } else {
3206 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3207 }
3208 }
3209
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003210 // TODO - move iface listing, queries, etc to new module
3211 // javadoc from interface
3212 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003213 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003214 return mTethering.getTetherableIfaces();
3215 }
3216
3217 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003218 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003219 return mTethering.getTetheredIfaces();
3220 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003221
Robert Greenwalt5a735062010-03-02 17:25:02 -08003222 public String[] getTetheringErroredIfaces() {
3223 enforceTetherAccessPermission();
3224 return mTethering.getErroredIfaces();
3225 }
3226
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003227 // if ro.tether.denied = true we default to no tethering
3228 // gservices could set the secure setting to 1 though to enable it on a build where it
3229 // had previously been turned off.
3230 public boolean isTetheringSupported() {
3231 enforceTetherAccessPermission();
3232 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003233 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3234 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003235 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3236 mTethering.getTetherableWifiRegexs().length != 0 ||
3237 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3238 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003239 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003240
3241 // An API NetworkStateTrackers can call when they lose their network.
3242 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3243 // whichever happens first. The timer is started by the first caller and not
3244 // restarted by subsequent callers.
3245 public void requestNetworkTransitionWakelock(String forWhom) {
3246 enforceConnectivityInternalPermission();
3247 synchronized (this) {
3248 if (mNetTransitionWakeLock.isHeld()) return;
3249 mNetTransitionWakeLockSerialNumber++;
3250 mNetTransitionWakeLock.acquire();
3251 mNetTransitionWakeLockCausedBy = forWhom;
3252 }
3253 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003254 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003255 mNetTransitionWakeLockSerialNumber, 0),
3256 mNetTransitionWakeLockTimeout);
3257 return;
3258 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003259
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003260 // 100 percent is full good, 0 is full bad.
3261 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003262 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003263 mContext.enforceCallingOrSelfPermission(
3264 android.Manifest.permission.STATUS_BAR,
3265 "ConnectivityService");
3266
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003267 if (DBG) {
3268 int pid = getCallingPid();
3269 int uid = getCallingUid();
3270 String s = pid + "(" + uid + ") reports inet is " +
3271 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3272 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3273 mInetLog.add(s);
3274 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3275 mInetLog.remove(0);
3276 }
3277 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003278 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003279 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3280 }
3281
3282 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003283 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003284 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003285 return;
3286 }
3287 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003288 if (DBG) log("handleInetConditionChange: net=" + netType +
3289 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003290 return;
3291 }
Wink Savillec9acde92011-09-21 11:05:43 -07003292 if (VDBG) {
3293 log("handleInetConditionChange: net=" +
3294 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003295 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003296 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003297 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003298 int delay;
3299 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003300 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003301 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003302 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003303 delay = Settings.Global.getInt(mContext.getContentResolver(),
3304 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003305 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003306 delay = Settings.Global.getInt(mContext.getContentResolver(),
3307 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003308 }
3309 mInetConditionChangeInFlight = true;
3310 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003311 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003312 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003313 // we've set the new condition, when this hold ends that will get picked up
3314 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003315 }
3316 }
3317
Wink Saville5b7573e2013-01-31 00:30:13 +00003318 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003319 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003320 log("handleInetConditionHoldEnd: net=" + netType +
3321 ", condition=" + mDefaultInetCondition +
3322 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003323 }
3324 mInetConditionChangeInFlight = false;
3325
3326 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003327 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003328 return;
3329 }
3330 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003331 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003332 return;
3333 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003334 // TODO: Figure out why this optimization sometimes causes a
3335 // change in mDefaultInetCondition to be missed and the
3336 // UI to not be updated.
3337 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3338 // if (DBG) log("no change in condition - aborting");
3339 // return;
3340 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003341 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3342 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003343 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003344 return;
3345 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003346 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003347 sendInetConditionBroadcast(networkInfo);
3348 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003349 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003351 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003352 // this information is already available as a world read/writable jvm property
3353 // so this API change wouldn't have a benifit. It also breaks the passing
3354 // of proxy info to all the JVMs.
3355 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003356 synchronized (mProxyLock) {
Jason Monk602b2322013-07-03 17:04:33 -04003357 ProxyProperties ret = mGlobalProxy;
3358 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3359 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003360 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003361 }
3362
3363 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003364 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003365
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003366 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003367 if (proxyProperties == mGlobalProxy) return;
3368 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3369 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3370
3371 String host = "";
3372 int port = 0;
3373 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003374 String pacFileUrl = "";
3375 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3376 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003377 mGlobalProxy = new ProxyProperties(proxyProperties);
3378 host = mGlobalProxy.getHost();
3379 port = mGlobalProxy.getPort();
3380 exclList = mGlobalProxy.getExclusionList();
Jason Monk602b2322013-07-03 17:04:33 -04003381 if (proxyProperties.getPacFileUrl() != null) {
3382 pacFileUrl = proxyProperties.getPacFileUrl();
3383 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003384 } else {
3385 mGlobalProxy = null;
3386 }
3387 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003388 final long token = Binder.clearCallingIdentity();
3389 try {
3390 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3391 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3392 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3393 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003394 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003395 } finally {
3396 Binder.restoreCallingIdentity(token);
3397 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003398 }
3399
3400 if (mGlobalProxy == null) {
3401 proxyProperties = mDefaultProxy;
3402 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003403 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003404 }
3405
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003406 private void loadGlobalProxy() {
3407 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003408 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3409 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3410 String exclList = Settings.Global.getString(res,
3411 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003412 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3413 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3414 ProxyProperties proxyProperties;
3415 if (!TextUtils.isEmpty(pacFileUrl)) {
3416 proxyProperties = new ProxyProperties(pacFileUrl);
3417 } else {
3418 proxyProperties = new ProxyProperties(host, port, exclList);
3419 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003420 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003421 mGlobalProxy = proxyProperties;
3422 }
3423 }
3424 }
3425
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003427 // this information is already available as a world read/writable jvm property
3428 // so this API change wouldn't have a benifit. It also breaks the passing
3429 // of proxy info to all the JVMs.
3430 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003431 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003432 return mGlobalProxy;
3433 }
3434 }
3435
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003436 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003437 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3438 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003439 proxy = null;
3440 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003441 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003443 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003444 mDefaultProxy = proxy;
3445
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003446 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003447 if (!mDefaultProxyDisabled) {
3448 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003449 }
3450 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003451 }
3452
3453 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003454 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3455 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 if (!TextUtils.isEmpty(proxy)) {
3457 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003458 if (data.length == 0) {
3459 return;
3460 }
3461
Robert Greenwalt434203a2010-10-11 16:00:27 -07003462 String proxyHost = data[0];
3463 int proxyPort = 8080;
3464 if (data.length > 1) {
3465 try {
3466 proxyPort = Integer.parseInt(data[1]);
3467 } catch (NumberFormatException e) {
3468 return;
3469 }
3470 }
3471 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3472 setGlobalProxy(p);
3473 }
3474 }
3475
3476 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003477 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003478 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003479 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003480 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003481 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3482 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003483 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003484 final long ident = Binder.clearCallingIdentity();
3485 try {
3486 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3487 } finally {
3488 Binder.restoreCallingIdentity(ident);
3489 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003490 }
3491
3492 private static class SettingsObserver extends ContentObserver {
3493 private int mWhat;
3494 private Handler mHandler;
3495 SettingsObserver(Handler handler, int what) {
3496 super(handler);
3497 mHandler = handler;
3498 mWhat = what;
3499 }
3500
3501 void observe(Context context) {
3502 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003503 resolver.registerContentObserver(Settings.Global.getUriFor(
3504 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003505 }
3506
3507 @Override
3508 public void onChange(boolean selfChange) {
3509 mHandler.obtainMessage(mWhat).sendToTarget();
3510 }
3511 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003512
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003513 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003514 Slog.d(TAG, s);
3515 }
3516
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003517 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003518 Slog.e(TAG, s);
3519 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003520
repo syncaea743a2011-07-29 23:55:49 -07003521 int convertFeatureToNetworkType(int networkType, String feature) {
3522 int usedNetworkType = networkType;
3523
3524 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3525 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3526 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3527 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3528 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3529 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3530 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3531 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3532 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3533 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3534 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3535 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3536 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3537 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3538 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3539 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3540 } else {
3541 Slog.e(TAG, "Can't match any mobile netTracker!");
3542 }
3543 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3544 if (TextUtils.equals(feature, "p2p")) {
3545 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3546 } else {
3547 Slog.e(TAG, "Can't match any wifi netTracker!");
3548 }
3549 } else {
3550 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003551 }
repo syncaea743a2011-07-29 23:55:49 -07003552 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003553 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003554
3555 private static <T> T checkNotNull(T value, String message) {
3556 if (value == null) {
3557 throw new NullPointerException(message);
3558 }
3559 return value;
3560 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003561
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003562 /**
3563 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003564 * VpnBuilder and not available in ConnectivityManager. Permissions
3565 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003566 * @hide
3567 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003568 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003569 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003570 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003571 try {
3572 int type = mActiveDefaultNetwork;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003573 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003574 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003575 synchronized(mVpns) {
3576 mVpns.get(user).protect(socket,
3577 mNetTrackers[type].getLinkProperties().getInterfaceName());
3578 }
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003579 return true;
3580 }
3581 } catch (Exception e) {
3582 // ignore
3583 } finally {
3584 try {
3585 socket.close();
3586 } catch (Exception e) {
3587 // ignore
3588 }
3589 }
3590 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003591 }
3592
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003593 /**
3594 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003595 * and not available in ConnectivityManager. Permissions are checked
3596 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003597 * @hide
3598 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003599 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003600 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003601 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003602 int user = UserHandle.getUserId(Binder.getCallingUid());
3603 synchronized(mVpns) {
3604 return mVpns.get(user).prepare(oldPackage, newPackage);
3605 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003606 }
3607
Chad Brubakerd475c702013-07-11 13:29:30 -07003608 @Override
3609 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3610 enforceMarkNetworkSocketPermission();
3611 final long token = Binder.clearCallingIdentity();
3612 try {
3613 int mark = mNetd.getMarkForUid(uid);
3614 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3615 if (mark == -1) {
3616 mark = 0;
3617 }
3618 NetworkUtils.markSocket(socket.getFd(), mark);
3619 } catch (RemoteException e) {
3620 } finally {
3621 Binder.restoreCallingIdentity(token);
3622 }
3623 }
3624
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003625 /**
3626 * Configure a TUN interface and return its file descriptor. Parameters
3627 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003628 * and not available in ConnectivityManager. Permissions are checked in
3629 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003630 * @hide
3631 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003632 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003633 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003634 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003635 int user = UserHandle.getUserId(Binder.getCallingUid());
3636 synchronized(mVpns) {
3637 return mVpns.get(user).establish(config);
3638 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003639 }
3640
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003641 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003642 * Start legacy VPN, controlling native daemons as needed. Creates a
3643 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003644 */
3645 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003646 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003647 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003648 final LinkProperties egress = getActiveLinkProperties();
3649 if (egress == null) {
3650 throw new IllegalStateException("Missing active network connection");
3651 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003652 int user = UserHandle.getUserId(Binder.getCallingUid());
3653 synchronized(mVpns) {
3654 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3655 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003656 }
3657
3658 /**
3659 * Return the information of the ongoing legacy VPN. This method is used
3660 * by VpnSettings and not available in ConnectivityManager. Permissions
3661 * are checked in Vpn class.
3662 * @hide
3663 */
3664 @Override
3665 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003666 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003667 int user = UserHandle.getUserId(Binder.getCallingUid());
3668 synchronized(mVpns) {
3669 return mVpns.get(user).getLegacyVpnInfo();
3670 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003671 }
3672
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003673 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003674 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3675 * not available in ConnectivityManager.
3676 * Permissions are checked in Vpn class.
3677 * @hide
3678 */
3679 @Override
3680 public VpnConfig getVpnConfig() {
3681 int user = UserHandle.getUserId(Binder.getCallingUid());
3682 synchronized(mVpns) {
3683 return mVpns.get(user).getVpnConfig();
3684 }
3685 }
3686
3687 /**
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003688 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3689 * through NetworkStateTracker since it works differently. For example, it
3690 * needs to override DNS servers but never takes the default routes. It
3691 * relies on another data network, and it could keep existing connections
3692 * alive after reconnecting, switching between networks, or even resuming
3693 * from deep sleep. Calls from applications should be done synchronously
3694 * to avoid race conditions. As these are all hidden APIs, refactoring can
3695 * be done whenever a better abstraction is developed.
3696 */
3697 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003698 private VpnCallback() {
3699 }
3700
Jeff Sharkey899223b2012-08-04 15:24:58 -07003701 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003702 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003703 }
3704
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003705 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003706 if (dnsServers == null) {
3707 restore();
3708 return;
3709 }
3710
3711 // Convert DNS servers into addresses.
3712 List<InetAddress> addresses = new ArrayList<InetAddress>();
3713 for (String address : dnsServers) {
3714 // Double check the addresses and remove invalid ones.
3715 try {
3716 addresses.add(InetAddress.parseNumericAddress(address));
3717 } catch (Exception e) {
3718 // ignore
3719 }
3720 }
3721 if (addresses.isEmpty()) {
3722 restore();
3723 return;
3724 }
3725
3726 // Concatenate search domains into a string.
3727 StringBuilder buffer = new StringBuilder();
3728 if (searchDomains != null) {
3729 for (String domain : searchDomains) {
3730 buffer.append(domain).append(' ');
3731 }
3732 }
3733 String domains = buffer.toString().trim();
3734
3735 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003736 synchronized (mDnsLock) {
Chad Brubaker20a7e882013-07-23 17:13:36 -07003737 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003738 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003739
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003740 // Temporarily disable the default proxy (not global).
3741 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003742 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003743 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003744 sendProxyBroadcast(null);
3745 }
3746 }
3747
3748 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003749 }
3750
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003751 public void restore() {
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003752 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003753 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003754 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003755 sendProxyBroadcast(mDefaultProxy);
3756 }
3757 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003758 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003759
3760 public void protect(ParcelFileDescriptor socket) {
3761 try {
3762 final int mark = mNetd.getMarkForProtect();
3763 NetworkUtils.markSocket(socket.getFd(), mark);
3764 } catch (RemoteException e) {
3765 }
3766 }
3767
3768 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3769 for (RouteInfo route : routes) {
3770 try {
3771 mNetd.setMarkedForwardingRoute(interfaze, route);
3772 } catch (RemoteException e) {
3773 }
3774 }
3775 }
3776
3777 public void setMarkedForwarding(String interfaze) {
3778 try {
3779 mNetd.setMarkedForwarding(interfaze);
3780 } catch (RemoteException e) {
3781 }
3782 }
3783
3784 public void clearMarkedForwarding(String interfaze) {
3785 try {
3786 mNetd.clearMarkedForwarding(interfaze);
3787 } catch (RemoteException e) {
3788 }
3789 }
3790
Robert Greenwalt69887e82013-09-24 11:05:57 -07003791 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003792 int uidStart = uid * UserHandle.PER_USER_RANGE;
3793 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt69887e82013-09-24 11:05:57 -07003794 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003795 }
3796
Robert Greenwalt69887e82013-09-24 11:05:57 -07003797 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003798 int uidStart = uid * UserHandle.PER_USER_RANGE;
3799 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt69887e82013-09-24 11:05:57 -07003800 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003801 }
3802
Robert Greenwalt69887e82013-09-24 11:05:57 -07003803 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3804 boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003805 try {
3806 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt69887e82013-09-24 11:05:57 -07003807 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003808 } catch (RemoteException e) {
3809 }
3810
3811 }
3812
Robert Greenwalt69887e82013-09-24 11:05:57 -07003813 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3814 boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003815 try {
3816 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt69887e82013-09-24 11:05:57 -07003817 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003818 } catch (RemoteException e) {
3819 }
3820
3821 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003822 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003823
3824 @Override
3825 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003826 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3827 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3828 return false;
3829 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003830
3831 // Tear down existing lockdown if profile was removed
3832 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3833 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003834 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003835 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3836 return false;
3837 }
3838
3839 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3840 final VpnProfile profile = VpnProfile.decode(
3841 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003842 int user = UserHandle.getUserId(Binder.getCallingUid());
3843 synchronized(mVpns) {
3844 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3845 profile));
3846 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003847 } else {
3848 setLockdownTracker(null);
3849 }
3850
3851 return true;
3852 }
3853
3854 /**
3855 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3856 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3857 */
3858 private void setLockdownTracker(LockdownVpnTracker tracker) {
3859 // Shutdown any existing tracker
3860 final LockdownVpnTracker existing = mLockdownTracker;
3861 mLockdownTracker = null;
3862 if (existing != null) {
3863 existing.shutdown();
3864 }
3865
3866 try {
3867 if (tracker != null) {
3868 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003869 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003870 mLockdownTracker = tracker;
3871 mLockdownTracker.init();
3872 } else {
3873 mNetd.setFirewallEnabled(false);
3874 }
3875 } catch (RemoteException e) {
3876 // ignored; NMS lives inside system_server
3877 }
3878 }
3879
3880 private void throwIfLockdownEnabled() {
3881 if (mLockdownEnabled) {
3882 throw new IllegalStateException("Unavailable in lockdown mode");
3883 }
3884 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003885
3886 public void supplyMessenger(int networkType, Messenger messenger) {
3887 enforceConnectivityInternalPermission();
3888
3889 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3890 mNetTrackers[networkType].supplyMessenger(messenger);
3891 }
3892 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003893
3894 public int findConnectionTypeForIface(String iface) {
3895 enforceConnectivityInternalPermission();
3896
3897 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3898 for (NetworkStateTracker tracker : mNetTrackers) {
3899 if (tracker != null) {
3900 LinkProperties lp = tracker.getLinkProperties();
3901 if (lp != null && iface.equals(lp.getInterfaceName())) {
3902 return tracker.getNetworkInfo().getType();
3903 }
3904 }
3905 }
3906 return ConnectivityManager.TYPE_NONE;
3907 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003908
3909 /**
3910 * Have mobile data fail fast if enabled.
3911 *
3912 * @param enabled DctConstants.ENABLED/DISABLED
3913 */
3914 private void setEnableFailFastMobileData(int enabled) {
3915 int tag;
3916
3917 if (enabled == DctConstants.ENABLED) {
3918 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3919 } else {
3920 tag = mEnableFailFastMobileDataTag.get();
3921 }
3922 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3923 enabled));
3924 }
3925
Wink Savilledce52cd2013-08-16 17:17:28 -07003926 private boolean isMobileDataStateTrackerReady() {
3927 MobileDataStateTracker mdst =
Wink Saville948282b2013-08-29 08:55:16 -07003928 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilledce52cd2013-08-16 17:17:28 -07003929 return (mdst != null) && (mdst.isReady());
3930 }
3931
Wink Saville948282b2013-08-29 08:55:16 -07003932 /**
3933 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3934 */
3935
3936 /**
3937 * No connection was possible to the network.
Wink Saville4fea0412013-09-06 09:53:08 -07003938 * This is NOT a warm sim.
Wink Saville948282b2013-08-29 08:55:16 -07003939 */
Wink Saville4fea0412013-09-06 09:53:08 -07003940 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville948282b2013-08-29 08:55:16 -07003941
3942 /**
3943 * A connection was made to the internet, all is well.
Wink Saville4fea0412013-09-06 09:53:08 -07003944 * This is NOT a warm sim.
Wink Saville948282b2013-08-29 08:55:16 -07003945 */
Wink Saville4fea0412013-09-06 09:53:08 -07003946 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville948282b2013-08-29 08:55:16 -07003947
3948 /**
3949 * A connection was made but no dns server was available to resolve a name to address.
Wink Saville4fea0412013-09-06 09:53:08 -07003950 * This is NOT a warm sim since provisioning network is supported.
Wink Saville948282b2013-08-29 08:55:16 -07003951 */
Wink Saville4fea0412013-09-06 09:53:08 -07003952 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville948282b2013-08-29 08:55:16 -07003953
3954 /**
3955 * A connection was made but could not open a TCP connection.
Wink Saville4fea0412013-09-06 09:53:08 -07003956 * This is NOT a warm sim since provisioning network is supported.
Wink Saville948282b2013-08-29 08:55:16 -07003957 */
Wink Saville4fea0412013-09-06 09:53:08 -07003958 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3959
3960 /**
3961 * A connection was made but there was a redirection, we appear to be in walled garden.
3962 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3963 */
3964 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville948282b2013-08-29 08:55:16 -07003965
3966 /**
3967 * The mobile network is a provisioning network.
Wink Saville4fea0412013-09-06 09:53:08 -07003968 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville948282b2013-08-29 08:55:16 -07003969 */
Wink Saville4fea0412013-09-06 09:53:08 -07003970 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville948282b2013-08-29 08:55:16 -07003971
Wink Saville4fea0412013-09-06 09:53:08 -07003972 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville948282b2013-08-29 08:55:16 -07003973
Wink Savilleab9321d2013-06-29 21:10:57 -07003974 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003975 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3976 int timeOutMs = -1;
3977 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3978 enforceConnectivityInternalPermission();
Wink Saville68e6c642013-07-02 10:55:14 -07003979
Wink Savilleab9321d2013-06-29 21:10:57 -07003980 final long token = Binder.clearCallingIdentity();
3981 try {
Wink Saville948282b2013-08-29 08:55:16 -07003982 timeOutMs = suggestedTimeOutMs;
3983 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3984 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3985 }
3986
3987 // Check that mobile networks are supported
3988 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3989 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3990 if (DBG) log("checkMobileProvisioning: X no mobile network");
3991 return timeOutMs;
3992 }
3993
3994 // If we're already checking don't do it again
3995 // TODO: Add a queue of results...
3996 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3997 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3998 return timeOutMs;
3999 }
4000
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004001 // Start off with mobile notification off
4002 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville948282b2013-08-29 08:55:16 -07004003
Wink Savilleab9321d2013-06-29 21:10:57 -07004004 CheckMp checkMp = new CheckMp(mContext, this);
4005 CheckMp.CallBack cb = new CheckMp.CallBack() {
4006 @Override
4007 void onComplete(Integer result) {
Wink Saville948282b2013-08-29 08:55:16 -07004008 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Savilleab9321d2013-06-29 21:10:57 -07004009 NetworkInfo ni =
4010 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4011 switch(result) {
Wink Saville948282b2013-08-29 08:55:16 -07004012 case CMP_RESULT_CODE_CONNECTABLE:
Wink Saville4fea0412013-09-06 09:53:08 -07004013 case CMP_RESULT_CODE_NO_CONNECTION:
4014 case CMP_RESULT_CODE_NO_DNS:
4015 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville948282b2013-08-29 08:55:16 -07004016 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Savilleab9321d2013-06-29 21:10:57 -07004017 break;
4018 }
Wink Saville948282b2013-08-29 08:55:16 -07004019 case CMP_RESULT_CODE_REDIRECTED: {
4020 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004021 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07004022 if (TextUtils.isEmpty(url)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004023 url = getMobileRedirectedProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07004024 }
4025 if (TextUtils.isEmpty(url) == false) {
Wink Saville948282b2013-08-29 08:55:16 -07004026 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004027 setProvNotificationVisible(true,
4028 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville948282b2013-08-29 08:55:16 -07004029 url);
Wink Savilleab9321d2013-06-29 21:10:57 -07004030 } else {
Wink Saville948282b2013-08-29 08:55:16 -07004031 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Savilleab9321d2013-06-29 21:10:57 -07004032 }
4033 break;
4034 }
Wink Saville4fea0412013-09-06 09:53:08 -07004035 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004036 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07004037 if (TextUtils.isEmpty(url) == false) {
Wink Saville948282b2013-08-29 08:55:16 -07004038 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004039 setProvNotificationVisible(true,
4040 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville948282b2013-08-29 08:55:16 -07004041 url);
Wink Savilleab9321d2013-06-29 21:10:57 -07004042 } else {
Wink Saville948282b2013-08-29 08:55:16 -07004043 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Savilleab9321d2013-06-29 21:10:57 -07004044 }
4045 break;
4046 }
4047 default: {
4048 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4049 break;
4050 }
4051 }
Wink Saville948282b2013-08-29 08:55:16 -07004052 mIsCheckingMobileProvisioning.set(false);
Wink Savilleab9321d2013-06-29 21:10:57 -07004053 }
4054 };
4055 CheckMp.Params params =
4056 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville948282b2013-08-29 08:55:16 -07004057 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Savilleab9321d2013-06-29 21:10:57 -07004058 checkMp.execute(params);
4059 } finally {
4060 Binder.restoreCallingIdentity(token);
Wink Saville948282b2013-08-29 08:55:16 -07004061 if (DBG) log("checkMobileProvisioning: X");
Wink Savilleab9321d2013-06-29 21:10:57 -07004062 }
4063 return timeOutMs;
4064 }
4065
4066 static class CheckMp extends
4067 AsyncTask<CheckMp.Params, Void, Integer> {
4068 private static final String CHECKMP_TAG = "CheckMp";
4069 public static final int MAX_TIMEOUT_MS = 60000;
4070 private static final int SOCKET_TIMEOUT_MS = 5000;
4071 private Context mContext;
4072 private ConnectivityService mCs;
4073 private TelephonyManager mTm;
4074 private Params mParams;
4075
4076 /**
4077 * Parameters for AsyncTask.execute
4078 */
4079 static class Params {
4080 private String mUrl;
4081 private long mTimeOutMs;
4082 private CallBack mCb;
4083
4084 Params(String url, long timeOutMs, CallBack cb) {
4085 mUrl = url;
4086 mTimeOutMs = timeOutMs;
4087 mCb = cb;
4088 }
4089
4090 @Override
4091 public String toString() {
4092 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4093 }
4094 }
4095
4096 /**
4097 * The call back object passed in Params. onComplete will be called
4098 * on the main thread.
4099 */
4100 abstract static class CallBack {
4101 // Called on the main thread.
4102 abstract void onComplete(Integer result);
4103 }
4104
4105 public CheckMp(Context context, ConnectivityService cs) {
4106 mContext = context;
4107 mCs = cs;
4108
4109 // Setup access to TelephonyService we'll be using.
4110 mTm = (TelephonyManager) mContext.getSystemService(
4111 Context.TELEPHONY_SERVICE);
4112 }
4113
4114 /**
4115 * Get the default url to use for the test.
4116 */
4117 public String getDefaultUrl() {
4118 // See http://go/clientsdns for usage approval
4119 String server = Settings.Global.getString(mContext.getContentResolver(),
4120 Settings.Global.CAPTIVE_PORTAL_SERVER);
4121 if (server == null) {
4122 server = "clients3.google.com";
4123 }
4124 return "http://" + server + "/generate_204";
4125 }
4126
4127 /**
4128 * Detect if its possible to connect to the http url. DNS based detection techniques
4129 * do not work at all hotspots. The best way to check is to perform a request to
4130 * a known address that fetches the data we expect.
4131 */
4132 private synchronized Integer isMobileOk(Params params) {
Wink Saville948282b2013-08-29 08:55:16 -07004133 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savilleab9321d2013-06-29 21:10:57 -07004134 Uri orgUri = Uri.parse(params.mUrl);
4135 Random rand = new Random();
4136 mParams = params;
4137
Wink Savilleafe58b02013-08-13 12:41:06 -07004138 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville948282b2013-08-29 08:55:16 -07004139 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savilled95ccc52013-09-13 12:40:11 -07004140 log("isMobileOk: X not mobile capable result=" + result);
4141 return result;
4142 }
4143
4144 // See if we've already determined we've got a provisioning connection,
4145 // if so we don't need to do anything active.
4146 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4147 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4148 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4149 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4150
4151 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4152 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4153 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4154 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4155
4156 if (isDefaultProvisioning || isHipriProvisioning) {
4157 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4158 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Savilleafe58b02013-08-13 12:41:06 -07004159 return result;
4160 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004161
Wink Savilleafe58b02013-08-13 12:41:06 -07004162 try {
Wink Savilleab9321d2013-06-29 21:10:57 -07004163 // Continue trying to connect until time has run out
4164 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville7f6ee2e2013-08-07 11:02:57 -07004165
Wink Savilledce52cd2013-08-16 17:17:28 -07004166 if (!mCs.isMobileDataStateTrackerReady()) {
4167 // Wait for MobileDataStateTracker to be ready.
4168 if (DBG) log("isMobileOk: mdst is not ready");
4169 while(SystemClock.elapsedRealtime() < endTime) {
4170 if (mCs.isMobileDataStateTrackerReady()) {
4171 // Enable fail fast as we'll do retries here and use a
4172 // hipri connection so the default connection stays active.
4173 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4174 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4175 break;
4176 }
4177 sleep(1);
4178 }
4179 }
4180
4181 log("isMobileOk: start hipri url=" + params.mUrl);
4182
Wink Saville7f6ee2e2013-08-07 11:02:57 -07004183 // First wait until we can start using hipri
4184 Binder binder = new Binder();
4185 while(SystemClock.elapsedRealtime() < endTime) {
4186 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4187 Phone.FEATURE_ENABLE_HIPRI, binder);
4188 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4189 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4190 log("isMobileOk: hipri started");
4191 break;
4192 }
4193 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville948282b2013-08-29 08:55:16 -07004194 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville7f6ee2e2013-08-07 11:02:57 -07004195 sleep(1);
4196 }
4197
4198 // Continue trying to connect until time has run out
Wink Savilleab9321d2013-06-29 21:10:57 -07004199 while(SystemClock.elapsedRealtime() < endTime) {
4200 try {
4201 // Wait for hipri to connect.
4202 // TODO: Don't poll and handle situation where hipri fails
4203 // because default is retrying. See b/9569540
4204 NetworkInfo.State state = mCs
4205 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4206 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville948282b2013-08-29 08:55:16 -07004207 if (true/*VDBG*/) {
Wink Saville1aef7fc2013-07-31 15:49:04 -07004208 log("isMobileOk: not connected ni=" +
Wink Savilleab9321d2013-06-29 21:10:57 -07004209 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville1aef7fc2013-07-31 15:49:04 -07004210 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004211 sleep(1);
Wink Saville948282b2013-08-29 08:55:16 -07004212 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savilleab9321d2013-06-29 21:10:57 -07004213 continue;
4214 }
4215
Wink Saville948282b2013-08-29 08:55:16 -07004216 // Hipri has started check if this is a provisioning url
4217 MobileDataStateTracker mdst = (MobileDataStateTracker)
4218 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4219 if (mdst.isProvisioningNetwork()) {
Wink Saville4fea0412013-09-06 09:53:08 -07004220 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Savilled95ccc52013-09-13 12:40:11 -07004221 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville948282b2013-08-29 08:55:16 -07004222 return result;
4223 } else {
4224 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4225 }
4226
Wink Savilleab9321d2013-06-29 21:10:57 -07004227 // Get of the addresses associated with the url host. We need to use the
4228 // address otherwise HttpURLConnection object will use the name to get
4229 // the addresses and is will try every address but that will bypass the
4230 // route to host we setup and the connection could succeed as the default
4231 // interface might be connected to the internet via wifi or other interface.
4232 InetAddress[] addresses;
4233 try {
4234 addresses = InetAddress.getAllByName(orgUri.getHost());
4235 } catch (UnknownHostException e) {
Wink Saville948282b2013-08-29 08:55:16 -07004236 result = CMP_RESULT_CODE_NO_DNS;
Wink Savilled95ccc52013-09-13 12:40:11 -07004237 log("isMobileOk: X UnknownHostException result=" + result);
Wink Savilleab9321d2013-06-29 21:10:57 -07004238 return result;
4239 }
4240 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4241
4242 // Get the type of addresses supported by this link
4243 LinkProperties lp = mCs.getLinkProperties(
4244 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti4faa0272013-08-08 11:00:12 +09004245 boolean linkHasIpv4 = lp.hasIPv4Address();
4246 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Savilleab9321d2013-06-29 21:10:57 -07004247 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4248 + " linkHasIpv6=" + linkHasIpv6);
4249
4250 // Loop through at most 3 valid addresses or all of the address or until
4251 // we run out of time
4252 int loops = Math.min(3, addresses.length);
4253 for(int validAddr=0, addrTried=0;
4254 (validAddr < loops) && (addrTried < addresses.length)
4255 && (SystemClock.elapsedRealtime() < endTime);
4256 addrTried ++) {
4257
4258 // Choose the address at random but make sure its type is supported
Lorenzo Colitti143a2cf2013-10-08 10:41:25 +09004259 // TODO: This doesn't work 100% of the time, because we may end up
4260 // trying the same invalid address more than once and ignoring one
4261 // of the valid addresses.
Wink Savilleab9321d2013-06-29 21:10:57 -07004262 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4263 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4264 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4265 // Valid address, so use it
4266 validAddr += 1;
4267 } else {
4268 // Invalid address so try next address
4269 continue;
4270 }
4271
4272 // Make a route to host so we check the specific interface.
4273 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4274 hostAddr.getAddress())) {
4275 // Wait a short time to be sure the route is established ??
4276 log("isMobileOk:"
4277 + " wait to establish route to hostAddr=" + hostAddr);
4278 sleep(3);
4279 } else {
4280 log("isMobileOk:"
4281 + " could not establish route to hostAddr=" + hostAddr);
4282 continue;
4283 }
4284
4285 // Rewrite the url to have numeric address to use the specific route.
Lorenzo Colitti143a2cf2013-10-08 10:41:25 +09004286 URL newUrl = new URL(orgUri.getScheme(),
4287 hostAddr.getHostAddress(), orgUri.getPath());
Wink Savilleab9321d2013-06-29 21:10:57 -07004288 log("isMobileOk: newUrl=" + newUrl);
4289
4290 HttpURLConnection urlConn = null;
4291 try {
4292 // Open the connection set the request header and get the response
4293 urlConn = (HttpURLConnection) newUrl.openConnection(
4294 java.net.Proxy.NO_PROXY);
4295 urlConn.setInstanceFollowRedirects(false);
4296 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4297 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4298 urlConn.setUseCaches(false);
4299 urlConn.setAllowUserInteraction(false);
Lorenzo Colitti143a2cf2013-10-08 10:41:25 +09004300 // Set the "Connection" to "Close" as by default "Keep-Alive"
4301 // is used which is useless in this case.
Wink Savilleab9321d2013-06-29 21:10:57 -07004302 urlConn.setRequestProperty("Connection", "close");
4303 int responseCode = urlConn.getResponseCode();
Wink Saville4fea0412013-09-06 09:53:08 -07004304
4305 // For debug display the headers
4306 Map<String, List<String>> headers = urlConn.getHeaderFields();
4307 log("isMobileOk: headers=" + headers);
4308
4309 // Close the connection
Wink Savilleab9321d2013-06-29 21:10:57 -07004310 urlConn.disconnect();
4311 urlConn = null;
Wink Saville4fea0412013-09-06 09:53:08 -07004312
4313 if (responseCode == 204) {
4314 // Return
Wink Saville4fea0412013-09-06 09:53:08 -07004315 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Savilled95ccc52013-09-13 12:40:11 -07004316 log("isMobileOk: X expected responseCode=" + responseCode
4317 + " result=" + result);
Wink Saville4fea0412013-09-06 09:53:08 -07004318 return result;
4319 } else {
4320 // Retry to be sure this was redirected, we've gotten
4321 // occasions where a server returned 200 even though
4322 // the device didn't have a "warm" sim.
4323 log("isMobileOk: not expected responseCode=" + responseCode);
4324 result = CMP_RESULT_CODE_REDIRECTED;
4325 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004326 } catch (Exception e) {
4327 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Saville4fea0412013-09-06 09:53:08 -07004328 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Savilleab9321d2013-06-29 21:10:57 -07004329 if (urlConn != null) {
4330 urlConn.disconnect();
4331 urlConn = null;
4332 }
4333 }
4334 }
Wink Savilled95ccc52013-09-13 12:40:11 -07004335 log("isMobileOk: X loops|timed out result=" + result);
Wink Savilleab9321d2013-06-29 21:10:57 -07004336 return result;
4337 } catch (Exception e) {
4338 log("isMobileOk: Exception e=" + e);
4339 continue;
4340 }
4341 }
4342 log("isMobileOk: timed out");
4343 } finally {
4344 log("isMobileOk: F stop hipri");
4345 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4346 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4347 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville948282b2013-08-29 08:55:16 -07004348
4349 // Wait for hipri to disconnect.
4350 long endTime = SystemClock.elapsedRealtime() + 5000;
4351
4352 while(SystemClock.elapsedRealtime() < endTime) {
4353 NetworkInfo.State state = mCs
4354 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4355 if (state != NetworkInfo.State.DISCONNECTED) {
4356 if (VDBG) {
4357 log("isMobileOk: connected ni=" +
4358 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4359 }
4360 sleep(1);
4361 continue;
4362 }
4363 }
4364
Wink Savilleab9321d2013-06-29 21:10:57 -07004365 log("isMobileOk: X result=" + result);
4366 }
4367 return result;
4368 }
4369
4370 @Override
4371 protected Integer doInBackground(Params... params) {
4372 return isMobileOk(params[0]);
4373 }
4374
4375 @Override
4376 protected void onPostExecute(Integer result) {
4377 log("onPostExecute: result=" + result);
4378 if ((mParams != null) && (mParams.mCb != null)) {
4379 mParams.mCb.onComplete(result);
4380 }
4381 }
4382
4383 private String inetAddressesToString(InetAddress[] addresses) {
4384 StringBuffer sb = new StringBuffer();
4385 boolean firstTime = true;
4386 for(InetAddress addr : addresses) {
4387 if (firstTime) {
4388 firstTime = false;
4389 } else {
4390 sb.append(",");
4391 }
4392 sb.append(addr);
4393 }
4394 return sb.toString();
4395 }
4396
4397 private void printNetworkInfo() {
4398 boolean hasIccCard = mTm.hasIccCard();
4399 int simState = mTm.getSimState();
4400 log("hasIccCard=" + hasIccCard
4401 + " simState=" + simState);
4402 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4403 if (ni != null) {
4404 log("ni.length=" + ni.length);
4405 for (NetworkInfo netInfo: ni) {
4406 log("netInfo=" + netInfo.toString());
4407 }
4408 } else {
4409 log("no network info ni=null");
4410 }
4411 }
4412
4413 /**
4414 * Sleep for a few seconds then return.
4415 * @param seconds
4416 */
4417 private static void sleep(int seconds) {
4418 try {
4419 Thread.sleep(seconds * 1000);
4420 } catch (InterruptedException e) {
4421 e.printStackTrace();
4422 }
4423 }
4424
Wink Savilleab9321d2013-06-29 21:10:57 -07004425 private void log(String s) {
4426 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4427 }
4428 }
4429
Wink Saville948282b2013-08-29 08:55:16 -07004430 // TODO: Move to ConnectivityManager and make public?
4431 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4432 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Savilleab9321d2013-06-29 21:10:57 -07004433
Wink Saville948282b2013-08-29 08:55:16 -07004434 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4435 @Override
4436 public void onReceive(Context context, Intent intent) {
4437 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4438 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4439 }
4440 }
4441 };
4442
4443 private void handleMobileProvisioningAction(String url) {
4444 // Notication mark notification as not visible
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004445 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville948282b2013-08-29 08:55:16 -07004446
4447 // If provisioning network handle as a special case,
4448 // otherwise launch browser with the intent directly.
4449 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville67c38212013-09-05 12:02:25 -07004450 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -07004451 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4452 MobileDataStateTracker mdst = (MobileDataStateTracker)
4453 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4454 mdst.enableMobileProvisioning(url);
4455 } else {
4456 if (DBG) log("handleMobileProvisioningAction: on default network");
Robert Greenwalt536b3c22013-10-17 12:46:52 -07004457 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4458 Intent.CATEGORY_APP_BROWSER);
4459 newIntent.setData(Uri.parse(url));
Wink Saville948282b2013-08-29 08:55:16 -07004460 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4461 Intent.FLAG_ACTIVITY_NEW_TASK);
4462 try {
4463 mContext.startActivity(newIntent);
4464 } catch (ActivityNotFoundException e) {
4465 loge("handleMobileProvisioningAction: startActivity failed" + e);
4466 }
4467 }
4468 }
4469
4470 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4471 private volatile boolean mIsNotificationVisible = false;
4472
4473 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4474 String url) {
4475 if (DBG) {
4476 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4477 + " extraInfo=" + extraInfo + " url=" + url);
4478 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004479
4480 Resources r = Resources.getSystem();
4481 NotificationManager notificationManager = (NotificationManager) mContext
4482 .getSystemService(Context.NOTIFICATION_SERVICE);
4483
4484 if (visible) {
4485 CharSequence title;
4486 CharSequence details;
4487 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07004488 Intent intent;
4489 Notification notification = new Notification();
4490 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07004491 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07004492 title = r.getString(R.string.wifi_available_sign_in, 0);
4493 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07004494 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07004495 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville948282b2013-08-29 08:55:16 -07004496 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4497 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4498 Intent.FLAG_ACTIVITY_NEW_TASK);
4499 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Savilleab9321d2013-06-29 21:10:57 -07004500 break;
4501 case ConnectivityManager.TYPE_MOBILE:
4502 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07004503 title = r.getString(R.string.network_available_sign_in, 0);
4504 // TODO: Change this to pull from NetworkInfo once a printable
4505 // name has been added to it
4506 details = mTelephonyManager.getNetworkOperatorName();
4507 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville948282b2013-08-29 08:55:16 -07004508 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4509 intent.putExtra("EXTRA_URL", url);
4510 intent.setFlags(0);
4511 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Savilleab9321d2013-06-29 21:10:57 -07004512 break;
4513 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07004514 title = r.getString(R.string.network_available_sign_in, 0);
4515 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07004516 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07004517 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville948282b2013-08-29 08:55:16 -07004518 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4519 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4520 Intent.FLAG_ACTIVITY_NEW_TASK);
4521 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Savilleab9321d2013-06-29 21:10:57 -07004522 break;
4523 }
4524
Wink Savilleab9321d2013-06-29 21:10:57 -07004525 notification.when = 0;
4526 notification.icon = icon;
4527 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07004528 notification.tickerText = title;
4529 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4530
Wink Saville948282b2013-08-29 08:55:16 -07004531 try {
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004532 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville948282b2013-08-29 08:55:16 -07004533 } catch (NullPointerException npe) {
4534 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4535 npe.printStackTrace();
4536 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004537 } else {
Wink Saville948282b2013-08-29 08:55:16 -07004538 try {
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004539 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville948282b2013-08-29 08:55:16 -07004540 } catch (NullPointerException npe) {
4541 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4542 npe.printStackTrace();
4543 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004544 }
Wink Saville948282b2013-08-29 08:55:16 -07004545 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07004546 }
4547
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004548 /** Location to an updatable file listing carrier provisioning urls.
4549 * An example:
4550 *
4551 * <?xml version="1.0" encoding="utf-8"?>
4552 * <provisioningUrls>
4553 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4554 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4555 * </provisioningUrls>
4556 */
4557 private static final String PROVISIONING_URL_PATH =
4558 "/data/misc/radio/provisioning_urls.xml";
4559 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004560
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004561 /** XML tag for root element. */
4562 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4563 /** XML tag for individual url */
4564 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4565 /** XML tag for redirected url */
4566 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4567 /** XML attribute for mcc */
4568 private static final String ATTR_MCC = "mcc";
4569 /** XML attribute for mnc */
4570 private static final String ATTR_MNC = "mnc";
4571
4572 private static final int REDIRECTED_PROVISIONING = 1;
4573 private static final int PROVISIONING = 2;
4574
4575 private String getProvisioningUrlBaseFromFile(int type) {
4576 FileReader fileReader = null;
4577 XmlPullParser parser = null;
4578 Configuration config = mContext.getResources().getConfiguration();
4579 String tagType;
4580
4581 switch (type) {
4582 case PROVISIONING:
4583 tagType = TAG_PROVISIONING_URL;
4584 break;
4585 case REDIRECTED_PROVISIONING:
4586 tagType = TAG_REDIRECTED_URL;
4587 break;
4588 default:
4589 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4590 type);
4591 }
4592
4593 try {
4594 fileReader = new FileReader(mProvisioningUrlFile);
4595 parser = Xml.newPullParser();
4596 parser.setInput(fileReader);
4597 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4598
4599 while (true) {
4600 XmlUtils.nextElement(parser);
4601
4602 String element = parser.getName();
4603 if (element == null) break;
4604
4605 if (element.equals(tagType)) {
4606 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4607 try {
4608 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4609 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4610 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4611 parser.next();
4612 if (parser.getEventType() == XmlPullParser.TEXT) {
4613 return parser.getText();
4614 }
4615 }
4616 }
4617 } catch (NumberFormatException e) {
4618 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4619 }
4620 }
4621 }
4622 return null;
4623 } catch (FileNotFoundException e) {
4624 loge("Carrier Provisioning Urls file not found");
4625 } catch (XmlPullParserException e) {
4626 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4627 } catch (IOException e) {
4628 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4629 } finally {
4630 if (fileReader != null) {
4631 try {
4632 fileReader.close();
4633 } catch (IOException e) {}
4634 }
4635 }
4636 return null;
4637 }
4638
Wink Saville42d4f082013-07-20 20:31:59 -07004639 @Override
4640 public String getMobileRedirectedProvisioningUrl() {
4641 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004642 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4643 if (TextUtils.isEmpty(url)) {
4644 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4645 }
4646 return url;
4647 }
4648
Wink Saville42d4f082013-07-20 20:31:59 -07004649 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004650 public String getMobileProvisioningUrl() {
4651 enforceConnectivityInternalPermission();
4652 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4653 if (TextUtils.isEmpty(url)) {
4654 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004655 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004656 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004657 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004658 }
Wink Saville8cf35602013-07-10 23:00:07 -07004659 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004660 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004661 String phoneNumber = mTelephonyManager.getLine1Number();
4662 if (TextUtils.isEmpty(phoneNumber)) {
4663 phoneNumber = "0000000000";
4664 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004665 url = String.format(url,
4666 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4667 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004668 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004669 }
4670
Wink Savilleab9321d2013-06-29 21:10:57 -07004671 return url;
4672 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004673
Wink Saville948282b2013-08-29 08:55:16 -07004674 @Override
4675 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4676 String extraInfo, String url) {
4677 enforceConnectivityInternalPermission();
4678 setProvNotificationVisible(visible, networkType, extraInfo, url);
4679 }
Wink Saville7788c612013-08-29 14:57:08 -07004680
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004681 @Override
4682 public void setAirplaneMode(boolean enable) {
4683 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004684 final long ident = Binder.clearCallingIdentity();
4685 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004686 final ContentResolver cr = mContext.getContentResolver();
4687 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4688 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4689 intent.putExtra("state", enable);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004690 mContext.sendBroadcast(intent);
4691 } finally {
4692 Binder.restoreCallingIdentity(ident);
4693 }
4694 }
4695
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004696 private void onUserStart(int userId) {
4697 synchronized(mVpns) {
4698 Vpn userVpn = mVpns.get(userId);
4699 if (userVpn != null) {
4700 loge("Starting user already has a VPN");
4701 return;
4702 }
4703 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4704 mVpns.put(userId, userVpn);
4705 userVpn.startMonitoring(mContext, mTrackerHandler);
4706 }
4707 }
4708
4709 private void onUserStop(int userId) {
4710 synchronized(mVpns) {
4711 Vpn userVpn = mVpns.get(userId);
4712 if (userVpn == null) {
4713 loge("Stopping user has no VPN");
4714 return;
4715 }
4716 mVpns.delete(userId);
4717 }
4718 }
4719
4720 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4721 @Override
4722 public void onReceive(Context context, Intent intent) {
4723 final String action = intent.getAction();
4724 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4725 if (userId == UserHandle.USER_NULL) return;
4726
4727 if (Intent.ACTION_USER_STARTING.equals(action)) {
4728 onUserStart(userId);
4729 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4730 onUserStop(userId);
4731 }
4732 }
4733 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004734
4735 @Override
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004736 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004737 enforceAccessPermission();
4738 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004739 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004740 } else {
4741 return null;
4742 }
4743 }
4744
4745 @Override
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004746 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004747 enforceAccessPermission();
4748 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004749 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004750 } else {
4751 return null;
4752 }
4753 }
4754
4755 @Override
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004756 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004757 enforceAccessPermission();
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004758 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004759 for (NetworkStateTracker tracker : mNetTrackers) {
4760 if (tracker != null) {
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004761 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004762 if (li != null) {
4763 result.add(li);
4764 }
4765 }
4766 }
4767
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004768 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004769 }
4770
4771 /* Infrastructure for network sampling */
4772
4773 private void handleNetworkSamplingTimeout() {
4774
4775 log("Sampling interval elapsed, updating statistics ..");
4776
4777 // initialize list of interfaces ..
4778 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4779 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4780 for (NetworkStateTracker tracker : mNetTrackers) {
4781 if (tracker != null) {
4782 String ifaceName = tracker.getNetworkInterfaceName();
4783 if (ifaceName != null) {
4784 mapIfaceToSample.put(ifaceName, null);
4785 }
4786 }
4787 }
4788
4789 // Read samples for all interfaces
4790 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4791
4792 // process samples for all networks
4793 for (NetworkStateTracker tracker : mNetTrackers) {
4794 if (tracker != null) {
4795 String ifaceName = tracker.getNetworkInterfaceName();
4796 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4797 if (ss != null) {
4798 // end the previous sampling cycle
4799 tracker.stopSampling(ss);
4800 // start a new sampling cycle ..
4801 tracker.startSampling(ss);
4802 }
4803 }
4804 }
4805
4806 log("Done.");
4807
4808 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4809 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4810 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4811
4812 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4813
4814 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4815 }
4816
4817 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4818 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4819 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821}