blob: 2231e605cb23890f578c9678664da809bb704938 [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
Wink Savilleab9321d2013-06-29 21:10:57 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080037import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090041import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070048import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080050import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080051import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070057import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080058import android.net.LinkProperties;
Wink Savilleab9321d2013-06-29 21:10:57 -070059import android.net.Uri;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Wink Savilleab9321d2013-06-29 21:10:57 -070065import android.net.NetworkInfo.State;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070069import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070070import android.net.Proxy;
71import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070072import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090074import android.net.wimax.WimaxManagerConstants;
Wink Savilleab9321d2013-06-29 21:10:57 -070075import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040077import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070079import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070080import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070081import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Looper;
83import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070084import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070085import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070086import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070087import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.RemoteException;
Wink Savilleab9321d2013-06-29 21:10:57 -070089import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070091import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070093import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700100import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700101import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700102import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700105import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700107import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.telephony.DctConstants;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700109import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -0700110import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700113import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400114import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900115import com.android.server.connectivity.Nat464Xlat;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700118import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700119import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700120import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700123import com.android.internal.annotations.GuardedBy;
124
tk.mun148c7d02011-10-13 22:51:57 +0900125import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import org.xmlpull.v1.XmlPullParser;
128import org.xmlpull.v1.XmlPullParserException;
129
130import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import java.io.FileNotFoundException;
133import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700134import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900136import java.lang.reflect.Constructor;
Wink Savilleab9321d2013-06-29 21:10:57 -0700137import java.net.HttpURLConnection;
Wink Savillec9822c52011-07-14 12:23:28 -0700138import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700139import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700140import java.net.InetAddress;
Wink Savilleab9321d2013-06-29 21:10:57 -0700141import java.net.URL;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700142import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700143import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700144import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700146import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import java.util.List;
Wink Savilleab9321d2013-06-29 21:10:57 -0700149import java.util.Random;
150import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152/**
153 * @hide
154 */
155public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700156 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Robert Greenwaltba175a52010-10-05 19:12:26 -0700158 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700159 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161 private static final boolean LOGD_RULES = false;
162
Jeff Sharkey899223b2012-08-04 15:24:58 -0700163 // TODO: create better separation between radio types and network types
164
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165 // how long to wait before switching back to a radio's default network
166 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
167 // system property that can override the above value
168 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
169 "android.telephony.apn-restore";
170
Wink Savilleab9321d2013-06-29 21:10:57 -0700171 // Default value if FAIL_FAST_TIME_MS is not set
172 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
173 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
174 private static final String FAIL_FAST_TIME_MS =
175 "persist.radio.fail_fast_time_ms";
176
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700177 // used in recursive route setting to add gateways for the host for which
178 // a host route was requested.
179 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
180
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800181 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800182 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800183
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700184 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700185
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700186 @GuardedBy("mVpns")
187 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700188 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700189
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700190 private boolean mLockdownEnabled;
191 private LockdownVpnTracker mLockdownTracker;
192
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900193 private Nat464Xlat mClat;
194
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700195 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
196 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700197 /** Currently active network rules by UID. */
198 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700199 /** Set of ifaces that are costly. */
200 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 /**
203 * Sometimes we want to refer to the individual network state
204 * trackers separately, and sometimes we just want to treat them
205 * abstractly.
206 */
207 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700208
Irfan Sheriffda6da092012-08-16 12:49:23 -0700209 /* Handles captive portal check on a network */
210 private CaptivePortalTracker mCaptivePortalTracker;
211
Robert Greenwalt42acef32009-08-12 16:08:25 -0700212 /**
Wink Savillee8222252011-07-13 13:44:13 -0700213 * The link properties that define the current links
214 */
215 private LinkProperties mCurrentLinkProperties[];
216
217 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700218 * A per Net list of the PID's that requested access to the net
219 * used both as a refcount and for per-PID DNS selection
220 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200221 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700222
Robert Greenwalt42acef32009-08-12 16:08:25 -0700223 // priority order of the nettrackers
224 // (excluding dynamically set mNetworkPreference)
225 // TODO - move mNetworkTypePreference into this
226 private int[] mPriorityList;
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private Context mContext;
229 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700230 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700231 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000232 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700233 private int mDefaultInetConditionPublished = 0;
234 private boolean mInetConditionChangeInFlight = false;
235 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700237 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800238 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700239 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700242 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700244 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700245 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700246
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700247 private static final int ENABLED = 1;
248 private static final int DISABLED = 0;
249
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700250 private static final boolean ADD = true;
251 private static final boolean REMOVE = false;
252
253 private static final boolean TO_DEFAULT_TABLE = true;
254 private static final boolean TO_SECONDARY_TABLE = false;
255
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256 /**
257 * used internally as a delayed event to make us switch back to the
258 * default network
259 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700260 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700261
262 /**
263 * used internally to change our mobile data enabled flag
264 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700265 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266
267 /**
268 * used internally to change our network preference setting
269 * arg1 = networkType to prefer
270 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700271 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700272
273 /**
274 * used internally to synchronize inet condition reports
275 * arg1 = networkType
276 * arg2 = condition (0 bad, 100 good)
277 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700278 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700279
280 /**
281 * used internally to mark the end of inet condition hold periods
282 * arg1 = networkType
283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700285
286 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700287 * used internally to set enable/disable cellular data
288 * arg1 = ENBALED or DISABLED
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700291
Robert Greenwaltf3331232010-09-24 14:32:21 -0700292 /**
293 * used internally to clear a wakelock when transitioning
294 * from one net to another
295 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700296 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700297
Robert Greenwalt434203a2010-10-11 16:00:27 -0700298 /**
299 * used internally to reload global proxy settings
300 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700301 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700302
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700303 /**
304 * used internally to set external dependency met/unmet
305 * arg1 = ENABLED (met) or DISABLED (unmet)
306 * arg2 = NetworkType
307 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700308 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700309
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700310 /**
311 * used internally to restore DNS properties back to the
312 * default network
313 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700314 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700315
Wink Saville2b30afd2011-08-05 11:40:22 -0700316 /**
Wink Saville628b0852011-08-04 15:01:58 -0700317 * used internally to send a sticky broadcast delayed.
318 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700319 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700320
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321 /**
322 * Used internally to
323 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
324 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700325 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700327 private static final int EVENT_VPN_STATE_CHANGED = 14;
328
Wink Savilleab9321d2013-06-29 21:10:57 -0700329 /**
330 * Used internally to disable fail fast of mobile data
331 */
332 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
333
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700334 /** Handler used for internal events. */
335 private InternalHandler mHandler;
336 /** Handler used for incoming {@link NetworkStateTracker} events. */
337 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700338
339 // list of DeathRecipients used to make sure features are turned off when
340 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500341 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700342
Mike Lockwood0f79b542009-08-14 14:18:49 -0400343 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800344 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400345
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700346 private PowerManager.WakeLock mNetTransitionWakeLock;
347 private String mNetTransitionWakeLockCausedBy = "";
348 private int mNetTransitionWakeLockSerialNumber;
349 private int mNetTransitionWakeLockTimeout;
350
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700351 private InetAddress mDefaultDns;
352
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700353 // this collection is used to refcount the added routes - if there are none left
354 // it's time to remove the route from the route table
355 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
356
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700357 // used in DBG mode to track inet condition reports
358 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
359 private ArrayList mInetLog;
360
Robert Greenwalt434203a2010-10-11 16:00:27 -0700361 // track the current default http proxy - tell the world if we get a new one (real change)
362 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700363 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700364 private boolean mDefaultProxyDisabled = false;
365
Robert Greenwalt434203a2010-10-11 16:00:27 -0700366 // track the global proxy.
367 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700368
369 private SettingsObserver mSettingsObserver;
370
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700371 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700372 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700373
Robert Greenwalt511288a2009-12-07 11:33:18 -0800374 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700375 public int mSimultaneity;
376 public int mType;
377 public RadioAttributes(String init) {
378 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700379 mType = Integer.parseInt(fragments[0]);
380 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700381 }
382 }
383 RadioAttributes[] mRadioAttributes;
384
Robert Greenwalt50393202011-06-21 17:26:14 -0700385 // the set of network types that can only be enabled by system/sig apps
386 List mProtectedNetworks;
387
John Spurlockbf991a82013-06-24 14:20:23 -0400388 private DataConnectionStats mDataConnectionStats;
Wink Savilleab9321d2013-06-29 21:10:57 -0700389 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
390
391 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400392
Wink Savillefde1ac92013-07-16 17:16:37 -0700393 // We only want one checkMobileProvisioning after booting.
394 volatile boolean mFirstProvisioningCheckStarted = false;
395
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700396 public ConnectivityService(Context context, INetworkManagementService netd,
397 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700398 // Currently, omitting a NetworkFactory will create one internally
399 // TODO: create here when we have cleaner WiMAX support
400 this(context, netd, statsService, policyManager, null);
401 }
402
Jeff Sharkey899223b2012-08-04 15:24:58 -0700403 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700404 INetworkStatsService statsService, INetworkPolicyManager policyManager,
405 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800406 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800407
Wink Savillebb08caf2010-09-02 19:23:52 -0700408 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
409 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700410 mHandler = new InternalHandler(handlerThread.getLooper());
411 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700412
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700413 if (netFactory == null) {
414 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
415 }
416
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800417 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800418 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
419 String id = Settings.Secure.getString(context.getContentResolver(),
420 Settings.Secure.ANDROID_ID);
421 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700422 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800423 SystemProperties.set("net.hostname", name);
424 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800425 }
426
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700427 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700428 String dns = Settings.Global.getString(context.getContentResolver(),
429 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700430 if (dns == null || dns.length() == 0) {
431 dns = context.getResources().getString(
432 com.android.internal.R.string.config_default_dns_server);
433 }
434 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800435 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
436 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800437 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700438 }
439
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700440 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700441 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700442 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700443 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700444 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700445
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700446 try {
447 mPolicyManager.registerListener(mPolicyListener);
448 } catch (RemoteException e) {
449 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700450 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700451 }
452
453 final PowerManager powerManager = (PowerManager) context.getSystemService(
454 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700455 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
456 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
457 com.android.internal.R.integer.config_networkTransitionTimeout);
458
Robert Greenwalt42acef32009-08-12 16:08:25 -0700459 mNetTrackers = new NetworkStateTracker[
460 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700461 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700462
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700463 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700464 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700465
Robert Greenwalt42acef32009-08-12 16:08:25 -0700466 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700467 String[] raStrings = context.getResources().getStringArray(
468 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700469 for (String raString : raStrings) {
470 RadioAttributes r = new RadioAttributes(raString);
471 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800472 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700473 continue;
474 }
475 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800476 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700477 r.mType);
478 continue;
479 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700480 mRadioAttributes[r.mType] = r;
481 }
482
Wink Saville51f456f2013-04-23 14:26:51 -0700483 // TODO: What is the "correct" way to do determine if this is a wifi only device?
484 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
485 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700486 String[] naStrings = context.getResources().getStringArray(
487 com.android.internal.R.array.networkAttributes);
488 for (String naString : naStrings) {
489 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700490 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700491 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800492 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700493 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700494 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700495 }
Wink Saville51f456f2013-04-23 14:26:51 -0700496 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
497 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
498 n.type);
499 continue;
500 }
Wink Saville975c8482011-04-07 14:23:45 -0700501 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800502 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700503 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700504 continue;
505 }
Wink Saville975c8482011-04-07 14:23:45 -0700506 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800507 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700508 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700509 continue;
510 }
Wink Saville975c8482011-04-07 14:23:45 -0700511 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700512 mNetworksDefined++;
513 } catch(Exception e) {
514 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700515 }
516 }
517
Robert Greenwalt50393202011-06-21 17:26:14 -0700518 mProtectedNetworks = new ArrayList<Integer>();
519 int[] protectedNetworks = context.getResources().getIntArray(
520 com.android.internal.R.array.config_protectedNetworks);
521 for (int p : protectedNetworks) {
522 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
523 mProtectedNetworks.add(p);
524 } else {
525 if (DBG) loge("Ignoring protectedNetwork " + p);
526 }
527 }
528
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700529 // high priority first
530 mPriorityList = new int[mNetworksDefined];
531 {
532 int insertionPoint = mNetworksDefined-1;
533 int currentLowest = 0;
534 int nextLowest = 0;
535 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700536 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700537 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700538 if (na.priority < currentLowest) continue;
539 if (na.priority > currentLowest) {
540 if (na.priority < nextLowest || nextLowest == 0) {
541 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700542 }
543 continue;
544 }
Wink Saville975c8482011-04-07 14:23:45 -0700545 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700546 }
547 currentLowest = nextLowest;
548 nextLowest = 0;
549 }
550 }
551
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800552 // Update mNetworkPreference according to user mannually first then overlay config.xml
553 mNetworkPreference = getPersistedNetworkPreference();
554 if (mNetworkPreference == -1) {
555 for (int n : mPriorityList) {
556 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
557 mNetworkPreference = n;
558 break;
559 }
560 }
561 if (mNetworkPreference == -1) {
562 throw new IllegalStateException(
563 "You should set at least one default Network in config.xml!");
564 }
565 }
566
Mattias Falk8b47b362011-08-23 14:15:13 +0200567 mNetRequestersPids =
568 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700569 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200570 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700571 }
572
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500573 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700574
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700575 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
576 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700577
578 // Create and start trackers for hard-coded networks
579 for (int targetNetworkType : mPriorityList) {
580 final NetworkConfig config = mNetConfigs[targetNetworkType];
581 final NetworkStateTracker tracker;
582 try {
583 tracker = netFactory.createTracker(targetNetworkType, config);
584 mNetTrackers[targetNetworkType] = tracker;
585 } catch (IllegalArgumentException e) {
586 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
587 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700588 continue;
589 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700590
591 tracker.startMonitoring(context, mTrackerHandler);
592 if (config.isDefault()) {
593 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800594 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700595 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800596
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700597 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700598 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700599 mTethering.getTetherableWifiRegexs().length != 0 ||
600 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700601 mTethering.getUpstreamIfaceTypes().length != 0);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700602 //set up the listener for user state for creating user VPNs
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800603
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700604 IntentFilter intentFilter = new IntentFilter();
605 intentFilter.addAction(Intent.ACTION_USER_STARTING);
606 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
607 mContext.registerReceiverAsUser(
608 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900609 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
610
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700611 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700612 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700613 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900614 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700615 } catch (RemoteException e) {
616 loge("Error registering observer :" + e);
617 }
618
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700619 if (DBG) {
620 mInetLog = new ArrayList();
621 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700622
623 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
624 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800625
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700626 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800627 loadGlobalProxy();
John Spurlockbf991a82013-06-24 14:20:23 -0400628
629 mDataConnectionStats = new DataConnectionStats(mContext);
630 mDataConnectionStats.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700632
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700633 /**
634 * Factory that creates {@link NetworkStateTracker} instances using given
635 * {@link NetworkConfig}.
636 */
637 public interface NetworkFactory {
638 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
639 }
640
641 private static class DefaultNetworkFactory implements NetworkFactory {
642 private final Context mContext;
643 private final Handler mTrackerHandler;
644
645 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
646 mContext = context;
647 mTrackerHandler = trackerHandler;
648 }
649
650 @Override
651 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
652 switch (config.radio) {
653 case TYPE_WIFI:
654 return new WifiStateTracker(targetNetworkType, config.name);
655 case TYPE_MOBILE:
656 return new MobileDataStateTracker(targetNetworkType, config.name);
657 case TYPE_DUMMY:
658 return new DummyDataStateTracker(targetNetworkType, config.name);
659 case TYPE_BLUETOOTH:
660 return BluetoothTetheringDataTracker.getInstance();
661 case TYPE_WIMAX:
662 return makeWimaxStateTracker(mContext, mTrackerHandler);
663 case TYPE_ETHERNET:
664 return EthernetDataTracker.getInstance();
665 default:
666 throw new IllegalArgumentException(
667 "Trying to create a NetworkStateTracker for an unknown radio type: "
668 + config.radio);
669 }
670 }
671 }
672
673 /**
674 * Loads external WiMAX library and registers as system service, returning a
675 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
676 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
677 */
678 private static NetworkStateTracker makeWimaxStateTracker(
679 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700680 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900681 DexClassLoader wimaxClassLoader;
682 Class wimaxStateTrackerClass = null;
683 Class wimaxServiceClass = null;
684 Class wimaxManagerClass;
685 String wimaxJarLocation;
686 String wimaxLibLocation;
687 String wimaxManagerClassName;
688 String wimaxServiceClassName;
689 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690
tk.mun148c7d02011-10-13 22:51:57 +0900691 NetworkStateTracker wimaxStateTracker = null;
692
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700693 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900694 com.android.internal.R.bool.config_wimaxEnabled);
695
696 if (isWimaxEnabled) {
697 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700698 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900699 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700700 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900701 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700702 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900703 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700704 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900705 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700706 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900707 com.android.internal.R.string.config_wimaxStateTrackerClassname);
708
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800709 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900710 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700711 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900712 wimaxLibLocation, ClassLoader.getSystemClassLoader());
713
714 try {
715 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
716 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
717 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
718 } catch (ClassNotFoundException ex) {
719 loge("Exception finding Wimax classes: " + ex.toString());
720 return null;
721 }
722 } catch(Resources.NotFoundException ex) {
723 loge("Wimax Resources does not exist!!! ");
724 return null;
725 }
726
727 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800728 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900729
730 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
731 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700732 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
733 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900734
735 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
736 (new Class[] {Context.class, wimaxStateTrackerClass});
737 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700738 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900739 wmxSrvConst.setAccessible(false);
740
741 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
742
743 } catch(Exception ex) {
744 loge("Exception creating Wimax classes: " + ex.toString());
745 return null;
746 }
747 } else {
748 loge("Wimax is not enabled or not added to the network attributes!!! ");
749 return null;
750 }
751
752 return wimaxStateTracker;
753 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700756 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 * @param preference the new preference
758 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700759 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700761
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700762 mHandler.sendMessage(
763 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
765
766 public int getNetworkPreference() {
767 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700768 int preference;
769 synchronized(this) {
770 preference = mNetworkPreference;
771 }
772 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700775 private void handleSetNetworkPreference(int preference) {
776 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700777 mNetConfigs[preference] != null &&
778 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700779 if (mNetworkPreference != preference) {
780 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700781 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700782 synchronized(this) {
783 mNetworkPreference = preference;
784 }
785 enforcePreference();
786 }
787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700789
Wink Saville628b0852011-08-04 15:01:58 -0700790 private int getConnectivityChangeDelay() {
791 final ContentResolver cr = mContext.getContentResolver();
792
793 /** Check system properties for the default value then use secure settings value, if any. */
794 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700795 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
796 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
797 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700798 defaultDelay);
799 }
800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 private int getPersistedNetworkPreference() {
802 final ContentResolver cr = mContext.getContentResolver();
803
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700804 final int networkPrefSetting = Settings.Global
805 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800807 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700811 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 * In this method, we only tear down a non-preferred network. Establishing
813 * a connection to the preferred network is taken care of when we handle
814 * the disconnect event from the non-preferred network
815 * (see {@link #handleDisconnect(NetworkInfo)}).
816 */
817 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700818 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 return;
820
Robert Greenwalt42acef32009-08-12 16:08:25 -0700821 if (!mNetTrackers[mNetworkPreference].isAvailable())
822 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823
Robert Greenwalt42acef32009-08-12 16:08:25 -0700824 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700825 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700826 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700827 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800828 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700829 " in enforcePreference");
830 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700831 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 }
834 }
835
836 private boolean teardown(NetworkStateTracker netTracker) {
837 if (netTracker.teardown()) {
838 netTracker.setTeardownRequested(true);
839 return true;
840 } else {
841 return false;
842 }
843 }
844
845 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700846 * Check if UID should be blocked from using the network represented by the
847 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700848 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700849 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
850 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700851
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700852 final boolean networkCostly;
853 final int uidRules;
854 synchronized (mRulesLock) {
855 networkCostly = mMeteredIfaces.contains(iface);
856 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700857 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700858
859 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
860 return true;
861 }
862
863 // no restrictive rules; network is visible
864 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700865 }
866
867 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700868 * Return a filtered {@link NetworkInfo}, potentially marked
869 * {@link DetailedState#BLOCKED} based on
870 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700871 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700872 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
873 NetworkInfo info = tracker.getNetworkInfo();
874 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700875 // network is blocked; clone and override state
876 info = new NetworkInfo(info);
877 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700878 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700879 if (mLockdownTracker != null) {
880 info = mLockdownTracker.augmentNetworkInfo(info);
881 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700882 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700883 }
884
885 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 * Return NetworkInfo for the active (i.e., connected) network interface.
887 * It is assumed that at most one network is active at a time. If more
888 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700889 * @return the info for the active network, or {@code null} if none is
890 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700892 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700894 enforceAccessPermission();
895 final int uid = Binder.getCallingUid();
896 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700899 public NetworkInfo getActiveNetworkInfoUnfiltered() {
900 enforceAccessPermission();
901 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
902 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
903 if (tracker != null) {
904 return tracker.getNetworkInfo();
905 }
906 }
907 return null;
908 }
909
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700910 @Override
911 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
912 enforceConnectivityInternalPermission();
913 return getNetworkInfo(mActiveDefaultNetwork, uid);
914 }
915
916 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 public NetworkInfo getNetworkInfo(int networkType) {
918 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700919 final int uid = Binder.getCallingUid();
920 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 }
922
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700923 private NetworkInfo getNetworkInfo(int networkType, int uid) {
924 NetworkInfo info = null;
925 if (isNetworkTypeValid(networkType)) {
926 final NetworkStateTracker tracker = mNetTrackers[networkType];
927 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700928 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700929 }
930 }
931 return info;
932 }
933
934 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 public NetworkInfo[] getAllNetworkInfo() {
936 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700937 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700938 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700939 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700940 for (NetworkStateTracker tracker : mNetTrackers) {
941 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700942 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700943 }
944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700946 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
948
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700949 @Override
950 public boolean isNetworkSupported(int networkType) {
951 enforceAccessPermission();
952 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
953 }
954
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700955 /**
956 * Return LinkProperties for the active (i.e., connected) default
957 * network interface. It is assumed that at most one default network
958 * is active at a time. If more than one is active, it is indeterminate
959 * which will be returned.
960 * @return the ip properties for the active network, or {@code null} if
961 * none is active
962 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700964 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700965 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700966 }
967
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700968 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700969 public LinkProperties getLinkProperties(int networkType) {
970 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 if (isNetworkTypeValid(networkType)) {
972 final NetworkStateTracker tracker = mNetTrackers[networkType];
973 if (tracker != null) {
974 return tracker.getLinkProperties();
975 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700976 }
977 return null;
978 }
979
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700980 @Override
981 public NetworkState[] getAllNetworkState() {
982 enforceAccessPermission();
983 final int uid = Binder.getCallingUid();
984 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700985 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700986 for (NetworkStateTracker tracker : mNetTrackers) {
987 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700988 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700989 result.add(new NetworkState(
990 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
991 }
992 }
993 }
994 return result.toArray(new NetworkState[result.size()]);
995 }
996
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700997 private NetworkState getNetworkStateUnchecked(int networkType) {
998 if (isNetworkTypeValid(networkType)) {
999 final NetworkStateTracker tracker = mNetTrackers[networkType];
1000 if (tracker != null) {
1001 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1002 tracker.getLinkCapabilities());
1003 }
1004 }
1005 return null;
1006 }
1007
1008 @Override
1009 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1010 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001011
1012 final long token = Binder.clearCallingIdentity();
1013 try {
1014 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1015 if (state != null) {
1016 try {
1017 return mPolicyManager.getNetworkQuotaInfo(state);
1018 } catch (RemoteException e) {
1019 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001020 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001021 return null;
1022 } finally {
1023 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001024 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001025 }
1026
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001027 @Override
1028 public boolean isActiveNetworkMetered() {
1029 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001030 final long token = Binder.clearCallingIdentity();
1031 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001032 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001033 } finally {
1034 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001035 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001036 }
1037
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001038 private boolean isNetworkMeteredUnchecked(int networkType) {
1039 final NetworkState state = getNetworkStateUnchecked(networkType);
1040 if (state != null) {
1041 try {
1042 return mPolicyManager.isNetworkMetered(state);
1043 } catch (RemoteException e) {
1044 }
1045 }
1046 return false;
1047 }
1048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 public boolean setRadios(boolean turnOn) {
1050 boolean result = true;
1051 enforceChangePermission();
1052 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001053 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
1055 return result;
1056 }
1057
1058 public boolean setRadio(int netType, boolean turnOn) {
1059 enforceChangePermission();
1060 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1061 return false;
1062 }
1063 NetworkStateTracker tracker = mNetTrackers[netType];
1064 return tracker != null && tracker.setRadio(turnOn);
1065 }
1066
Jeff Sharkey216c1812012-08-05 14:29:23 -07001067 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1068 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001069 public void interfaceClassDataActivityChanged(String label, boolean active) {
1070 int deviceType = Integer.parseInt(label);
1071 sendDataActivityBroadcast(deviceType, active);
1072 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001073 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001074
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001075 /**
1076 * Used to notice when the calling process dies so we can self-expire
1077 *
1078 * Also used to know if the process has cleaned up after itself when
1079 * our auto-expire timer goes off. The timer has a link to an object.
1080 *
1081 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001082 private class FeatureUser implements IBinder.DeathRecipient {
1083 int mNetworkType;
1084 String mFeature;
1085 IBinder mBinder;
1086 int mPid;
1087 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001088 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001089
1090 FeatureUser(int type, String feature, IBinder binder) {
1091 super();
1092 mNetworkType = type;
1093 mFeature = feature;
1094 mBinder = binder;
1095 mPid = getCallingPid();
1096 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001097 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001098
Robert Greenwalt42acef32009-08-12 16:08:25 -07001099 try {
1100 mBinder.linkToDeath(this, 0);
1101 } catch (RemoteException e) {
1102 binderDied();
1103 }
1104 }
1105
1106 void unlinkDeathRecipient() {
1107 mBinder.unlinkToDeath(this, 0);
1108 }
1109
1110 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001111 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001112 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1113 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001114 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001115 }
1116
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001117 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001118 if (VDBG) {
1119 log("ConnectivityService FeatureUser expire(" +
1120 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1121 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1122 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001123 stopUsingNetworkFeature(this, false);
1124 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001125
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001126 public boolean isSameUser(FeatureUser u) {
1127 if (u == null) return false;
1128
1129 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1130 }
1131
1132 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1133 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1134 TextUtils.equals(mFeature, feature)) {
1135 return true;
1136 }
1137 return false;
1138 }
1139
Robert Greenwaltb9285352009-12-21 18:24:07 -08001140 public String toString() {
1141 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1142 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1143 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001144 }
1145
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001146 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001147 public int startUsingNetworkFeature(int networkType, String feature,
1148 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001149 long startTime = 0;
1150 if (DBG) {
1151 startTime = SystemClock.elapsedRealtime();
1152 }
Wink Savillec9acde92011-09-21 11:05:43 -07001153 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001154 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1155 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001158 try {
1159 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1160 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001161 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001162 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001163
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001164 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001165
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001166 // TODO - move this into individual networktrackers
1167 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001168
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001169 if (mLockdownEnabled) {
1170 // Since carrier APNs usually aren't available from VPN
1171 // endpoint, mark them as unavailable.
1172 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1173 }
1174
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001175 if (mProtectedNetworks.contains(usedNetworkType)) {
1176 enforceConnectivityInternalPermission();
1177 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001178
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001179 // if UID is restricted, don't allow them to bring up metered APNs
1180 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1181 final int uidRules;
1182 synchronized (mRulesLock) {
1183 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1184 }
1185 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001186 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001187 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001188
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001189 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1190 if (network != null) {
1191 Integer currentPid = new Integer(getCallingPid());
1192 if (usedNetworkType != networkType) {
1193 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001194
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001195 if (ni.isAvailable() == false) {
1196 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1197 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001198 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001199 } else {
1200 // else make the attempt anyway - probably giving REQUEST_STARTED below
1201 if (DBG) {
1202 log("special network not available, but try anyway ni=" +
1203 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001204 }
1205 }
1206 }
1207
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001208 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001209
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001210 synchronized(this) {
1211 boolean addToList = true;
1212 if (restoreTimer < 0) {
1213 // In case there is no timer is specified for the feature,
1214 // make sure we don't add duplicate entry with the same request.
1215 for (FeatureUser u : mFeatureUsers) {
1216 if (u.isSameUser(f)) {
1217 // Duplicate user is found. Do not add.
1218 addToList = false;
1219 break;
1220 }
1221 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001222 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001223
1224 if (addToList) mFeatureUsers.add(f);
1225 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1226 // this gets used for per-pid dns when connected
1227 mNetRequestersPids[usedNetworkType].add(currentPid);
1228 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001229 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001230
1231 if (restoreTimer >= 0) {
1232 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1233 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1234 }
1235
1236 if ((ni.isConnectedOrConnecting() == true) &&
1237 !network.isTeardownRequested()) {
1238 if (ni.isConnected() == true) {
1239 final long token = Binder.clearCallingIdentity();
1240 try {
1241 // add the pid-specific dns
1242 handleDnsConfigurationChange(usedNetworkType);
1243 if (VDBG) log("special network already active");
1244 } finally {
1245 Binder.restoreCallingIdentity(token);
1246 }
Wink Savillea639b312012-07-10 12:37:54 -07001247 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001248 }
1249 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001250 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001251 }
1252
1253 // check if the radio in play can make another contact
1254 // assume if cannot for now
1255
1256 if (DBG) {
1257 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1258 feature);
1259 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001260 if (network.reconnect()) {
1261 return PhoneConstants.APN_REQUEST_STARTED;
1262 } else {
1263 return PhoneConstants.APN_REQUEST_FAILED;
1264 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001265 } else {
1266 // need to remember this unsupported request so we respond appropriately on stop
1267 synchronized(this) {
1268 mFeatureUsers.add(f);
1269 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1270 // this gets used for per-pid dns when connected
1271 mNetRequestersPids[usedNetworkType].add(currentPid);
1272 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001273 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001274 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001275 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001276 }
Wink Savillea639b312012-07-10 12:37:54 -07001277 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001278 } finally {
1279 if (DBG) {
1280 final long execTime = SystemClock.elapsedRealtime() - startTime;
1281 if (execTime > 250) {
1282 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1283 } else {
1284 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1285 }
1286 }
1287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
1289
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001290 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001292 enforceChangePermission();
1293
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001294 int pid = getCallingPid();
1295 int uid = getCallingUid();
1296
1297 FeatureUser u = null;
1298 boolean found = false;
1299
1300 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001301 for (FeatureUser x : mFeatureUsers) {
1302 if (x.isSameUser(pid, uid, networkType, feature)) {
1303 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001304 found = true;
1305 break;
1306 }
1307 }
1308 }
1309 if (found && u != null) {
1310 // stop regardless of how many other time this proc had called start
1311 return stopUsingNetworkFeature(u, true);
1312 } else {
1313 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001314 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001315 return 1;
1316 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001317 }
1318
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001319 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1320 int networkType = u.mNetworkType;
1321 String feature = u.mFeature;
1322 int pid = u.mPid;
1323 int uid = u.mUid;
1324
1325 NetworkStateTracker tracker = null;
1326 boolean callTeardown = false; // used to carry our decision outside of sync block
1327
Wink Savillec9acde92011-09-21 11:05:43 -07001328 if (VDBG) {
1329 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001330 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001333 if (DBG) {
1334 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1335 ", net is invalid");
1336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 return -1;
1338 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001339
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001340 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1341 // sync block
1342 synchronized(this) {
1343 // check if this process still has an outstanding start request
1344 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001345 if (VDBG) {
1346 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1347 ", ignoring");
1348 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001349 return 1;
1350 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001351 u.unlinkDeathRecipient();
1352 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1353 // If we care about duplicate requests, check for that here.
1354 //
1355 // This is done to support the extension of a request - the app
1356 // can request we start the network feature again and renew the
1357 // auto-shutoff delay. Normal "stop" calls from the app though
1358 // do not pay attention to duplicate requests - in effect the
1359 // API does not refcount and a single stop will counter multiple starts.
1360 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001361 for (FeatureUser x : mFeatureUsers) {
1362 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001363 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001364 return 1;
1365 }
1366 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001367 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001368
repo syncaea743a2011-07-29 23:55:49 -07001369 // TODO - move to individual network trackers
1370 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1371
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001372 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001373 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001374 if (DBG) {
1375 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1376 " no known tracker for used net type " + usedNetworkType);
1377 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001378 return -1;
1379 }
1380 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001381 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001382 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001383
1384 final long token = Binder.clearCallingIdentity();
1385 try {
1386 reassessPidDns(pid, true);
1387 } finally {
1388 Binder.restoreCallingIdentity(token);
1389 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001390 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001391 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001392 if (VDBG) {
1393 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1394 " others still using it");
1395 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001396 return 1;
1397 }
1398 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001399 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001400 if (DBG) {
1401 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1402 " not a known feature - dropping");
1403 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001404 }
1405 }
Wink Savillec9acde92011-09-21 11:05:43 -07001406
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001407 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001408 if (DBG) {
1409 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1410 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001411 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001412 return 1;
1413 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001414 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417
1418 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001419 * @deprecated use requestRouteToHostAddress instead
1420 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 * Ensure that a network route exists to deliver traffic to the specified
1422 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001423 * @param networkType the type of the network over which traffic to the
1424 * specified host is to be routed
1425 * @param hostAddress the IP address of the host to which the route is
1426 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 * @return {@code true} on success, {@code false} on failure
1428 */
1429 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001430 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1431
1432 if (inetAddress == null) {
1433 return false;
1434 }
1435
1436 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1437 }
1438
1439 /**
1440 * Ensure that a network route exists to deliver traffic to the specified
1441 * host via the specified network interface.
1442 * @param networkType the type of the network over which traffic to the
1443 * specified host is to be routed
1444 * @param hostAddress the IP address of the host to which the route is
1445 * desired
1446 * @return {@code true} on success, {@code false} on failure
1447 */
1448 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001450 if (mProtectedNetworks.contains(networkType)) {
1451 enforceConnectivityInternalPermission();
1452 }
1453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001455 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 return false;
1457 }
1458 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001459 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001460
Irfan Sheriffda6da092012-08-16 12:49:23 -07001461 if (tracker == null || (netState != DetailedState.CONNECTED &&
1462 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001463 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001464 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001465 log("requestRouteToHostAddress on down network "
1466 + "(" + networkType + ") - dropped"
1467 + " tracker=" + tracker
1468 + " netState=" + netState
1469 + " isTeardownRequested="
1470 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001471 }
1472 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001474 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001475 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001476 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001477 LinkProperties lp = tracker.getLinkProperties();
Wink Savilleab9321d2013-06-29 21:10:57 -07001478 boolean ok = addRouteToAddress(lp, addr);
1479 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1480 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001481 } catch (UnknownHostException e) {
1482 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1483 } finally {
1484 Binder.restoreCallingIdentity(token);
1485 }
Wink Savilleab9321d2013-06-29 21:10:57 -07001486 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001487 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001488 }
1489
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001490 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001491 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001492 }
1493
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001494 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001495 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001496 }
1497
Robert Greenwaltad55d352011-07-22 11:55:33 -07001498 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001499 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001500 }
1501
1502 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001503 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001504 }
1505
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001506 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1507 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001508 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001509 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001510 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001511 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001512 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001513 if (bestRoute.getGateway().equals(addr)) {
1514 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001515 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001516 } else {
1517 // if we will connect to this through another route, add a direct route
1518 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001519 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001520 }
1521 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001522 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001523 }
1524
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001525 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1526 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001527 if ((lp == null) || (r == null)) {
1528 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001529 return false;
1530 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001531
1532 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001533 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001534 return false;
1535 }
1536
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001537 String ifaceName = r.getInterface();
1538 if(ifaceName == null) {
1539 loge("Error modifying route - no interface name");
1540 return false;
1541 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001542 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001543 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001544 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001545 if (bestRoute.getGateway().equals(r.getGateway())) {
1546 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001547 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001548 } else {
1549 // if we will connect to our gateway through another route, add a direct
1550 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001551 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1552 bestRoute.getGateway(),
1553 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001554 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001555 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001556 }
1557 }
1558 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001559 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001560 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001561 if (toDefaultTable) {
1562 mAddedRoutes.add(r); // only track default table - only one apps can effect
1563 mNetd.addRoute(ifaceName, r);
1564 } else {
1565 mNetd.addSecondaryRoute(ifaceName, r);
1566 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001567 } catch (Exception e) {
1568 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001569 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001570 return false;
1571 }
1572 } else {
1573 // if we remove this one and there are no more like it, then refcount==0 and
1574 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001575 if (toDefaultTable) {
1576 mAddedRoutes.remove(r);
1577 if (mAddedRoutes.contains(r) == false) {
1578 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1579 try {
1580 mNetd.removeRoute(ifaceName, r);
1581 } catch (Exception e) {
1582 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001583 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001584 return false;
1585 }
1586 } else {
1587 if (VDBG) log("not removing " + r + " as it's still in use");
1588 }
1589 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001590 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001591 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001592 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001593 } catch (Exception e) {
1594 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001595 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001596 return false;
1597 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001598 }
1599 }
1600 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602
1603 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001604 * @see ConnectivityManager#getMobileDataEnabled()
1605 */
1606 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001607 // TODO: This detail should probably be in DataConnectionTracker's
1608 // which is where we store the value and maybe make this
1609 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001610 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001611 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1612 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001613 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001614 return retVal;
1615 }
1616
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001617 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001618 enforceConnectivityInternalPermission();
1619
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001620 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1621 (met ? ENABLED : DISABLED), networkType));
1622 }
1623
1624 private void handleSetDependencyMet(int networkType, boolean met) {
1625 if (mNetTrackers[networkType] != null) {
1626 if (DBG) {
1627 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1628 }
1629 mNetTrackers[networkType].setDependencyMet(met);
1630 }
1631 }
1632
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001633 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1634 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001635 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001636 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001637 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001638 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001639 }
1640
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001641 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001642 // skip update when we've already applied rules
1643 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1644 if (oldRules == uidRules) return;
1645
1646 mUidRules.put(uid, uidRules);
1647 }
1648
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001649 // TODO: notify UID when it has requested targeted updates
1650 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001651
1652 @Override
1653 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001654 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001655 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001656 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001657 }
1658
1659 synchronized (mRulesLock) {
1660 mMeteredIfaces.clear();
1661 for (String iface : meteredIfaces) {
1662 mMeteredIfaces.add(iface);
1663 }
1664 }
1665 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001666
1667 @Override
1668 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1669 // caller is NPMS, since we only register with them
1670 if (LOGD_RULES) {
1671 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1672 }
1673
1674 // kick off connectivity change broadcast for active network, since
1675 // global background policy change is radical.
1676 final int networkType = mActiveDefaultNetwork;
1677 if (isNetworkTypeValid(networkType)) {
1678 final NetworkStateTracker tracker = mNetTrackers[networkType];
1679 if (tracker != null) {
1680 final NetworkInfo info = tracker.getNetworkInfo();
1681 if (info != null && info.isConnected()) {
1682 sendConnectedBroadcast(info);
1683 }
1684 }
1685 }
1686 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001687 };
1688
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001689 /**
1690 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1691 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001692 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001693 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001694 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001695
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001697 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001698 }
1699
1700 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001701 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001702 if (VDBG) {
1703 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001704 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001705 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1706 }
tk.munb97d34c2012-01-06 10:43:52 +09001707 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1708 if (VDBG) {
1709 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1710 }
1711 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1712 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001713 }
1714
1715 @Override
1716 public void setPolicyDataEnable(int networkType, boolean enabled) {
1717 // only someone like NPMS should only be calling us
1718 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1719
1720 mHandler.sendMessage(mHandler.obtainMessage(
1721 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1722 }
1723
1724 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1725 if (isNetworkTypeValid(networkType)) {
1726 final NetworkStateTracker tracker = mNetTrackers[networkType];
1727 if (tracker != null) {
1728 tracker.setPolicyDataEnable(enabled);
1729 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001730 }
1731 }
1732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001734 mContext.enforceCallingOrSelfPermission(
1735 android.Manifest.permission.ACCESS_NETWORK_STATE,
1736 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738
1739 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001740 mContext.enforceCallingOrSelfPermission(
1741 android.Manifest.permission.CHANGE_NETWORK_STATE,
1742 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001745 // TODO Make this a special check when it goes public
1746 private void enforceTetherChangePermission() {
1747 mContext.enforceCallingOrSelfPermission(
1748 android.Manifest.permission.CHANGE_NETWORK_STATE,
1749 "ConnectivityService");
1750 }
1751
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001752 private void enforceTetherAccessPermission() {
1753 mContext.enforceCallingOrSelfPermission(
1754 android.Manifest.permission.ACCESS_NETWORK_STATE,
1755 "ConnectivityService");
1756 }
1757
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001758 private void enforceConnectivityInternalPermission() {
1759 mContext.enforceCallingOrSelfPermission(
1760 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1761 "ConnectivityService");
1762 }
1763
Chad Brubakerd475c702013-07-11 13:29:30 -07001764 private void enforceMarkNetworkSocketPermission() {
1765 //Media server special case
1766 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1767 return;
1768 }
1769 mContext.enforceCallingOrSelfPermission(
1770 android.Manifest.permission.MARK_NETWORK_SOCKET,
1771 "ConnectivityService");
1772 }
1773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001775 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1776 * network, we ignore it. If it is for the active network, we send out a
1777 * broadcast. But first, we check whether it might be possible to connect
1778 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 * @param info the {@code NetworkInfo} for the network
1780 */
1781 private void handleDisconnect(NetworkInfo info) {
1782
Robert Greenwalt42acef32009-08-12 16:08:25 -07001783 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784
Robert Greenwalt42acef32009-08-12 16:08:25 -07001785 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001786
1787 // Remove idletimer previously setup in {@code handleConnect}
1788 removeDataActivityTracking(prevNetType);
1789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 /*
1791 * If the disconnected network is not the active one, then don't report
1792 * this as a loss of connectivity. What probably happened is that we're
1793 * getting the disconnect for a network that we explicitly disabled
1794 * in accordance with network preference policies.
1795 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001796 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001797 List<Integer> pids = mNetRequestersPids[prevNetType];
1798 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001799 // will remove them because the net's no longer connected
1800 // need to do this now as only now do we know the pids and
1801 // can properly null things that are no longer referenced.
1802 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001807 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001808 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 if (info.isFailover()) {
1810 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1811 info.setFailover(false);
1812 }
1813 if (info.getReason() != null) {
1814 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1815 }
1816 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001817 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1818 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001820
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001821 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001822 tryFailover(prevNetType);
1823 if (mActiveDefaultNetwork != -1) {
1824 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001825 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1826 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001827 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001828 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1829 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001830 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001831 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001832
1833 // Reset interface if no other connections are using the same interface
1834 boolean doReset = true;
1835 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1836 if (linkProperties != null) {
1837 String oldIface = linkProperties.getInterfaceName();
1838 if (TextUtils.isEmpty(oldIface) == false) {
1839 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1840 if (networkStateTracker == null) continue;
1841 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1842 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1843 LinkProperties l = networkStateTracker.getLinkProperties();
1844 if (l == null) continue;
1845 if (oldIface.equals(l.getInterfaceName())) {
1846 doReset = false;
1847 break;
1848 }
1849 }
1850 }
1851 }
1852 }
1853
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001854 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001855 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001856
Jeff Sharkey961e3042011-08-29 16:02:57 -07001857 final Intent immediateIntent = new Intent(intent);
1858 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1859 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001860 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001861 /*
1862 * If the failover network is already connected, then immediately send
1863 * out a followup broadcast indicating successful failover
1864 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001865 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001866 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1867 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001868 }
1869 }
1870
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001871 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001872 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001873 * If this is a default network, check if other defaults are available.
1874 * Try to reconnect on all available and let them hash it out when
1875 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001876 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001877 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001878 if (mActiveDefaultNetwork == prevNetType) {
1879 mActiveDefaultNetwork = -1;
1880 }
1881
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001882 // don't signal a reconnect for anything lower or equal priority than our
1883 // current connected default
1884 // TODO - don't filter by priority now - nice optimization but risky
1885// int currentPriority = -1;
1886// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001887// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001888// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001889 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001890 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001891 if (mNetConfigs[checkType] == null) continue;
1892 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001893 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001894
1895// Enabling the isAvailable() optimization caused mobile to not get
1896// selected if it was in the middle of error handling. Specifically
1897// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1898// would not be available and we wouldn't get connected to anything.
1899// So removing the isAvailable() optimization below for now. TODO: This
1900// optimization should work and we need to investigate why it doesn't work.
1901// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1902// complete before it is really complete.
1903// if (!mNetTrackers[checkType].isAvailable()) continue;
1904
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001905// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001906
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001907 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1908 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1909 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1910 checkInfo.setFailover(true);
1911 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001912 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001913 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
1917
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001918 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001919 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001920 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1921 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001922 }
1923
Wink Saville628b0852011-08-04 15:01:58 -07001924 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001925 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1926 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001927 }
1928
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001929 private void sendInetConditionBroadcast(NetworkInfo info) {
1930 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1931 }
1932
Wink Saville628b0852011-08-04 15:01:58 -07001933 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001934 if (mLockdownTracker != null) {
1935 info = mLockdownTracker.augmentNetworkInfo(info);
1936 }
1937
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001938 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001939 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001940 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 if (info.isFailover()) {
1942 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1943 info.setFailover(false);
1944 }
1945 if (info.getReason() != null) {
1946 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1947 }
1948 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001949 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1950 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001952 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001953 return intent;
1954 }
1955
1956 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1957 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1958 }
1959
1960 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1961 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963
Haoyu Baidb3c8672012-06-20 14:29:57 -07001964 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1965 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1966 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1967 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001968 final long ident = Binder.clearCallingIdentity();
1969 try {
1970 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1971 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1972 } finally {
1973 Binder.restoreCallingIdentity(ident);
1974 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001975 }
1976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 /**
1978 * Called when an attempt to fail over to another network has failed.
1979 * @param info the {@link NetworkInfo} for the failed network
1980 */
1981 private void handleConnectionFailure(NetworkInfo info) {
1982 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983
Robert Greenwalt42acef32009-08-12 16:08:25 -07001984 String reason = info.getReason();
1985 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001986
Robert Greenwalt572172b2010-10-08 16:35:52 -07001987 String reasonText;
1988 if (reason == null) {
1989 reasonText = ".";
1990 } else {
1991 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001993 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001994
1995 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001996 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001997 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001998 if (getActiveNetworkInfo() == null) {
1999 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2000 }
2001 if (reason != null) {
2002 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2003 }
2004 if (extraInfo != null) {
2005 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2006 }
2007 if (info.isFailover()) {
2008 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2009 info.setFailover(false);
2010 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002011
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002012 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002013 tryFailover(info.getType());
2014 if (mActiveDefaultNetwork != -1) {
2015 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002016 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2017 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07002018 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002019 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2020 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002021 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002022
Robert Greenwalt029be812010-09-20 18:01:43 -07002023 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07002024
2025 final Intent immediateIntent = new Intent(intent);
2026 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2027 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002028 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002029 /*
2030 * If the failover network is already connected, then immediately send
2031 * out a followup broadcast indicating successful failover
2032 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002033 if (mActiveDefaultNetwork != -1) {
2034 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002035 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002036 }
2037
2038 private void sendStickyBroadcast(Intent intent) {
2039 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002040 if (!mSystemReady) {
2041 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002042 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002043 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07002044 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002045 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002046 }
2047
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002048 final long ident = Binder.clearCallingIdentity();
2049 try {
2050 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2051 } finally {
2052 Binder.restoreCallingIdentity(ident);
2053 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002054 }
2055 }
2056
Wink Saville628b0852011-08-04 15:01:58 -07002057 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2058 if (delayMs <= 0) {
2059 sendStickyBroadcast(intent);
2060 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002061 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002062 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2063 + intent.getAction());
2064 }
Wink Saville628b0852011-08-04 15:01:58 -07002065 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2066 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2067 }
2068 }
2069
Mike Lockwood0f79b542009-08-14 14:18:49 -04002070 void systemReady() {
2071 synchronized(this) {
2072 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002073 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002074 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002075 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002076 }
2077 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002078 // load the global proxy at startup
2079 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002080
2081 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2082 // for user to unlock device.
2083 if (!updateLockdownVpn()) {
2084 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2085 mContext.registerReceiver(mUserPresentReceiver, filter);
2086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
2088
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002089 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2090 @Override
2091 public void onReceive(Context context, Intent intent) {
2092 // Try creating lockdown tracker, since user present usually means
2093 // unlocked keystore.
2094 if (updateLockdownVpn()) {
2095 mContext.unregisterReceiver(this);
2096 }
2097 }
2098 };
2099
Irfan Sheriffda6da092012-08-16 12:49:23 -07002100 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2101 if ((type != mNetworkPreference &&
2102 mNetConfigs[mActiveDefaultNetwork].priority >
2103 mNetConfigs[type].priority) ||
2104 mNetworkPreference == mActiveDefaultNetwork) return false;
2105 return true;
2106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107
Irfan Sheriffda6da092012-08-16 12:49:23 -07002108 private void handleConnect(NetworkInfo info) {
2109 final int newNetType = info.getType();
2110
2111 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 // snapshot isFailover, because sendConnectedBroadcast() resets it
2114 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002115 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002116 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117
Robert Greenwalt42acef32009-08-12 16:08:25 -07002118 // if this is a default net and other default is running
2119 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002120 if (mNetConfigs[newNetType].isDefault()) {
2121 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2122 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002123 // tear down the other
2124 NetworkStateTracker otherNet =
2125 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002126 if (DBG) {
2127 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002128 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002129 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002130 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002131 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002132 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002133 return;
2134 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002135 } else {
2136 // don't accept this one
2137 if (VDBG) {
2138 log("Not broadcasting CONNECT_ACTION " +
2139 "to torn down network " + info.getTypeName());
2140 }
2141 teardown(thisNet);
2142 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002143 }
2144 }
2145 synchronized (ConnectivityService.this) {
2146 // have a new default network, release the transition wakelock in a second
2147 // if it's held. The second pause is to allow apps to reconnect over the
2148 // new network
2149 if (mNetTransitionWakeLock.isHeld()) {
2150 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002151 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002152 mNetTransitionWakeLockSerialNumber, 0),
2153 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002154 }
2155 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002156 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002157 // this will cause us to come up initially as unconnected and switching
2158 // to connected after our normal pause unless somebody reports us as reall
2159 // disconnected
2160 mDefaultInetConditionPublished = 0;
2161 mDefaultConnectionSequence++;
2162 mInetConditionChangeInFlight = false;
2163 // Don't do this - if we never sign in stay, grey
2164 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002167 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002168 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002169 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002170
2171 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002172 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002173 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002174 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002175 } catch (RemoteException e) {
2176 // ignored; service lives in system_server
2177 }
2178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180
Irfan Sheriffda6da092012-08-16 12:49:23 -07002181 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2182 if (DBG) log("Captive portal check " + info);
2183 int type = info.getType();
2184 final NetworkStateTracker thisNet = mNetTrackers[type];
2185 if (mNetConfigs[type].isDefault()) {
2186 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2187 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2188 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002189 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002190 return;
2191 } else {
2192 if (DBG) log("Tear down low priority net " + info.getTypeName());
2193 teardown(thisNet);
2194 return;
2195 }
2196 }
2197 }
2198
2199 thisNet.captivePortalCheckComplete();
2200 }
2201
2202 /** @hide */
2203 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002204 enforceConnectivityInternalPermission();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002205 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002206 }
2207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002209 * Setup data activity tracking for the given network interface.
2210 *
2211 * Every {@code setupDataActivityTracking} should be paired with a
2212 * {@link removeDataActivityTracking} for cleanup.
2213 */
2214 private void setupDataActivityTracking(int type) {
2215 final NetworkStateTracker thisNet = mNetTrackers[type];
2216 final String iface = thisNet.getLinkProperties().getInterfaceName();
2217
2218 final int timeout;
2219
2220 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002221 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2222 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002223 0);
2224 // Canonicalize mobile network type
2225 type = ConnectivityManager.TYPE_MOBILE;
2226 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002227 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2228 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002229 0);
2230 } else {
2231 // do not track any other networks
2232 timeout = 0;
2233 }
2234
2235 if (timeout > 0 && iface != null) {
2236 try {
2237 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2238 } catch (RemoteException e) {
2239 }
2240 }
2241 }
2242
2243 /**
2244 * Remove data activity tracking when network disconnects.
2245 */
2246 private void removeDataActivityTracking(int type) {
2247 final NetworkStateTracker net = mNetTrackers[type];
2248 final String iface = net.getLinkProperties().getInterfaceName();
2249
2250 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2251 ConnectivityManager.TYPE_WIFI == type)) {
2252 try {
2253 // the call fails silently if no idletimer setup for this interface
2254 mNetd.removeIdleTimer(iface);
2255 } catch (RemoteException e) {
2256 }
2257 }
2258 }
2259
2260 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002261 * After a change in the connectivity state of a network. We're mainly
2262 * concerned with making sure that the list of DNS servers is set up
2263 * according to which networks are connected, and ensuring that the
2264 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002266 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002267 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002270 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002271 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002273 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002274
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002275 LinkProperties curLp = mCurrentLinkProperties[netType];
2276 LinkProperties newLp = null;
2277
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002278 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002279 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002280 if (VDBG) {
2281 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2282 " doReset=" + doReset + " resetMask=" + resetMask +
2283 "\n curLp=" + curLp +
2284 "\n newLp=" + newLp);
2285 }
2286
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002287 if (curLp != null) {
2288 if (curLp.isIdenticalInterfaceName(newLp)) {
2289 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2290 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2291 for (LinkAddress linkAddr : car.removed) {
2292 if (linkAddr.getAddress() instanceof Inet4Address) {
2293 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2294 }
2295 if (linkAddr.getAddress() instanceof Inet6Address) {
2296 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2297 }
Wink Savillee8222252011-07-13 13:44:13 -07002298 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002299 if (DBG) {
2300 log("handleConnectivityChange: addresses changed" +
2301 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2302 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002303 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002304 } else {
2305 if (DBG) {
2306 log("handleConnectivityChange: address are the same reset per doReset" +
2307 " linkProperty[" + netType + "]:" +
2308 " resetMask=" + resetMask);
2309 }
Wink Savillee8222252011-07-13 13:44:13 -07002310 }
2311 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002312 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002313 if (DBG) {
2314 log("handleConnectivityChange: interface not not equivalent reset both" +
2315 " linkProperty[" + netType + "]:" +
2316 " resetMask=" + resetMask);
2317 }
Wink Savillee8222252011-07-13 13:44:13 -07002318 }
Wink Savillee8222252011-07-13 13:44:13 -07002319 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002320 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002321 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002322 }
2323 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002324 if (VDBG) {
2325 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2326 " doReset=" + doReset + " resetMask=" + resetMask +
2327 "\n curLp=" + curLp +
2328 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002331 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002332 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002333
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002334 if (resetMask != 0 || resetDns) {
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002335 if (curLp != null) {
2336 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002337 if (TextUtils.isEmpty(iface) == false) {
2338 if (resetMask != 0) {
2339 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2340 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002341
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002342 // Tell VPN the interface is down. It is a temporary
2343 // but effective fix to make VPN aware of the change.
2344 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002345 synchronized(mVpns) {
2346 for (int i = 0; i < mVpns.size(); i++) {
2347 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2348 }
2349 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002350 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002351 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002352 if (resetDns) {
2353 flushVmDnsCache();
2354 if (VDBG) log("resetting DNS cache for " + iface);
2355 try {
2356 mNetd.flushInterfaceDnsCache(iface);
2357 } catch (Exception e) {
2358 // never crash - catch them all
2359 if (DBG) loge("Exception resetting dns cache: " + e);
2360 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002361 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002362 } else {
2363 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002364 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002365 }
2366 }
2367 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002368
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002369 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002370 NetworkStateTracker tracker = mNetTrackers[netType];
2371 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002372 // If the connection was previously using clat, but is not using it now, stop the clat
2373 // daemon. Normally, this happens automatically when the connection disconnects, but if
2374 // the disconnect is not reported, or if the connection's LinkProperties changed for
2375 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2376 // still be running. If it's not running, then stopping it is a no-op.
2377 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2378 mClat.stopClat();
2379 }
2380 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002381 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2382 mClat.startClat(tracker);
2383 } else {
2384 mClat.stopClat();
2385 }
2386 }
2387
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002388 // TODO: Temporary notifying upstread change to Tethering.
2389 // @see bug/4455071
2390 /** Notify TetheringService if interface name has been changed. */
2391 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002392 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002393 if (isTetheringSupported()) {
2394 mTethering.handleTetherIfaceChange();
2395 }
2396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002399 /**
2400 * Add and remove routes using the old properties (null if not previously connected),
2401 * new properties (null if becoming disconnected). May even be double null, which
2402 * is a noop.
2403 * Uses isLinkDefault to determine if default routes should be set or conversely if
2404 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002405 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002406 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002407 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2408 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002409 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002410 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2411 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002412 if (curLp != null) {
2413 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002414 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002415 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002416 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002417 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002418 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002419 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002420
Robert Greenwaltf125a092011-08-15 12:31:55 -07002421 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2422
Robert Greenwaltad55d352011-07-22 11:55:33 -07002423 for (RouteInfo r : routeDiff.removed) {
2424 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002425 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2426 }
2427 if (isLinkDefault == false) {
2428 // remove from a secondary route table
2429 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002430 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002431 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002432
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002433 if (!isLinkDefault) {
2434 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002435 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002436 // routes changed - remove all old dns entries and add new
2437 if (curLp != null) {
2438 for (InetAddress oldDns : curLp.getDnses()) {
2439 removeRouteToAddress(curLp, oldDns);
2440 }
2441 }
2442 if (newLp != null) {
2443 for (InetAddress newDns : newLp.getDnses()) {
2444 addRouteToAddress(newLp, newDns);
2445 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002446 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002447 } else {
2448 // no change in routes, check for change in dns themselves
2449 for (InetAddress oldDns : dnsDiff.removed) {
2450 removeRouteToAddress(curLp, oldDns);
2451 }
2452 for (InetAddress newDns : dnsDiff.added) {
2453 addRouteToAddress(newLp, newDns);
2454 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002455 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002456 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002457
2458 for (RouteInfo r : routeDiff.added) {
2459 if (isLinkDefault || ! r.isDefaultRoute()) {
2460 addRoute(newLp, r, TO_DEFAULT_TABLE);
2461 } else {
2462 // add to a secondary route table
2463 addRoute(newLp, r, TO_SECONDARY_TABLE);
2464
2465 // many radios add a default route even when we don't want one.
2466 // remove the default route unless somebody else has asked for it
2467 String ifaceName = newLp.getInterfaceName();
2468 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2469 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2470 try {
2471 mNetd.removeRoute(ifaceName, r);
2472 } catch (Exception e) {
2473 // never crash - catch them all
2474 if (DBG) loge("Exception trying to remove a route: " + e);
2475 }
2476 }
2477 }
2478 }
2479
Robert Greenwaltf125a092011-08-15 12:31:55 -07002480 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002481 }
2482
2483
Irfan Sheriffd649c122010-06-09 15:39:36 -07002484 /**
2485 * Reads the network specific TCP buffer sizes from SystemProperties
2486 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2487 * wide use
2488 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002489 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002490 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002491 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002492
Jeff Sharkey899223b2012-08-04 15:24:58 -07002493 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002494 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002495
2496 // Setting to default values so we won't be stuck to previous values
2497 key = "net.tcp.buffersize.default";
2498 bufferSizes = SystemProperties.get(key);
2499 }
2500
2501 // Set values in kernel
2502 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002503 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002504 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002505 + "] which comes from [" + key + "]");
2506 }
2507 setBufferSize(bufferSizes);
2508 }
2509 }
2510
2511 /**
2512 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2513 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2514 *
2515 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2516 * writeMin, writeInitial, writeMax"
2517 */
2518 private void setBufferSize(String bufferSizes) {
2519 try {
2520 String[] values = bufferSizes.split(",");
2521
2522 if (values.length == 6) {
2523 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002524 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2525 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2526 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2527 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2528 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2529 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002530 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002531 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002532 }
2533 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002534 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002535 }
2536 }
2537
Robert Greenwalt42acef32009-08-12 16:08:25 -07002538 /**
2539 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2540 * on the highest priority active net which this process requested.
2541 * If there aren't any, clear it out
2542 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002543 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002544 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002545 if (VDBG) log("reassessPidDns for pid " + pid);
2546 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002547 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002548 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002549 continue;
2550 }
2551 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002552 if (nt.getNetworkInfo().isConnected() &&
2553 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002554 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002555 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002556 if (mNetRequestersPids[i].contains(myPid)) {
2557 try {
2558 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2559 } catch (Exception e) {
2560 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002561 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002562 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002563 }
2564 }
2565 }
2566 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002567 try {
2568 mNetd.clearDnsInterfaceForPid(pid);
2569 } catch (Exception e) {
2570 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002571 }
2572 }
2573
Mattias Falk8b47b362011-08-23 14:15:13 +02002574 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002575 /*
2576 * Tell the VMs to toss their DNS caches
2577 */
2578 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2579 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002580 /*
2581 * Connectivity events can happen before boot has completed ...
2582 */
2583 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002584 final long ident = Binder.clearCallingIdentity();
2585 try {
2586 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2587 } finally {
2588 Binder.restoreCallingIdentity(ident);
2589 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002590 }
2591
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002592 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002593 private void updateDnsLocked(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002594 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002595 int last = 0;
2596 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002597 dnses = new ArrayList();
2598 dnses.add(mDefaultDns);
2599 if (DBG) {
2600 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002601 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002602 }
2603
Mattias Falk8b47b362011-08-23 14:15:13 +02002604 try {
2605 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002606 for (InetAddress dns : dnses) {
2607 ++last;
2608 String key = "net.dns" + last;
2609 String value = dns.getHostAddress();
2610 SystemProperties.set(key, value);
2611 }
2612 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2613 String key = "net.dns" + i;
2614 SystemProperties.set(key, "");
2615 }
2616 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002617 } catch (Exception e) {
2618 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002619 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002620 }
2621
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002622 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002623 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002624 NetworkStateTracker nt = mNetTrackers[netType];
2625 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002626 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002627 if (p == null) return;
2628 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002629 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002630 String network = nt.getNetworkInfo().getTypeName();
2631 synchronized (mDnsLock) {
2632 if (!mDnsOverridden) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002633 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002634 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002635 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002636 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002637 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002638 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002639 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002640 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002641 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002642 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002643 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002644 List<Integer> pids = mNetRequestersPids[netType];
2645 for (Integer pid : pids) {
2646 try {
2647 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2648 } catch (Exception e) {
2649 Slog.e(TAG, "exception setting interface for pid: " + e);
2650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 }
2652 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002653 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002655 }
2656
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002657 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002658 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2659 NETWORK_RESTORE_DELAY_PROP_NAME);
2660 if(restoreDefaultNetworkDelayStr != null &&
2661 restoreDefaultNetworkDelayStr.length() != 0) {
2662 try {
2663 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2664 } catch (NumberFormatException e) {
2665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002667 // if the system property isn't set, use the value for the apn type
2668 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2669
2670 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2671 (mNetConfigs[networkType] != null)) {
2672 ret = mNetConfigs[networkType].restoreTime;
2673 }
2674 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
2676
2677 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002678 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2679 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002680 if (mContext.checkCallingOrSelfPermission(
2681 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002683 pw.println("Permission Denial: can't dump ConnectivityService " +
2684 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2685 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 return;
2687 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002688
2689 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002691 for (int i = 0; i < mNetTrackers.length; i++) {
2692 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002693 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002694 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2695 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002696 if (nst.getNetworkInfo().isConnected()) {
2697 pw.println("Active network: " + nst.getNetworkInfo().
2698 getTypeName());
2699 }
2700 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002701 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002702 pw.println(nst);
2703 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002704 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002707
2708 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002709 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002710 for (int net : mPriorityList) {
2711 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002712 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002713 pidString = pidString + pid.toString() + ", ";
2714 }
2715 pw.println(pidString);
2716 }
2717 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002718 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002719
2720 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002721 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002722 for (Object requester : mFeatureUsers) {
2723 pw.println(requester.toString());
2724 }
2725 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002726 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002727
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002728 synchronized (this) {
2729 pw.println("NetworkTranstionWakeLock is currently " +
2730 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2731 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2732 }
2733 pw.println();
2734
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002735 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002736
2737 if (mInetLog != null) {
2738 pw.println();
2739 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002740 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002741 for(int i = 0; i < mInetLog.size(); i++) {
2742 pw.println(mInetLog.get(i));
2743 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002744 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747
Robert Greenwalt42acef32009-08-12 16:08:25 -07002748 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002749 private class NetworkStateTrackerHandler extends Handler {
2750 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002751 super(looper);
2752 }
2753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 @Override
2755 public void handleMessage(Message msg) {
2756 NetworkInfo info;
2757 switch (msg.what) {
2758 case NetworkStateTracker.EVENT_STATE_CHANGED:
2759 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002760 int type = info.getType();
2761 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002762
Wink Savillec9acde92011-09-21 11:05:43 -07002763 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2764 (state == NetworkInfo.State.DISCONNECTED)) {
2765 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002766 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002767 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769
Wink Savillefde1ac92013-07-16 17:16:37 -07002770 // After booting we'll check once for mobile provisioning
2771 // if we've provisioned by and connected.
2772 if (!mFirstProvisioningCheckStarted
2773 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2774 Settings.Global.DEVICE_PROVISIONED, 0))
2775 && (state == NetworkInfo.State.CONNECTED)) {
2776 log("check provisioning after booting");
2777 mFirstProvisioningCheckStarted = true;
2778 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2779 }
2780
Jeff Sharkey2528b502012-11-09 15:57:02 -08002781 EventLogTags.writeConnectivityStateChanged(
2782 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002783
2784 if (info.getDetailedState() ==
2785 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002787 } else if (info.getDetailedState() ==
2788 DetailedState.CAPTIVE_PORTAL_CHECK) {
2789 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002790 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002792 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002794 // the logic here is, handle SUSPENDED the same as
2795 // DISCONNECTED. The only difference being we are
2796 // broadcasting an intent with NetworkInfo that's
2797 // suspended. This allows the applications an
2798 // opportunity to handle DISCONNECTED and SUSPENDED
2799 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002801 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 handleConnect(info);
2803 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002804 if (mLockdownTracker != null) {
2805 mLockdownTracker.onNetworkInfoChanged(info);
2806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002809 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002810 // TODO: Temporary allowing network configuration
2811 // change not resetting sockets.
2812 // @see bug/4455071
2813 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002815 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2816 info = (NetworkInfo) msg.obj;
2817 type = info.getType();
2818 updateNetworkSettings(mNetTrackers[type]);
2819 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002820 }
2821 }
2822 }
2823
2824 private class InternalHandler extends Handler {
2825 public InternalHandler(Looper looper) {
2826 super(looper);
2827 }
2828
2829 @Override
2830 public void handleMessage(Message msg) {
2831 NetworkInfo info;
2832 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002833 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002834 String causedBy = null;
2835 synchronized (ConnectivityService.this) {
2836 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2837 mNetTransitionWakeLock.isHeld()) {
2838 mNetTransitionWakeLock.release();
2839 causedBy = mNetTransitionWakeLockCausedBy;
2840 }
2841 }
2842 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002843 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002844 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002845 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002846 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002847 FeatureUser u = (FeatureUser)msg.obj;
2848 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002849 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002850 case EVENT_INET_CONDITION_CHANGE:
2851 {
2852 int netType = msg.arg1;
2853 int condition = msg.arg2;
2854 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002855 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002856 }
2857 case EVENT_INET_CONDITION_HOLD_END:
2858 {
2859 int netType = msg.arg1;
2860 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002861 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002862 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002863 }
2864 case EVENT_SET_NETWORK_PREFERENCE:
2865 {
2866 int preference = msg.arg1;
2867 handleSetNetworkPreference(preference);
2868 break;
2869 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002870 case EVENT_SET_MOBILE_DATA:
2871 {
2872 boolean enabled = (msg.arg1 == ENABLED);
2873 handleSetMobileData(enabled);
2874 break;
2875 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002876 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2877 {
2878 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002879 break;
2880 }
2881 case EVENT_SET_DEPENDENCY_MET:
2882 {
2883 boolean met = (msg.arg1 == ENABLED);
2884 handleSetDependencyMet(msg.arg2, met);
2885 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002886 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002887 case EVENT_RESTORE_DNS:
2888 {
2889 if (mActiveDefaultNetwork != -1) {
2890 handleDnsConfigurationChange(mActiveDefaultNetwork);
2891 }
2892 break;
2893 }
Wink Saville628b0852011-08-04 15:01:58 -07002894 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2895 {
2896 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002897 sendStickyBroadcast(intent);
2898 break;
2899 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002900 case EVENT_SET_POLICY_DATA_ENABLE: {
2901 final int networkType = msg.arg1;
2902 final boolean enabled = msg.arg2 == ENABLED;
2903 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002904 break;
2905 }
2906 case EVENT_VPN_STATE_CHANGED: {
2907 if (mLockdownTracker != null) {
2908 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2909 }
2910 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002911 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002912 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2913 int tag = mEnableFailFastMobileDataTag.get();
2914 if (msg.arg1 == tag) {
2915 MobileDataStateTracker mobileDst =
2916 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2917 if (mobileDst != null) {
2918 mobileDst.setEnableFailFastMobileData(msg.arg2);
2919 }
2920 } else {
2921 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2922 + " != tag:" + tag);
2923 }
2924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
2927 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002928
2929 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002930 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002931 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002932
2933 if (isTetheringSupported()) {
2934 return mTethering.tether(iface);
2935 } else {
2936 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2937 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002938 }
2939
2940 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002941 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002942 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002943
2944 if (isTetheringSupported()) {
2945 return mTethering.untether(iface);
2946 } else {
2947 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2948 }
2949 }
2950
2951 // javadoc from interface
2952 public int getLastTetherError(String iface) {
2953 enforceTetherAccessPermission();
2954
2955 if (isTetheringSupported()) {
2956 return mTethering.getLastTetherError(iface);
2957 } else {
2958 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2959 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002960 }
2961
2962 // TODO - proper iface API for selection by property, inspection, etc
2963 public String[] getTetherableUsbRegexs() {
2964 enforceTetherAccessPermission();
2965 if (isTetheringSupported()) {
2966 return mTethering.getTetherableUsbRegexs();
2967 } else {
2968 return new String[0];
2969 }
2970 }
2971
2972 public String[] getTetherableWifiRegexs() {
2973 enforceTetherAccessPermission();
2974 if (isTetheringSupported()) {
2975 return mTethering.getTetherableWifiRegexs();
2976 } else {
2977 return new String[0];
2978 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002979 }
2980
Danica Chang6fdd0c62010-08-11 14:54:43 -07002981 public String[] getTetherableBluetoothRegexs() {
2982 enforceTetherAccessPermission();
2983 if (isTetheringSupported()) {
2984 return mTethering.getTetherableBluetoothRegexs();
2985 } else {
2986 return new String[0];
2987 }
2988 }
2989
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002990 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002991 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002992 if (isTetheringSupported()) {
2993 return mTethering.setUsbTethering(enable);
2994 } else {
2995 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2996 }
2997 }
2998
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002999 // TODO - move iface listing, queries, etc to new module
3000 // javadoc from interface
3001 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003002 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003003 return mTethering.getTetherableIfaces();
3004 }
3005
3006 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003007 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003008 return mTethering.getTetheredIfaces();
3009 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003010
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07003011 @Override
3012 public String[] getTetheredIfacePairs() {
3013 enforceTetherAccessPermission();
3014 return mTethering.getTetheredIfacePairs();
3015 }
3016
Robert Greenwalt5a735062010-03-02 17:25:02 -08003017 public String[] getTetheringErroredIfaces() {
3018 enforceTetherAccessPermission();
3019 return mTethering.getErroredIfaces();
3020 }
3021
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003022 // if ro.tether.denied = true we default to no tethering
3023 // gservices could set the secure setting to 1 though to enable it on a build where it
3024 // had previously been turned off.
3025 public boolean isTetheringSupported() {
3026 enforceTetherAccessPermission();
3027 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003028 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3029 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08003030 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003031 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003032
3033 // An API NetworkStateTrackers can call when they lose their network.
3034 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3035 // whichever happens first. The timer is started by the first caller and not
3036 // restarted by subsequent callers.
3037 public void requestNetworkTransitionWakelock(String forWhom) {
3038 enforceConnectivityInternalPermission();
3039 synchronized (this) {
3040 if (mNetTransitionWakeLock.isHeld()) return;
3041 mNetTransitionWakeLockSerialNumber++;
3042 mNetTransitionWakeLock.acquire();
3043 mNetTransitionWakeLockCausedBy = forWhom;
3044 }
3045 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003046 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003047 mNetTransitionWakeLockSerialNumber, 0),
3048 mNetTransitionWakeLockTimeout);
3049 return;
3050 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003051
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003052 // 100 percent is full good, 0 is full bad.
3053 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003054 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003055 mContext.enforceCallingOrSelfPermission(
3056 android.Manifest.permission.STATUS_BAR,
3057 "ConnectivityService");
3058
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003059 if (DBG) {
3060 int pid = getCallingPid();
3061 int uid = getCallingUid();
3062 String s = pid + "(" + uid + ") reports inet is " +
3063 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3064 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3065 mInetLog.add(s);
3066 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3067 mInetLog.remove(0);
3068 }
3069 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003070 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003071 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3072 }
3073
3074 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003075 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003076 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003077 return;
3078 }
3079 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003080 if (DBG) log("handleInetConditionChange: net=" + netType +
3081 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003082 return;
3083 }
Wink Savillec9acde92011-09-21 11:05:43 -07003084 if (VDBG) {
3085 log("handleInetConditionChange: net=" +
3086 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003087 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003088 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003089 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003090 int delay;
3091 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003092 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003093 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003094 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003095 delay = Settings.Global.getInt(mContext.getContentResolver(),
3096 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003097 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003098 delay = Settings.Global.getInt(mContext.getContentResolver(),
3099 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003100 }
3101 mInetConditionChangeInFlight = true;
3102 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003103 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003104 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003105 // we've set the new condition, when this hold ends that will get picked up
3106 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003107 }
3108 }
3109
Wink Saville5b7573e2013-01-31 00:30:13 +00003110 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003111 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003112 log("handleInetConditionHoldEnd: net=" + netType +
3113 ", condition=" + mDefaultInetCondition +
3114 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003115 }
3116 mInetConditionChangeInFlight = false;
3117
3118 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003119 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003120 return;
3121 }
3122 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003123 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003124 return;
3125 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003126 // TODO: Figure out why this optimization sometimes causes a
3127 // change in mDefaultInetCondition to be missed and the
3128 // UI to not be updated.
3129 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3130 // if (DBG) log("no change in condition - aborting");
3131 // return;
3132 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003133 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3134 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003135 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003136 return;
3137 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003138 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003139 sendInetConditionBroadcast(networkInfo);
3140 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003141 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003142
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003143 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003144 // this information is already available as a world read/writable jvm property
3145 // so this API change wouldn't have a benifit. It also breaks the passing
3146 // of proxy info to all the JVMs.
3147 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003148 synchronized (mProxyLock) {
3149 if (mGlobalProxy != null) return mGlobalProxy;
3150 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003151 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003152 }
3153
3154 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003155 enforceConnectivityInternalPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003156 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003157 if (proxyProperties == mGlobalProxy) return;
3158 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3159 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3160
3161 String host = "";
3162 int port = 0;
3163 String exclList = "";
3164 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3165 mGlobalProxy = new ProxyProperties(proxyProperties);
3166 host = mGlobalProxy.getHost();
3167 port = mGlobalProxy.getPort();
3168 exclList = mGlobalProxy.getExclusionList();
3169 } else {
3170 mGlobalProxy = null;
3171 }
3172 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003173 final long token = Binder.clearCallingIdentity();
3174 try {
3175 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3176 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3177 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3178 exclList);
3179 } finally {
3180 Binder.restoreCallingIdentity(token);
3181 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003182 }
3183
3184 if (mGlobalProxy == null) {
3185 proxyProperties = mDefaultProxy;
3186 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003187 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003188 }
3189
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003190 private void loadGlobalProxy() {
3191 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003192 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3193 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3194 String exclList = Settings.Global.getString(res,
3195 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003196 if (!TextUtils.isEmpty(host)) {
3197 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003198 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003199 mGlobalProxy = proxyProperties;
3200 }
3201 }
3202 }
3203
Robert Greenwalt434203a2010-10-11 16:00:27 -07003204 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003205 // this information is already available as a world read/writable jvm property
3206 // so this API change wouldn't have a benifit. It also breaks the passing
3207 // of proxy info to all the JVMs.
3208 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003209 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003210 return mGlobalProxy;
3211 }
3212 }
3213
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003214 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3215 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3216 proxy = null;
3217 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003218 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003219 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003220 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003221 mDefaultProxy = proxy;
3222
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003223 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003224 if (!mDefaultProxyDisabled) {
3225 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003226 }
3227 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003228 }
3229
3230 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003231 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3232 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003233 if (!TextUtils.isEmpty(proxy)) {
3234 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003235 if (data.length == 0) {
3236 return;
3237 }
3238
Robert Greenwalt434203a2010-10-11 16:00:27 -07003239 String proxyHost = data[0];
3240 int proxyPort = 8080;
3241 if (data.length > 1) {
3242 try {
3243 proxyPort = Integer.parseInt(data[1]);
3244 } catch (NumberFormatException e) {
3245 return;
3246 }
3247 }
3248 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3249 setGlobalProxy(p);
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003250 } else {
3251 setGlobalProxy(null);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 }
3253 }
3254
3255 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003256 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003257 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003258 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003259 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3260 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003262 final long ident = Binder.clearCallingIdentity();
3263 try {
3264 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3265 } finally {
3266 Binder.restoreCallingIdentity(ident);
3267 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 }
3269
3270 private static class SettingsObserver extends ContentObserver {
3271 private int mWhat;
3272 private Handler mHandler;
3273 SettingsObserver(Handler handler, int what) {
3274 super(handler);
3275 mHandler = handler;
3276 mWhat = what;
3277 }
3278
3279 void observe(Context context) {
3280 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003281 resolver.registerContentObserver(Settings.Global.getUriFor(
3282 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003283 }
3284
3285 @Override
3286 public void onChange(boolean selfChange) {
3287 mHandler.obtainMessage(mWhat).sendToTarget();
3288 }
3289 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003290
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003291 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003292 Slog.d(TAG, s);
3293 }
3294
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003295 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003296 Slog.e(TAG, s);
3297 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003298
repo syncaea743a2011-07-29 23:55:49 -07003299 int convertFeatureToNetworkType(int networkType, String feature) {
3300 int usedNetworkType = networkType;
3301
3302 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3303 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3304 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3305 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3306 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3307 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3308 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3309 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3310 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3311 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3312 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3313 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3314 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3315 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3316 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3317 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3318 } else {
3319 Slog.e(TAG, "Can't match any mobile netTracker!");
3320 }
3321 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3322 if (TextUtils.equals(feature, "p2p")) {
3323 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3324 } else {
3325 Slog.e(TAG, "Can't match any wifi netTracker!");
3326 }
3327 } else {
3328 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003329 }
repo syncaea743a2011-07-29 23:55:49 -07003330 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003331 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003332
3333 private static <T> T checkNotNull(T value, String message) {
3334 if (value == null) {
3335 throw new NullPointerException(message);
3336 }
3337 return value;
3338 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003339
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003340 /**
3341 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003342 * VpnBuilder and not available in ConnectivityManager. Permissions
3343 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003344 * @hide
3345 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003346 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003347 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003348 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003349 try {
3350 int type = mActiveDefaultNetwork;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003351 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003352 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003353 synchronized(mVpns) {
3354 mVpns.get(user).protect(socket,
3355 mNetTrackers[type].getLinkProperties().getInterfaceName());
3356 }
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003357 return true;
3358 }
3359 } catch (Exception e) {
3360 // ignore
3361 } finally {
3362 try {
3363 socket.close();
3364 } catch (Exception e) {
3365 // ignore
3366 }
3367 }
3368 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003369 }
3370
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003371 /**
3372 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003373 * and not available in ConnectivityManager. Permissions are checked
3374 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003375 * @hide
3376 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003377 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003378 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003379 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003380 int user = UserHandle.getUserId(Binder.getCallingUid());
3381 synchronized(mVpns) {
3382 return mVpns.get(user).prepare(oldPackage, newPackage);
3383 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003384 }
3385
Chad Brubakerd475c702013-07-11 13:29:30 -07003386 @Override
3387 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3388 enforceMarkNetworkSocketPermission();
3389 final long token = Binder.clearCallingIdentity();
3390 try {
3391 int mark = mNetd.getMarkForUid(uid);
3392 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3393 if (mark == -1) {
3394 mark = 0;
3395 }
3396 NetworkUtils.markSocket(socket.getFd(), mark);
3397 } catch (RemoteException e) {
3398 } finally {
3399 Binder.restoreCallingIdentity(token);
3400 }
3401 }
3402
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003403 /**
3404 * Configure a TUN interface and return its file descriptor. Parameters
3405 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003406 * and not available in ConnectivityManager. Permissions are checked in
3407 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003408 * @hide
3409 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003410 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003411 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003412 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003413 int user = UserHandle.getUserId(Binder.getCallingUid());
3414 synchronized(mVpns) {
3415 return mVpns.get(user).establish(config);
3416 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003417 }
3418
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003419 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003420 * Start legacy VPN, controlling native daemons as needed. Creates a
3421 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003422 */
3423 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003424 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003425 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003426 final LinkProperties egress = getActiveLinkProperties();
3427 if (egress == null) {
3428 throw new IllegalStateException("Missing active network connection");
3429 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003430 int user = UserHandle.getUserId(Binder.getCallingUid());
3431 synchronized(mVpns) {
3432 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3433 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003434 }
3435
3436 /**
3437 * Return the information of the ongoing legacy VPN. This method is used
3438 * by VpnSettings and not available in ConnectivityManager. Permissions
3439 * are checked in Vpn class.
3440 * @hide
3441 */
3442 @Override
3443 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003444 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003445 int user = UserHandle.getUserId(Binder.getCallingUid());
3446 synchronized(mVpns) {
3447 return mVpns.get(user).getLegacyVpnInfo();
3448 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003449 }
3450
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003451 /**
3452 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3453 * through NetworkStateTracker since it works differently. For example, it
3454 * needs to override DNS servers but never takes the default routes. It
3455 * relies on another data network, and it could keep existing connections
3456 * alive after reconnecting, switching between networks, or even resuming
3457 * from deep sleep. Calls from applications should be done synchronously
3458 * to avoid race conditions. As these are all hidden APIs, refactoring can
3459 * be done whenever a better abstraction is developed.
3460 */
3461 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003462 private VpnCallback() {
3463 }
3464
Jeff Sharkey899223b2012-08-04 15:24:58 -07003465 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003466 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003467 }
3468
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003469 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003470 if (dnsServers == null) {
3471 restore();
3472 return;
3473 }
3474
3475 // Convert DNS servers into addresses.
3476 List<InetAddress> addresses = new ArrayList<InetAddress>();
3477 for (String address : dnsServers) {
3478 // Double check the addresses and remove invalid ones.
3479 try {
3480 addresses.add(InetAddress.parseNumericAddress(address));
3481 } catch (Exception e) {
3482 // ignore
3483 }
3484 }
3485 if (addresses.isEmpty()) {
3486 restore();
3487 return;
3488 }
3489
3490 // Concatenate search domains into a string.
3491 StringBuilder buffer = new StringBuilder();
3492 if (searchDomains != null) {
3493 for (String domain : searchDomains) {
3494 buffer.append(domain).append(' ');
3495 }
3496 }
3497 String domains = buffer.toString().trim();
3498
3499 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003500 synchronized (mDnsLock) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003501 updateDnsLocked("VPN", iface, addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003502 mDnsOverridden = true;
3503 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003504
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003505 // Temporarily disable the default proxy (not global).
3506 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003507 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003508 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003509 sendProxyBroadcast(null);
3510 }
3511 }
3512
3513 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003514 }
3515
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003516 public void restore() {
3517 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003518 if (mDnsOverridden) {
3519 mDnsOverridden = false;
3520 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003521 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003522 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003523 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003524 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003525 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003526 sendProxyBroadcast(mDefaultProxy);
3527 }
3528 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003529 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003530
3531 public void protect(ParcelFileDescriptor socket) {
3532 try {
3533 final int mark = mNetd.getMarkForProtect();
3534 NetworkUtils.markSocket(socket.getFd(), mark);
3535 } catch (RemoteException e) {
3536 }
3537 }
3538
3539 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3540 for (RouteInfo route : routes) {
3541 try {
3542 mNetd.setMarkedForwardingRoute(interfaze, route);
3543 } catch (RemoteException e) {
3544 }
3545 }
3546 }
3547
3548 public void setMarkedForwarding(String interfaze) {
3549 try {
3550 mNetd.setMarkedForwarding(interfaze);
3551 } catch (RemoteException e) {
3552 }
3553 }
3554
3555 public void clearMarkedForwarding(String interfaze) {
3556 try {
3557 mNetd.clearMarkedForwarding(interfaze);
3558 } catch (RemoteException e) {
3559 }
3560 }
3561
3562 public void addUserForwarding(String interfaze, int uid) {
3563 int uidStart = uid * UserHandle.PER_USER_RANGE;
3564 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3565 addUidForwarding(interfaze, uidStart, uidEnd);
3566 }
3567
3568 public void clearUserForwarding(String interfaze, int uid) {
3569 int uidStart = uid * UserHandle.PER_USER_RANGE;
3570 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3571 clearUidForwarding(interfaze, uidStart, uidEnd);
3572 }
3573
3574 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3575 try {
3576 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3577 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3578 } catch (RemoteException e) {
3579 }
3580
3581 }
3582
3583 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3584 try {
3585 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3586 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3587 } catch (RemoteException e) {
3588 }
3589
3590 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003591 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003592
3593 @Override
3594 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003595 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3596 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3597 return false;
3598 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003599
3600 // Tear down existing lockdown if profile was removed
3601 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3602 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003603 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003604 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3605 return false;
3606 }
3607
3608 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3609 final VpnProfile profile = VpnProfile.decode(
3610 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003611 int user = UserHandle.getUserId(Binder.getCallingUid());
3612 synchronized(mVpns) {
3613 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3614 profile));
3615 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003616 } else {
3617 setLockdownTracker(null);
3618 }
3619
3620 return true;
3621 }
3622
3623 /**
3624 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3625 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3626 */
3627 private void setLockdownTracker(LockdownVpnTracker tracker) {
3628 // Shutdown any existing tracker
3629 final LockdownVpnTracker existing = mLockdownTracker;
3630 mLockdownTracker = null;
3631 if (existing != null) {
3632 existing.shutdown();
3633 }
3634
3635 try {
3636 if (tracker != null) {
3637 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003638 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003639 mLockdownTracker = tracker;
3640 mLockdownTracker.init();
3641 } else {
3642 mNetd.setFirewallEnabled(false);
3643 }
3644 } catch (RemoteException e) {
3645 // ignored; NMS lives inside system_server
3646 }
3647 }
3648
3649 private void throwIfLockdownEnabled() {
3650 if (mLockdownEnabled) {
3651 throw new IllegalStateException("Unavailable in lockdown mode");
3652 }
3653 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003654
3655 public void supplyMessenger(int networkType, Messenger messenger) {
3656 enforceConnectivityInternalPermission();
3657
3658 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3659 mNetTrackers[networkType].supplyMessenger(messenger);
3660 }
3661 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003662
3663 public int findConnectionTypeForIface(String iface) {
3664 enforceConnectivityInternalPermission();
3665
3666 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3667 for (NetworkStateTracker tracker : mNetTrackers) {
3668 if (tracker != null) {
3669 LinkProperties lp = tracker.getLinkProperties();
3670 if (lp != null && iface.equals(lp.getInterfaceName())) {
3671 return tracker.getNetworkInfo().getType();
3672 }
3673 }
3674 }
3675 return ConnectivityManager.TYPE_NONE;
3676 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003677
3678 /**
3679 * Have mobile data fail fast if enabled.
3680 *
3681 * @param enabled DctConstants.ENABLED/DISABLED
3682 */
3683 private void setEnableFailFastMobileData(int enabled) {
3684 int tag;
3685
3686 if (enabled == DctConstants.ENABLED) {
3687 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3688 } else {
3689 tag = mEnableFailFastMobileDataTag.get();
3690 }
3691 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3692 enabled));
3693 }
3694
3695 @Override
Wink Savillec2fee242013-07-19 09:27:56 -07003696 public int checkMobileProvisioning(final boolean sendNotification, int suggestedTimeOutMs,
Wink Savilleab9321d2013-06-29 21:10:57 -07003697 final ResultReceiver resultReceiver) {
3698 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3699 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3700 + " resultReceiver=" + resultReceiver);
3701 enforceChangePermission();
3702
Wink Savillefde1ac92013-07-16 17:16:37 -07003703 mFirstProvisioningCheckStarted = true;
3704
Wink Savilleab9321d2013-06-29 21:10:57 -07003705 int timeOutMs = suggestedTimeOutMs;
3706 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3707 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3708 }
3709
Wink Saville68e6c642013-07-02 10:55:14 -07003710 // Check that mobile networks are supported
3711 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3712 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3713 log("checkMobileProvisioning: X no mobile network");
3714 if (resultReceiver != null) {
3715 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3716 }
3717 return timeOutMs;
3718 }
3719
Wink Savilleab9321d2013-06-29 21:10:57 -07003720 final long token = Binder.clearCallingIdentity();
3721 try {
3722 CheckMp checkMp = new CheckMp(mContext, this);
3723 CheckMp.CallBack cb = new CheckMp.CallBack() {
3724 @Override
3725 void onComplete(Integer result) {
3726 log("CheckMp.onComplete: result=" + result);
3727 if (resultReceiver != null) {
3728 log("CheckMp.onComplete: send result");
3729 resultReceiver.send(result, null);
3730 }
Wink Savillec2fee242013-07-19 09:27:56 -07003731 if (!sendNotification) {
3732 log("CheckMp.onComplete: done, not sending notification");
3733 return;
3734 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003735 NetworkInfo ni =
3736 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3737 switch(result) {
3738 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3739 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3740 log("CheckMp.onComplete: ignore, connected or no connection");
3741 break;
3742 }
3743 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3744 log("CheckMp.onComplete: warm sim");
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003745 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003746 if (TextUtils.isEmpty(url)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003747 url = getMobileRedirectedProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003748 }
3749 if (TextUtils.isEmpty(url) == false) {
3750 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3751 setNotificationVisible(true, ni, url);
3752 } else {
3753 log("CheckMp.onComplete: warm sim (redirected), no url");
3754 }
3755 break;
3756 }
3757 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3758 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003759 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003760 if (TextUtils.isEmpty(url) == false) {
3761 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3762 setNotificationVisible(true, ni, url);
3763 } else {
3764 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3765 }
3766 break;
3767 }
3768 default: {
3769 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3770 break;
3771 }
3772 }
3773 }
3774 };
3775 CheckMp.Params params =
3776 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3777 log("checkMobileProvisioning: params=" + params);
3778 setNotificationVisible(false, null, null);
3779 checkMp.execute(params);
3780 } finally {
3781 Binder.restoreCallingIdentity(token);
3782 log("checkMobileProvisioning: X");
3783 }
3784 return timeOutMs;
3785 }
3786
3787 static class CheckMp extends
3788 AsyncTask<CheckMp.Params, Void, Integer> {
3789 private static final String CHECKMP_TAG = "CheckMp";
3790 public static final int MAX_TIMEOUT_MS = 60000;
3791 private static final int SOCKET_TIMEOUT_MS = 5000;
3792 private Context mContext;
3793 private ConnectivityService mCs;
3794 private TelephonyManager mTm;
3795 private Params mParams;
3796
3797 /**
3798 * Parameters for AsyncTask.execute
3799 */
3800 static class Params {
3801 private String mUrl;
3802 private long mTimeOutMs;
3803 private CallBack mCb;
3804
3805 Params(String url, long timeOutMs, CallBack cb) {
3806 mUrl = url;
3807 mTimeOutMs = timeOutMs;
3808 mCb = cb;
3809 }
3810
3811 @Override
3812 public String toString() {
3813 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3814 }
3815 }
3816
3817 /**
3818 * The call back object passed in Params. onComplete will be called
3819 * on the main thread.
3820 */
3821 abstract static class CallBack {
3822 // Called on the main thread.
3823 abstract void onComplete(Integer result);
3824 }
3825
3826 public CheckMp(Context context, ConnectivityService cs) {
3827 mContext = context;
3828 mCs = cs;
3829
3830 // Setup access to TelephonyService we'll be using.
3831 mTm = (TelephonyManager) mContext.getSystemService(
3832 Context.TELEPHONY_SERVICE);
3833 }
3834
3835 /**
3836 * Get the default url to use for the test.
3837 */
3838 public String getDefaultUrl() {
3839 // See http://go/clientsdns for usage approval
3840 String server = Settings.Global.getString(mContext.getContentResolver(),
3841 Settings.Global.CAPTIVE_PORTAL_SERVER);
3842 if (server == null) {
3843 server = "clients3.google.com";
3844 }
3845 return "http://" + server + "/generate_204";
3846 }
3847
3848 /**
3849 * Detect if its possible to connect to the http url. DNS based detection techniques
3850 * do not work at all hotspots. The best way to check is to perform a request to
3851 * a known address that fetches the data we expect.
3852 */
3853 private synchronized Integer isMobileOk(Params params) {
3854 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3855 Uri orgUri = Uri.parse(params.mUrl);
3856 Random rand = new Random();
3857 mParams = params;
3858
3859 try {
3860 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3861 log("isMobileOk: not mobile capable");
3862 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3863 return result;
3864 }
3865
3866 // Enable fail fast as we'll do retries here and use a
3867 // hipri connection so the default connection stays active.
3868 log("isMobileOk: start hipri url=" + params.mUrl);
3869 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3870 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3871 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3872
3873 // Continue trying to connect until time has run out
3874 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3875 while(SystemClock.elapsedRealtime() < endTime) {
3876 try {
3877 // Wait for hipri to connect.
3878 // TODO: Don't poll and handle situation where hipri fails
3879 // because default is retrying. See b/9569540
3880 NetworkInfo.State state = mCs
3881 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3882 if (state != NetworkInfo.State.CONNECTED) {
3883 log("isMobileOk: not connected ni=" +
3884 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3885 sleep(1);
3886 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3887 continue;
3888 }
3889
3890 // Get of the addresses associated with the url host. We need to use the
3891 // address otherwise HttpURLConnection object will use the name to get
3892 // the addresses and is will try every address but that will bypass the
3893 // route to host we setup and the connection could succeed as the default
3894 // interface might be connected to the internet via wifi or other interface.
3895 InetAddress[] addresses;
3896 try {
3897 addresses = InetAddress.getAllByName(orgUri.getHost());
3898 } catch (UnknownHostException e) {
3899 log("isMobileOk: UnknownHostException");
3900 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3901 return result;
3902 }
3903 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3904
3905 // Get the type of addresses supported by this link
3906 LinkProperties lp = mCs.getLinkProperties(
3907 ConnectivityManager.TYPE_MOBILE_HIPRI);
3908 boolean linkHasIpv4 = hasIPv4Address(lp);
3909 boolean linkHasIpv6 = hasIPv6Address(lp);
3910 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3911 + " linkHasIpv6=" + linkHasIpv6);
3912
3913 // Loop through at most 3 valid addresses or all of the address or until
3914 // we run out of time
3915 int loops = Math.min(3, addresses.length);
3916 for(int validAddr=0, addrTried=0;
3917 (validAddr < loops) && (addrTried < addresses.length)
3918 && (SystemClock.elapsedRealtime() < endTime);
3919 addrTried ++) {
3920
3921 // Choose the address at random but make sure its type is supported
3922 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3923 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3924 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3925 // Valid address, so use it
3926 validAddr += 1;
3927 } else {
3928 // Invalid address so try next address
3929 continue;
3930 }
3931
3932 // Make a route to host so we check the specific interface.
3933 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3934 hostAddr.getAddress())) {
3935 // Wait a short time to be sure the route is established ??
3936 log("isMobileOk:"
3937 + " wait to establish route to hostAddr=" + hostAddr);
3938 sleep(3);
3939 } else {
3940 log("isMobileOk:"
3941 + " could not establish route to hostAddr=" + hostAddr);
3942 continue;
3943 }
3944
3945 // Rewrite the url to have numeric address to use the specific route.
3946 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3947 // is used which is useless in this case.
3948 URL newUrl = new URL(orgUri.getScheme() + "://"
3949 + hostAddr.getHostAddress() + orgUri.getPath());
3950 log("isMobileOk: newUrl=" + newUrl);
3951
3952 HttpURLConnection urlConn = null;
3953 try {
3954 // Open the connection set the request header and get the response
3955 urlConn = (HttpURLConnection) newUrl.openConnection(
3956 java.net.Proxy.NO_PROXY);
3957 urlConn.setInstanceFollowRedirects(false);
3958 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3959 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3960 urlConn.setUseCaches(false);
3961 urlConn.setAllowUserInteraction(false);
3962 urlConn.setRequestProperty("Connection", "close");
3963 int responseCode = urlConn.getResponseCode();
3964 if (responseCode == 204) {
3965 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3966 } else {
3967 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3968 }
3969 log("isMobileOk: connected responseCode=" + responseCode);
3970 urlConn.disconnect();
3971 urlConn = null;
3972 return result;
3973 } catch (Exception e) {
3974 log("isMobileOk: HttpURLConnection Exception e=" + e);
3975 if (urlConn != null) {
3976 urlConn.disconnect();
3977 urlConn = null;
3978 }
3979 }
3980 }
3981 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3982 log("isMobileOk: loops|timed out");
3983 return result;
3984 } catch (Exception e) {
3985 log("isMobileOk: Exception e=" + e);
3986 continue;
3987 }
3988 }
3989 log("isMobileOk: timed out");
3990 } finally {
3991 log("isMobileOk: F stop hipri");
3992 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3993 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3994 Phone.FEATURE_ENABLE_HIPRI);
3995 log("isMobileOk: X result=" + result);
3996 }
3997 return result;
3998 }
3999
4000 @Override
4001 protected Integer doInBackground(Params... params) {
4002 return isMobileOk(params[0]);
4003 }
4004
4005 @Override
4006 protected void onPostExecute(Integer result) {
4007 log("onPostExecute: result=" + result);
4008 if ((mParams != null) && (mParams.mCb != null)) {
4009 mParams.mCb.onComplete(result);
4010 }
4011 }
4012
4013 private String inetAddressesToString(InetAddress[] addresses) {
4014 StringBuffer sb = new StringBuffer();
4015 boolean firstTime = true;
4016 for(InetAddress addr : addresses) {
4017 if (firstTime) {
4018 firstTime = false;
4019 } else {
4020 sb.append(",");
4021 }
4022 sb.append(addr);
4023 }
4024 return sb.toString();
4025 }
4026
4027 private void printNetworkInfo() {
4028 boolean hasIccCard = mTm.hasIccCard();
4029 int simState = mTm.getSimState();
4030 log("hasIccCard=" + hasIccCard
4031 + " simState=" + simState);
4032 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4033 if (ni != null) {
4034 log("ni.length=" + ni.length);
4035 for (NetworkInfo netInfo: ni) {
4036 log("netInfo=" + netInfo.toString());
4037 }
4038 } else {
4039 log("no network info ni=null");
4040 }
4041 }
4042
4043 /**
4044 * Sleep for a few seconds then return.
4045 * @param seconds
4046 */
4047 private static void sleep(int seconds) {
4048 try {
4049 Thread.sleep(seconds * 1000);
4050 } catch (InterruptedException e) {
4051 e.printStackTrace();
4052 }
4053 }
4054
4055 public boolean hasIPv4Address(LinkProperties lp) {
4056 return lp.hasIPv4Address();
4057 }
4058
4059 // Not implemented in LinkProperties, do it here.
4060 public boolean hasIPv6Address(LinkProperties lp) {
4061 for (LinkAddress address : lp.getLinkAddresses()) {
4062 if (address.getAddress() instanceof Inet6Address) {
4063 return true;
4064 }
4065 }
4066 return false;
4067 }
4068
4069 private void log(String s) {
4070 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4071 }
4072 }
4073
4074 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4075
4076 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4077 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4078
4079 Resources r = Resources.getSystem();
4080 NotificationManager notificationManager = (NotificationManager) mContext
4081 .getSystemService(Context.NOTIFICATION_SERVICE);
4082
4083 if (visible) {
4084 CharSequence title;
4085 CharSequence details;
4086 int icon;
4087 switch (networkInfo.getType()) {
4088 case ConnectivityManager.TYPE_WIFI:
4089 log("setNotificationVisible: TYPE_WIFI");
4090 title = r.getString(R.string.wifi_available_sign_in, 0);
4091 details = r.getString(R.string.network_available_sign_in_detailed,
4092 networkInfo.getExtraInfo());
4093 icon = R.drawable.stat_notify_wifi_in_range;
4094 break;
4095 case ConnectivityManager.TYPE_MOBILE:
4096 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4097 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4098 title = r.getString(R.string.network_available_sign_in, 0);
4099 // TODO: Change this to pull from NetworkInfo once a printable
4100 // name has been added to it
4101 details = mTelephonyManager.getNetworkOperatorName();
4102 icon = R.drawable.stat_notify_rssi_in_range;
4103 break;
4104 default:
4105 log("setNotificationVisible: other type=" + networkInfo.getType());
4106 title = r.getString(R.string.network_available_sign_in, 0);
4107 details = r.getString(R.string.network_available_sign_in_detailed,
4108 networkInfo.getExtraInfo());
4109 icon = R.drawable.stat_notify_rssi_in_range;
4110 break;
4111 }
4112
4113 Notification notification = new Notification();
4114 notification.when = 0;
4115 notification.icon = icon;
4116 notification.flags = Notification.FLAG_AUTO_CANCEL;
4117 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4118 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4119 Intent.FLAG_ACTIVITY_NEW_TASK);
4120 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4121 notification.tickerText = title;
4122 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4123
4124 log("setNotificaitionVisible: notify notificaiton=" + notification);
4125 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4126 } else {
4127 log("setNotificaitionVisible: cancel");
4128 notificationManager.cancel(NOTIFICATION_ID, 1);
4129 }
4130 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4131 }
4132
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004133 /** Location to an updatable file listing carrier provisioning urls.
4134 * An example:
4135 *
4136 * <?xml version="1.0" encoding="utf-8"?>
4137 * <provisioningUrls>
4138 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4139 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4140 * </provisioningUrls>
4141 */
4142 private static final String PROVISIONING_URL_PATH =
4143 "/data/misc/radio/provisioning_urls.xml";
4144 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004145
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004146 /** XML tag for root element. */
4147 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4148 /** XML tag for individual url */
4149 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4150 /** XML tag for redirected url */
4151 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4152 /** XML attribute for mcc */
4153 private static final String ATTR_MCC = "mcc";
4154 /** XML attribute for mnc */
4155 private static final String ATTR_MNC = "mnc";
4156
4157 private static final int REDIRECTED_PROVISIONING = 1;
4158 private static final int PROVISIONING = 2;
4159
4160 private String getProvisioningUrlBaseFromFile(int type) {
4161 FileReader fileReader = null;
4162 XmlPullParser parser = null;
4163 Configuration config = mContext.getResources().getConfiguration();
4164 String tagType;
4165
4166 switch (type) {
4167 case PROVISIONING:
4168 tagType = TAG_PROVISIONING_URL;
4169 break;
4170 case REDIRECTED_PROVISIONING:
4171 tagType = TAG_REDIRECTED_URL;
4172 break;
4173 default:
4174 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4175 type);
4176 }
4177
4178 try {
4179 fileReader = new FileReader(mProvisioningUrlFile);
4180 parser = Xml.newPullParser();
4181 parser.setInput(fileReader);
4182 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4183
4184 while (true) {
4185 XmlUtils.nextElement(parser);
4186
4187 String element = parser.getName();
4188 if (element == null) break;
4189
4190 if (element.equals(tagType)) {
4191 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4192 try {
4193 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4194 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4195 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4196 parser.next();
4197 if (parser.getEventType() == XmlPullParser.TEXT) {
4198 return parser.getText();
4199 }
4200 }
4201 }
4202 } catch (NumberFormatException e) {
4203 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4204 }
4205 }
4206 }
4207 return null;
4208 } catch (FileNotFoundException e) {
4209 loge("Carrier Provisioning Urls file not found");
4210 } catch (XmlPullParserException e) {
4211 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4212 } catch (IOException e) {
4213 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4214 } finally {
4215 if (fileReader != null) {
4216 try {
4217 fileReader.close();
4218 } catch (IOException e) {}
4219 }
4220 }
4221 return null;
4222 }
4223
4224 private String getMobileRedirectedProvisioningUrl() {
4225 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4226 if (TextUtils.isEmpty(url)) {
4227 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4228 }
4229 return url;
4230 }
4231
4232 public String getMobileProvisioningUrl() {
4233 enforceConnectivityInternalPermission();
4234 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4235 if (TextUtils.isEmpty(url)) {
4236 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4237 log("getProvisioningUrl: mobile_provisioining_url from resource =" + url);
4238 } else {
4239 log("getProvisioningUrl: mobile_provisioning_url from File =" + url);
4240 }
Wink Saville8cf35602013-07-10 23:00:07 -07004241 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004242 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004243 String phoneNumber = mTelephonyManager.getLine1Number();
4244 if (TextUtils.isEmpty(phoneNumber)) {
4245 phoneNumber = "0000000000";
4246 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004247 url = String.format(url,
4248 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4249 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004250 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004251 }
4252
Wink Savilleab9321d2013-06-29 21:10:57 -07004253 return url;
4254 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004255
4256 private void onUserStart(int userId) {
4257 synchronized(mVpns) {
4258 Vpn userVpn = mVpns.get(userId);
4259 if (userVpn != null) {
4260 loge("Starting user already has a VPN");
4261 return;
4262 }
4263 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4264 mVpns.put(userId, userVpn);
4265 userVpn.startMonitoring(mContext, mTrackerHandler);
4266 }
4267 }
4268
4269 private void onUserStop(int userId) {
4270 synchronized(mVpns) {
4271 Vpn userVpn = mVpns.get(userId);
4272 if (userVpn == null) {
4273 loge("Stopping user has no VPN");
4274 return;
4275 }
4276 mVpns.delete(userId);
4277 }
4278 }
4279
4280 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4281 @Override
4282 public void onReceive(Context context, Intent intent) {
4283 final String action = intent.getAction();
4284 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4285 if (userId == UserHandle.USER_NULL) return;
4286
4287 if (Intent.ACTION_USER_STARTING.equals(action)) {
4288 onUserStart(userId);
4289 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4290 onUserStop(userId);
4291 }
4292 }
4293 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294}