blob: d2bae28e3877d81f609de18efae3d5afe55a6c58 [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;
tk.mun148c7d02011-10-13 22:51:57 +090045import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070046import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070047import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080049import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080050import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070056import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080057import android.net.LinkProperties;
Wink Savilleab9321d2013-06-29 21:10:57 -070058import android.net.Uri;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Wink Savilleab9321d2013-06-29 21:10:57 -070064import android.net.NetworkInfo.State;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
70import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090073import android.net.wimax.WimaxManagerConstants;
Wink Savilleab9321d2013-06-29 21:10:57 -070074import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.RemoteException;
Wink Savilleab9321d2013-06-29 21:10:57 -070088import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070096import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080098import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070099import android.util.SparseIntArray;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700100import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Wink Savilleab9321d2013-06-29 21:10:57 -0700102import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700103import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700104import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700105import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import com.android.internal.telephony.DctConstants;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700107import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -0700108import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700109import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700110import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400111import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900112import com.android.server.connectivity.Nat464Xlat;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800113import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700114import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700115import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700116import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700117import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700118import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700119
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700120import com.android.internal.annotations.GuardedBy;
121
tk.mun148c7d02011-10-13 22:51:57 +0900122import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700125import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900127import java.lang.reflect.Constructor;
Wink Savilleab9321d2013-06-29 21:10:57 -0700128import java.net.HttpURLConnection;
Wink Savillec9822c52011-07-14 12:23:28 -0700129import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700130import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700131import java.net.InetAddress;
Wink Savilleab9321d2013-06-29 21:10:57 -0700132import java.net.URL;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700133import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700134import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700136import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700137import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700138import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139import java.util.List;
Wink Savilleab9321d2013-06-29 21:10:57 -0700140import java.util.Random;
141import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
143/**
144 * @hide
145 */
146public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700147 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Robert Greenwaltba175a52010-10-05 19:12:26 -0700149 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700150 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700152 private static final boolean LOGD_RULES = false;
153
Jeff Sharkey899223b2012-08-04 15:24:58 -0700154 // TODO: create better separation between radio types and network types
155
Robert Greenwalt42acef32009-08-12 16:08:25 -0700156 // how long to wait before switching back to a radio's default network
157 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
158 // system property that can override the above value
159 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
160 "android.telephony.apn-restore";
161
Wink Savilleab9321d2013-06-29 21:10:57 -0700162 // Default value if FAIL_FAST_TIME_MS is not set
163 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
164 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
165 private static final String FAIL_FAST_TIME_MS =
166 "persist.radio.fail_fast_time_ms";
167
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700168 // used in recursive route setting to add gateways for the host for which
169 // a host route was requested.
170 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
171
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800172 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800173 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800174
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700175 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700176
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700177 @GuardedBy("mVpns")
178 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700179 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700180
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700181 private boolean mLockdownEnabled;
182 private LockdownVpnTracker mLockdownTracker;
183
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900184 private Nat464Xlat mClat;
185
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
187 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188 /** Currently active network rules by UID. */
189 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Set of ifaces that are costly. */
191 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 /**
194 * Sometimes we want to refer to the individual network state
195 * trackers separately, and sometimes we just want to treat them
196 * abstractly.
197 */
198 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700199
Irfan Sheriffda6da092012-08-16 12:49:23 -0700200 /* Handles captive portal check on a network */
201 private CaptivePortalTracker mCaptivePortalTracker;
202
Robert Greenwalt42acef32009-08-12 16:08:25 -0700203 /**
Wink Savillee8222252011-07-13 13:44:13 -0700204 * The link properties that define the current links
205 */
206 private LinkProperties mCurrentLinkProperties[];
207
208 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700209 * A per Net list of the PID's that requested access to the net
210 * used both as a refcount and for per-PID DNS selection
211 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200212 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213
Robert Greenwalt42acef32009-08-12 16:08:25 -0700214 // priority order of the nettrackers
215 // (excluding dynamically set mNetworkPreference)
216 // TODO - move mNetworkTypePreference into this
217 private int[] mPriorityList;
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private Context mContext;
220 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700221 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700222 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000223 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700224 private int mDefaultInetConditionPublished = 0;
225 private boolean mInetConditionChangeInFlight = false;
226 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700228 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800229 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700230 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700233 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700235 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700236 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700237
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 private static final int ENABLED = 1;
239 private static final int DISABLED = 0;
240
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700241 private static final boolean ADD = true;
242 private static final boolean REMOVE = false;
243
244 private static final boolean TO_DEFAULT_TABLE = true;
245 private static final boolean TO_SECONDARY_TABLE = false;
246
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700247 /**
248 * used internally as a delayed event to make us switch back to the
249 * default network
250 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700251 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252
253 /**
254 * used internally to change our mobile data enabled flag
255 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700256 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257
258 /**
259 * used internally to change our network preference setting
260 * arg1 = networkType to prefer
261 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700262 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700263
264 /**
265 * used internally to synchronize inet condition reports
266 * arg1 = networkType
267 * arg2 = condition (0 bad, 100 good)
268 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700269 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700270
271 /**
272 * used internally to mark the end of inet condition hold periods
273 * arg1 = networkType
274 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700275 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700276
277 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278 * used internally to set enable/disable cellular data
279 * arg1 = ENBALED or DISABLED
280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700282
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 /**
284 * used internally to clear a wakelock when transitioning
285 * from one net to another
286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700288
Robert Greenwalt434203a2010-10-11 16:00:27 -0700289 /**
290 * used internally to reload global proxy settings
291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700293
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700294 /**
295 * used internally to set external dependency met/unmet
296 * arg1 = ENABLED (met) or DISABLED (unmet)
297 * arg2 = NetworkType
298 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700299 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700300
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700301 /**
302 * used internally to restore DNS properties back to the
303 * default network
304 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700305 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700306
Wink Saville2b30afd2011-08-05 11:40:22 -0700307 /**
Wink Saville628b0852011-08-04 15:01:58 -0700308 * used internally to send a sticky broadcast delayed.
309 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700310 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700311
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700312 /**
313 * Used internally to
314 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
315 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700316 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700317
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700318 private static final int EVENT_VPN_STATE_CHANGED = 14;
319
Wink Savilleab9321d2013-06-29 21:10:57 -0700320 /**
321 * Used internally to disable fail fast of mobile data
322 */
323 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
324
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700325 /** Handler used for internal events. */
326 private InternalHandler mHandler;
327 /** Handler used for incoming {@link NetworkStateTracker} events. */
328 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700329
330 // list of DeathRecipients used to make sure features are turned off when
331 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500332 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700333
Mike Lockwood0f79b542009-08-14 14:18:49 -0400334 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800335 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400336
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700337 private PowerManager.WakeLock mNetTransitionWakeLock;
338 private String mNetTransitionWakeLockCausedBy = "";
339 private int mNetTransitionWakeLockSerialNumber;
340 private int mNetTransitionWakeLockTimeout;
341
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700342 private InetAddress mDefaultDns;
343
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700344 // this collection is used to refcount the added routes - if there are none left
345 // it's time to remove the route from the route table
346 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
347
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700348 // used in DBG mode to track inet condition reports
349 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
350 private ArrayList mInetLog;
351
Robert Greenwalt434203a2010-10-11 16:00:27 -0700352 // track the current default http proxy - tell the world if we get a new one (real change)
353 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700354 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700355 private boolean mDefaultProxyDisabled = false;
356
Robert Greenwalt434203a2010-10-11 16:00:27 -0700357 // track the global proxy.
358 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700359
360 private SettingsObserver mSettingsObserver;
361
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700362 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700363 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700364
Robert Greenwalt511288a2009-12-07 11:33:18 -0800365 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366 public int mSimultaneity;
367 public int mType;
368 public RadioAttributes(String init) {
369 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700370 mType = Integer.parseInt(fragments[0]);
371 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700372 }
373 }
374 RadioAttributes[] mRadioAttributes;
375
Robert Greenwalt50393202011-06-21 17:26:14 -0700376 // the set of network types that can only be enabled by system/sig apps
377 List mProtectedNetworks;
378
John Spurlockbf991a82013-06-24 14:20:23 -0400379 private DataConnectionStats mDataConnectionStats;
Wink Savilleab9321d2013-06-29 21:10:57 -0700380 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
381
382 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400383
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700384 public ConnectivityService(Context context, INetworkManagementService netd,
385 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700386 // Currently, omitting a NetworkFactory will create one internally
387 // TODO: create here when we have cleaner WiMAX support
388 this(context, netd, statsService, policyManager, null);
389 }
390
Jeff Sharkey899223b2012-08-04 15:24:58 -0700391 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700392 INetworkStatsService statsService, INetworkPolicyManager policyManager,
393 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800394 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800395
Wink Savillebb08caf2010-09-02 19:23:52 -0700396 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
397 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700398 mHandler = new InternalHandler(handlerThread.getLooper());
399 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700400
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700401 if (netFactory == null) {
402 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
403 }
404
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800405 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800406 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
407 String id = Settings.Secure.getString(context.getContentResolver(),
408 Settings.Secure.ANDROID_ID);
409 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700410 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800411 SystemProperties.set("net.hostname", name);
412 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800413 }
414
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700415 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700416 String dns = Settings.Global.getString(context.getContentResolver(),
417 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700418 if (dns == null || dns.length() == 0) {
419 dns = context.getResources().getString(
420 com.android.internal.R.string.config_default_dns_server);
421 }
422 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800423 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
424 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800425 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700426 }
427
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700428 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700429 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700430 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700431 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700432 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700433
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700434 try {
435 mPolicyManager.registerListener(mPolicyListener);
436 } catch (RemoteException e) {
437 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700438 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700439 }
440
441 final PowerManager powerManager = (PowerManager) context.getSystemService(
442 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700443 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
444 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
445 com.android.internal.R.integer.config_networkTransitionTimeout);
446
Robert Greenwalt42acef32009-08-12 16:08:25 -0700447 mNetTrackers = new NetworkStateTracker[
448 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700449 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700450
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700451 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700452 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700453
Robert Greenwalt42acef32009-08-12 16:08:25 -0700454 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700455 String[] raStrings = context.getResources().getStringArray(
456 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700457 for (String raString : raStrings) {
458 RadioAttributes r = new RadioAttributes(raString);
459 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800460 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700461 continue;
462 }
463 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800464 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700465 r.mType);
466 continue;
467 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700468 mRadioAttributes[r.mType] = r;
469 }
470
Wink Saville51f456f2013-04-23 14:26:51 -0700471 // TODO: What is the "correct" way to do determine if this is a wifi only device?
472 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
473 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700474 String[] naStrings = context.getResources().getStringArray(
475 com.android.internal.R.array.networkAttributes);
476 for (String naString : naStrings) {
477 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700478 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700479 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800480 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700481 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700482 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700483 }
Wink Saville51f456f2013-04-23 14:26:51 -0700484 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
485 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
486 n.type);
487 continue;
488 }
Wink Saville975c8482011-04-07 14:23:45 -0700489 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800490 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700491 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700492 continue;
493 }
Wink Saville975c8482011-04-07 14:23:45 -0700494 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800495 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700496 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700497 continue;
498 }
Wink Saville975c8482011-04-07 14:23:45 -0700499 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700500 mNetworksDefined++;
501 } catch(Exception e) {
502 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700503 }
504 }
505
Robert Greenwalt50393202011-06-21 17:26:14 -0700506 mProtectedNetworks = new ArrayList<Integer>();
507 int[] protectedNetworks = context.getResources().getIntArray(
508 com.android.internal.R.array.config_protectedNetworks);
509 for (int p : protectedNetworks) {
510 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
511 mProtectedNetworks.add(p);
512 } else {
513 if (DBG) loge("Ignoring protectedNetwork " + p);
514 }
515 }
516
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700517 // high priority first
518 mPriorityList = new int[mNetworksDefined];
519 {
520 int insertionPoint = mNetworksDefined-1;
521 int currentLowest = 0;
522 int nextLowest = 0;
523 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700524 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700525 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700526 if (na.priority < currentLowest) continue;
527 if (na.priority > currentLowest) {
528 if (na.priority < nextLowest || nextLowest == 0) {
529 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700530 }
531 continue;
532 }
Wink Saville975c8482011-04-07 14:23:45 -0700533 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700534 }
535 currentLowest = nextLowest;
536 nextLowest = 0;
537 }
538 }
539
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800540 // Update mNetworkPreference according to user mannually first then overlay config.xml
541 mNetworkPreference = getPersistedNetworkPreference();
542 if (mNetworkPreference == -1) {
543 for (int n : mPriorityList) {
544 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
545 mNetworkPreference = n;
546 break;
547 }
548 }
549 if (mNetworkPreference == -1) {
550 throw new IllegalStateException(
551 "You should set at least one default Network in config.xml!");
552 }
553 }
554
Mattias Falk8b47b362011-08-23 14:15:13 +0200555 mNetRequestersPids =
556 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700557 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200558 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700559 }
560
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500561 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700562
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700563 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
564 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700565
566 // Create and start trackers for hard-coded networks
567 for (int targetNetworkType : mPriorityList) {
568 final NetworkConfig config = mNetConfigs[targetNetworkType];
569 final NetworkStateTracker tracker;
570 try {
571 tracker = netFactory.createTracker(targetNetworkType, config);
572 mNetTrackers[targetNetworkType] = tracker;
573 } catch (IllegalArgumentException e) {
574 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
575 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700576 continue;
577 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700578
579 tracker.startMonitoring(context, mTrackerHandler);
580 if (config.isDefault()) {
581 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800582 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700583 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800584
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700585 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700586 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700587 mTethering.getTetherableWifiRegexs().length != 0 ||
588 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700589 mTethering.getUpstreamIfaceTypes().length != 0);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700590 //set up the listener for user state for creating user VPNs
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800591
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700592 IntentFilter intentFilter = new IntentFilter();
593 intentFilter.addAction(Intent.ACTION_USER_STARTING);
594 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
595 mContext.registerReceiverAsUser(
596 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900597 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
598
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700599 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700600 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700601 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900602 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700603 } catch (RemoteException e) {
604 loge("Error registering observer :" + e);
605 }
606
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700607 if (DBG) {
608 mInetLog = new ArrayList();
609 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700610
611 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
612 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800613
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700614 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800615 loadGlobalProxy();
John Spurlockbf991a82013-06-24 14:20:23 -0400616
617 mDataConnectionStats = new DataConnectionStats(mContext);
618 mDataConnectionStats.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700620
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700621 /**
622 * Factory that creates {@link NetworkStateTracker} instances using given
623 * {@link NetworkConfig}.
624 */
625 public interface NetworkFactory {
626 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
627 }
628
629 private static class DefaultNetworkFactory implements NetworkFactory {
630 private final Context mContext;
631 private final Handler mTrackerHandler;
632
633 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
634 mContext = context;
635 mTrackerHandler = trackerHandler;
636 }
637
638 @Override
639 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
640 switch (config.radio) {
641 case TYPE_WIFI:
642 return new WifiStateTracker(targetNetworkType, config.name);
643 case TYPE_MOBILE:
644 return new MobileDataStateTracker(targetNetworkType, config.name);
645 case TYPE_DUMMY:
646 return new DummyDataStateTracker(targetNetworkType, config.name);
647 case TYPE_BLUETOOTH:
648 return BluetoothTetheringDataTracker.getInstance();
649 case TYPE_WIMAX:
650 return makeWimaxStateTracker(mContext, mTrackerHandler);
651 case TYPE_ETHERNET:
652 return EthernetDataTracker.getInstance();
653 default:
654 throw new IllegalArgumentException(
655 "Trying to create a NetworkStateTracker for an unknown radio type: "
656 + config.radio);
657 }
658 }
659 }
660
661 /**
662 * Loads external WiMAX library and registers as system service, returning a
663 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
664 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
665 */
666 private static NetworkStateTracker makeWimaxStateTracker(
667 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700668 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900669 DexClassLoader wimaxClassLoader;
670 Class wimaxStateTrackerClass = null;
671 Class wimaxServiceClass = null;
672 Class wimaxManagerClass;
673 String wimaxJarLocation;
674 String wimaxLibLocation;
675 String wimaxManagerClassName;
676 String wimaxServiceClassName;
677 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678
tk.mun148c7d02011-10-13 22:51:57 +0900679 NetworkStateTracker wimaxStateTracker = null;
680
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700681 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900682 com.android.internal.R.bool.config_wimaxEnabled);
683
684 if (isWimaxEnabled) {
685 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700686 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900687 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700688 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900689 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700690 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900691 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700692 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900693 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700694 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900695 com.android.internal.R.string.config_wimaxStateTrackerClassname);
696
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800697 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900698 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700699 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900700 wimaxLibLocation, ClassLoader.getSystemClassLoader());
701
702 try {
703 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
704 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
705 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
706 } catch (ClassNotFoundException ex) {
707 loge("Exception finding Wimax classes: " + ex.toString());
708 return null;
709 }
710 } catch(Resources.NotFoundException ex) {
711 loge("Wimax Resources does not exist!!! ");
712 return null;
713 }
714
715 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800716 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900717
718 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
719 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700720 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
721 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900722
723 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
724 (new Class[] {Context.class, wimaxStateTrackerClass});
725 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700726 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900727 wmxSrvConst.setAccessible(false);
728
729 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
730
731 } catch(Exception ex) {
732 loge("Exception creating Wimax classes: " + ex.toString());
733 return null;
734 }
735 } else {
736 loge("Wimax is not enabled or not added to the network attributes!!! ");
737 return null;
738 }
739
740 return wimaxStateTracker;
741 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700744 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 * @param preference the new preference
746 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700747 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700749
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700750 mHandler.sendMessage(
751 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
753
754 public int getNetworkPreference() {
755 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700756 int preference;
757 synchronized(this) {
758 preference = mNetworkPreference;
759 }
760 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700763 private void handleSetNetworkPreference(int preference) {
764 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700765 mNetConfigs[preference] != null &&
766 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700767 if (mNetworkPreference != preference) {
768 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700769 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700770 synchronized(this) {
771 mNetworkPreference = preference;
772 }
773 enforcePreference();
774 }
775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700777
Wink Saville628b0852011-08-04 15:01:58 -0700778 private int getConnectivityChangeDelay() {
779 final ContentResolver cr = mContext.getContentResolver();
780
781 /** Check system properties for the default value then use secure settings value, if any. */
782 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700783 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
784 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
785 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700786 defaultDelay);
787 }
788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 private int getPersistedNetworkPreference() {
790 final ContentResolver cr = mContext.getContentResolver();
791
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700792 final int networkPrefSetting = Settings.Global
793 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800795 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700799 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 * In this method, we only tear down a non-preferred network. Establishing
801 * a connection to the preferred network is taken care of when we handle
802 * the disconnect event from the non-preferred network
803 * (see {@link #handleDisconnect(NetworkInfo)}).
804 */
805 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700806 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 return;
808
Robert Greenwalt42acef32009-08-12 16:08:25 -0700809 if (!mNetTrackers[mNetworkPreference].isAvailable())
810 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811
Robert Greenwalt42acef32009-08-12 16:08:25 -0700812 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700813 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700814 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700815 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800816 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700817 " in enforcePreference");
818 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700819 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 }
821 }
822 }
823
824 private boolean teardown(NetworkStateTracker netTracker) {
825 if (netTracker.teardown()) {
826 netTracker.setTeardownRequested(true);
827 return true;
828 } else {
829 return false;
830 }
831 }
832
833 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700834 * Check if UID should be blocked from using the network represented by the
835 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700836 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700837 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
838 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700839
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700840 final boolean networkCostly;
841 final int uidRules;
842 synchronized (mRulesLock) {
843 networkCostly = mMeteredIfaces.contains(iface);
844 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700845 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700846
847 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
848 return true;
849 }
850
851 // no restrictive rules; network is visible
852 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700853 }
854
855 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700856 * Return a filtered {@link NetworkInfo}, potentially marked
857 * {@link DetailedState#BLOCKED} based on
858 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700859 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700860 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
861 NetworkInfo info = tracker.getNetworkInfo();
862 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700863 // network is blocked; clone and override state
864 info = new NetworkInfo(info);
865 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700866 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700867 if (mLockdownTracker != null) {
868 info = mLockdownTracker.augmentNetworkInfo(info);
869 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700870 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700871 }
872
873 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 * Return NetworkInfo for the active (i.e., connected) network interface.
875 * It is assumed that at most one network is active at a time. If more
876 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700877 * @return the info for the active network, or {@code null} if none is
878 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700880 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700882 enforceAccessPermission();
883 final int uid = Binder.getCallingUid();
884 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700887 public NetworkInfo getActiveNetworkInfoUnfiltered() {
888 enforceAccessPermission();
889 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
890 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
891 if (tracker != null) {
892 return tracker.getNetworkInfo();
893 }
894 }
895 return null;
896 }
897
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700898 @Override
899 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
900 enforceConnectivityInternalPermission();
901 return getNetworkInfo(mActiveDefaultNetwork, uid);
902 }
903
904 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 public NetworkInfo getNetworkInfo(int networkType) {
906 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700907 final int uid = Binder.getCallingUid();
908 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 }
910
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700911 private NetworkInfo getNetworkInfo(int networkType, int uid) {
912 NetworkInfo info = null;
913 if (isNetworkTypeValid(networkType)) {
914 final NetworkStateTracker tracker = mNetTrackers[networkType];
915 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700916 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700917 }
918 }
919 return info;
920 }
921
922 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 public NetworkInfo[] getAllNetworkInfo() {
924 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700925 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700926 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700927 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700928 for (NetworkStateTracker tracker : mNetTrackers) {
929 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 }
932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700934 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700937 @Override
938 public boolean isNetworkSupported(int networkType) {
939 enforceAccessPermission();
940 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
941 }
942
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700943 /**
944 * Return LinkProperties for the active (i.e., connected) default
945 * network interface. It is assumed that at most one default network
946 * is active at a time. If more than one is active, it is indeterminate
947 * which will be returned.
948 * @return the ip properties for the active network, or {@code null} if
949 * none is active
950 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700951 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700952 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700953 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700954 }
955
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700957 public LinkProperties getLinkProperties(int networkType) {
958 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700959 if (isNetworkTypeValid(networkType)) {
960 final NetworkStateTracker tracker = mNetTrackers[networkType];
961 if (tracker != null) {
962 return tracker.getLinkProperties();
963 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700964 }
965 return null;
966 }
967
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700968 @Override
969 public NetworkState[] getAllNetworkState() {
970 enforceAccessPermission();
971 final int uid = Binder.getCallingUid();
972 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700973 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700974 for (NetworkStateTracker tracker : mNetTrackers) {
975 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700976 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700977 result.add(new NetworkState(
978 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
979 }
980 }
981 }
982 return result.toArray(new NetworkState[result.size()]);
983 }
984
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700985 private NetworkState getNetworkStateUnchecked(int networkType) {
986 if (isNetworkTypeValid(networkType)) {
987 final NetworkStateTracker tracker = mNetTrackers[networkType];
988 if (tracker != null) {
989 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
990 tracker.getLinkCapabilities());
991 }
992 }
993 return null;
994 }
995
996 @Override
997 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
998 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700999
1000 final long token = Binder.clearCallingIdentity();
1001 try {
1002 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1003 if (state != null) {
1004 try {
1005 return mPolicyManager.getNetworkQuotaInfo(state);
1006 } catch (RemoteException e) {
1007 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001008 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001009 return null;
1010 } finally {
1011 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001012 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001013 }
1014
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001015 @Override
1016 public boolean isActiveNetworkMetered() {
1017 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001018 final long token = Binder.clearCallingIdentity();
1019 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001020 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001021 } finally {
1022 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001023 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001024 }
1025
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001026 private boolean isNetworkMeteredUnchecked(int networkType) {
1027 final NetworkState state = getNetworkStateUnchecked(networkType);
1028 if (state != null) {
1029 try {
1030 return mPolicyManager.isNetworkMetered(state);
1031 } catch (RemoteException e) {
1032 }
1033 }
1034 return false;
1035 }
1036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 public boolean setRadios(boolean turnOn) {
1038 boolean result = true;
1039 enforceChangePermission();
1040 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001041 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 return result;
1044 }
1045
1046 public boolean setRadio(int netType, boolean turnOn) {
1047 enforceChangePermission();
1048 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1049 return false;
1050 }
1051 NetworkStateTracker tracker = mNetTrackers[netType];
1052 return tracker != null && tracker.setRadio(turnOn);
1053 }
1054
Jeff Sharkey216c1812012-08-05 14:29:23 -07001055 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1056 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001057 public void interfaceClassDataActivityChanged(String label, boolean active) {
1058 int deviceType = Integer.parseInt(label);
1059 sendDataActivityBroadcast(deviceType, active);
1060 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001061 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001062
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001063 /**
1064 * Used to notice when the calling process dies so we can self-expire
1065 *
1066 * Also used to know if the process has cleaned up after itself when
1067 * our auto-expire timer goes off. The timer has a link to an object.
1068 *
1069 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001070 private class FeatureUser implements IBinder.DeathRecipient {
1071 int mNetworkType;
1072 String mFeature;
1073 IBinder mBinder;
1074 int mPid;
1075 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001076 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001077
1078 FeatureUser(int type, String feature, IBinder binder) {
1079 super();
1080 mNetworkType = type;
1081 mFeature = feature;
1082 mBinder = binder;
1083 mPid = getCallingPid();
1084 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001085 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001086
Robert Greenwalt42acef32009-08-12 16:08:25 -07001087 try {
1088 mBinder.linkToDeath(this, 0);
1089 } catch (RemoteException e) {
1090 binderDied();
1091 }
1092 }
1093
1094 void unlinkDeathRecipient() {
1095 mBinder.unlinkToDeath(this, 0);
1096 }
1097
1098 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001099 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001100 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1101 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001102 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001103 }
1104
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001105 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001106 if (VDBG) {
1107 log("ConnectivityService FeatureUser expire(" +
1108 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1109 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1110 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001111 stopUsingNetworkFeature(this, false);
1112 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001113
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001114 public boolean isSameUser(FeatureUser u) {
1115 if (u == null) return false;
1116
1117 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1118 }
1119
1120 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1121 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1122 TextUtils.equals(mFeature, feature)) {
1123 return true;
1124 }
1125 return false;
1126 }
1127
Robert Greenwaltb9285352009-12-21 18:24:07 -08001128 public String toString() {
1129 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1130 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1131 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001132 }
1133
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001134 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001135 public int startUsingNetworkFeature(int networkType, String feature,
1136 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001137 long startTime = 0;
1138 if (DBG) {
1139 startTime = SystemClock.elapsedRealtime();
1140 }
Wink Savillec9acde92011-09-21 11:05:43 -07001141 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001142 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1143 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001146 try {
1147 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1148 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001149 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001150 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001151
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001152 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001153
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001154 // TODO - move this into individual networktrackers
1155 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001156
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001157 if (mLockdownEnabled) {
1158 // Since carrier APNs usually aren't available from VPN
1159 // endpoint, mark them as unavailable.
1160 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1161 }
1162
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001163 if (mProtectedNetworks.contains(usedNetworkType)) {
1164 enforceConnectivityInternalPermission();
1165 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001166
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001167 // if UID is restricted, don't allow them to bring up metered APNs
1168 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1169 final int uidRules;
1170 synchronized (mRulesLock) {
1171 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1172 }
1173 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001174 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001175 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001176
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001177 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1178 if (network != null) {
1179 Integer currentPid = new Integer(getCallingPid());
1180 if (usedNetworkType != networkType) {
1181 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001182
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001183 if (ni.isAvailable() == false) {
1184 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1185 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001186 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001187 } else {
1188 // else make the attempt anyway - probably giving REQUEST_STARTED below
1189 if (DBG) {
1190 log("special network not available, but try anyway ni=" +
1191 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001192 }
1193 }
1194 }
1195
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001196 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001197
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001198 synchronized(this) {
1199 boolean addToList = true;
1200 if (restoreTimer < 0) {
1201 // In case there is no timer is specified for the feature,
1202 // make sure we don't add duplicate entry with the same request.
1203 for (FeatureUser u : mFeatureUsers) {
1204 if (u.isSameUser(f)) {
1205 // Duplicate user is found. Do not add.
1206 addToList = false;
1207 break;
1208 }
1209 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001210 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001211
1212 if (addToList) mFeatureUsers.add(f);
1213 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1214 // this gets used for per-pid dns when connected
1215 mNetRequestersPids[usedNetworkType].add(currentPid);
1216 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001217 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001218
1219 if (restoreTimer >= 0) {
1220 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1221 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1222 }
1223
1224 if ((ni.isConnectedOrConnecting() == true) &&
1225 !network.isTeardownRequested()) {
1226 if (ni.isConnected() == true) {
1227 final long token = Binder.clearCallingIdentity();
1228 try {
1229 // add the pid-specific dns
1230 handleDnsConfigurationChange(usedNetworkType);
1231 if (VDBG) log("special network already active");
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
1234 }
Wink Savillea639b312012-07-10 12:37:54 -07001235 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001236 }
1237 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001238 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001239 }
1240
1241 // check if the radio in play can make another contact
1242 // assume if cannot for now
1243
1244 if (DBG) {
1245 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1246 feature);
1247 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001248 if (network.reconnect()) {
1249 return PhoneConstants.APN_REQUEST_STARTED;
1250 } else {
1251 return PhoneConstants.APN_REQUEST_FAILED;
1252 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001253 } else {
1254 // need to remember this unsupported request so we respond appropriately on stop
1255 synchronized(this) {
1256 mFeatureUsers.add(f);
1257 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1258 // this gets used for per-pid dns when connected
1259 mNetRequestersPids[usedNetworkType].add(currentPid);
1260 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001261 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001262 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001263 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001264 }
Wink Savillea639b312012-07-10 12:37:54 -07001265 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001266 } finally {
1267 if (DBG) {
1268 final long execTime = SystemClock.elapsedRealtime() - startTime;
1269 if (execTime > 250) {
1270 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1271 } else {
1272 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1273 }
1274 }
1275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001278 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001280 enforceChangePermission();
1281
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001282 int pid = getCallingPid();
1283 int uid = getCallingUid();
1284
1285 FeatureUser u = null;
1286 boolean found = false;
1287
1288 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001289 for (FeatureUser x : mFeatureUsers) {
1290 if (x.isSameUser(pid, uid, networkType, feature)) {
1291 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001292 found = true;
1293 break;
1294 }
1295 }
1296 }
1297 if (found && u != null) {
1298 // stop regardless of how many other time this proc had called start
1299 return stopUsingNetworkFeature(u, true);
1300 } else {
1301 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001302 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001303 return 1;
1304 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001305 }
1306
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001307 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1308 int networkType = u.mNetworkType;
1309 String feature = u.mFeature;
1310 int pid = u.mPid;
1311 int uid = u.mUid;
1312
1313 NetworkStateTracker tracker = null;
1314 boolean callTeardown = false; // used to carry our decision outside of sync block
1315
Wink Savillec9acde92011-09-21 11:05:43 -07001316 if (VDBG) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001318 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001321 if (DBG) {
1322 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1323 ", net is invalid");
1324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 return -1;
1326 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001327
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001328 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1329 // sync block
1330 synchronized(this) {
1331 // check if this process still has an outstanding start request
1332 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001333 if (VDBG) {
1334 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1335 ", ignoring");
1336 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001337 return 1;
1338 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001339 u.unlinkDeathRecipient();
1340 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1341 // If we care about duplicate requests, check for that here.
1342 //
1343 // This is done to support the extension of a request - the app
1344 // can request we start the network feature again and renew the
1345 // auto-shutoff delay. Normal "stop" calls from the app though
1346 // do not pay attention to duplicate requests - in effect the
1347 // API does not refcount and a single stop will counter multiple starts.
1348 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001349 for (FeatureUser x : mFeatureUsers) {
1350 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001351 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001352 return 1;
1353 }
1354 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001355 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001356
repo syncaea743a2011-07-29 23:55:49 -07001357 // TODO - move to individual network trackers
1358 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1359
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001360 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001361 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001362 if (DBG) {
1363 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1364 " no known tracker for used net type " + usedNetworkType);
1365 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001366 return -1;
1367 }
1368 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001369 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001370 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001371
1372 final long token = Binder.clearCallingIdentity();
1373 try {
1374 reassessPidDns(pid, true);
1375 } finally {
1376 Binder.restoreCallingIdentity(token);
1377 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001378 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001379 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001380 if (VDBG) {
1381 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1382 " others still using it");
1383 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001384 return 1;
1385 }
1386 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001387 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001388 if (DBG) {
1389 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1390 " not a known feature - dropping");
1391 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001392 }
1393 }
Wink Savillec9acde92011-09-21 11:05:43 -07001394
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001395 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001396 if (DBG) {
1397 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1398 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001399 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001400 return 1;
1401 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001402 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405
1406 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001407 * @deprecated use requestRouteToHostAddress instead
1408 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 * Ensure that a network route exists to deliver traffic to the specified
1410 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001411 * @param networkType the type of the network over which traffic to the
1412 * specified host is to be routed
1413 * @param hostAddress the IP address of the host to which the route is
1414 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 * @return {@code true} on success, {@code false} on failure
1416 */
1417 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001418 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1419
1420 if (inetAddress == null) {
1421 return false;
1422 }
1423
1424 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1425 }
1426
1427 /**
1428 * Ensure that a network route exists to deliver traffic to the specified
1429 * host via the specified network interface.
1430 * @param networkType the type of the network over which traffic to the
1431 * specified host is to be routed
1432 * @param hostAddress the IP address of the host to which the route is
1433 * desired
1434 * @return {@code true} on success, {@code false} on failure
1435 */
1436 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001438 if (mProtectedNetworks.contains(networkType)) {
1439 enforceConnectivityInternalPermission();
1440 }
1441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001443 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 return false;
1445 }
1446 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001447 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001448
Irfan Sheriffda6da092012-08-16 12:49:23 -07001449 if (tracker == null || (netState != DetailedState.CONNECTED &&
1450 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001451 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001452 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001453 log("requestRouteToHostAddress on down network "
1454 + "(" + networkType + ") - dropped"
1455 + " tracker=" + tracker
1456 + " netState=" + netState
1457 + " isTeardownRequested="
1458 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001459 }
1460 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001462 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001463 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001464 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001465 LinkProperties lp = tracker.getLinkProperties();
Wink Savilleab9321d2013-06-29 21:10:57 -07001466 boolean ok = addRouteToAddress(lp, addr);
1467 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1468 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001469 } catch (UnknownHostException e) {
1470 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1471 } finally {
1472 Binder.restoreCallingIdentity(token);
1473 }
Wink Savilleab9321d2013-06-29 21:10:57 -07001474 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001475 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001476 }
1477
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001478 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001479 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001480 }
1481
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001482 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001483 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001484 }
1485
Robert Greenwaltad55d352011-07-22 11:55:33 -07001486 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001487 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001488 }
1489
1490 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001491 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001492 }
1493
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001494 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1495 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001496 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001497 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001498 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001499 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001500 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001501 if (bestRoute.getGateway().equals(addr)) {
1502 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001503 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001504 } else {
1505 // if we will connect to this through another route, add a direct route
1506 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001507 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001508 }
1509 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001510 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001511 }
1512
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001513 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1514 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001515 if ((lp == null) || (r == null)) {
1516 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001517 return false;
1518 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001519
1520 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001521 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001522 return false;
1523 }
1524
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001525 String ifaceName = r.getInterface();
1526 if(ifaceName == null) {
1527 loge("Error modifying route - no interface name");
1528 return false;
1529 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001530 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001531 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001532 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001533 if (bestRoute.getGateway().equals(r.getGateway())) {
1534 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001535 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001536 } else {
1537 // if we will connect to our gateway through another route, add a direct
1538 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001539 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1540 bestRoute.getGateway(),
1541 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001542 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001543 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001544 }
1545 }
1546 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001547 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001548 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001549 if (toDefaultTable) {
1550 mAddedRoutes.add(r); // only track default table - only one apps can effect
1551 mNetd.addRoute(ifaceName, r);
1552 } else {
1553 mNetd.addSecondaryRoute(ifaceName, r);
1554 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001555 } catch (Exception e) {
1556 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001557 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001558 return false;
1559 }
1560 } else {
1561 // if we remove this one and there are no more like it, then refcount==0 and
1562 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001563 if (toDefaultTable) {
1564 mAddedRoutes.remove(r);
1565 if (mAddedRoutes.contains(r) == false) {
1566 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1567 try {
1568 mNetd.removeRoute(ifaceName, r);
1569 } catch (Exception e) {
1570 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001571 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001572 return false;
1573 }
1574 } else {
1575 if (VDBG) log("not removing " + r + " as it's still in use");
1576 }
1577 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001578 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001579 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001580 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001581 } 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 Greenwalt0a46db52011-07-14 14:28:05 -07001584 return false;
1585 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001586 }
1587 }
1588 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
1591 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001592 * @see ConnectivityManager#getMobileDataEnabled()
1593 */
1594 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001595 // TODO: This detail should probably be in DataConnectionTracker's
1596 // which is where we store the value and maybe make this
1597 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001598 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001599 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1600 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001601 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001602 return retVal;
1603 }
1604
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001605 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001606 enforceConnectivityInternalPermission();
1607
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1609 (met ? ENABLED : DISABLED), networkType));
1610 }
1611
1612 private void handleSetDependencyMet(int networkType, boolean met) {
1613 if (mNetTrackers[networkType] != null) {
1614 if (DBG) {
1615 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1616 }
1617 mNetTrackers[networkType].setDependencyMet(met);
1618 }
1619 }
1620
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001621 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1622 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001623 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001624 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001625 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001626 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001627 }
1628
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001629 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001630 // skip update when we've already applied rules
1631 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1632 if (oldRules == uidRules) return;
1633
1634 mUidRules.put(uid, uidRules);
1635 }
1636
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001637 // TODO: notify UID when it has requested targeted updates
1638 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001639
1640 @Override
1641 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001642 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001643 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001644 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001645 }
1646
1647 synchronized (mRulesLock) {
1648 mMeteredIfaces.clear();
1649 for (String iface : meteredIfaces) {
1650 mMeteredIfaces.add(iface);
1651 }
1652 }
1653 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001654
1655 @Override
1656 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1657 // caller is NPMS, since we only register with them
1658 if (LOGD_RULES) {
1659 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1660 }
1661
1662 // kick off connectivity change broadcast for active network, since
1663 // global background policy change is radical.
1664 final int networkType = mActiveDefaultNetwork;
1665 if (isNetworkTypeValid(networkType)) {
1666 final NetworkStateTracker tracker = mNetTrackers[networkType];
1667 if (tracker != null) {
1668 final NetworkInfo info = tracker.getNetworkInfo();
1669 if (info != null && info.isConnected()) {
1670 sendConnectedBroadcast(info);
1671 }
1672 }
1673 }
1674 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001675 };
1676
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001677 /**
1678 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1679 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001680 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001681 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001682 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001683
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001685 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001686 }
1687
1688 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001689 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001690 if (VDBG) {
1691 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001692 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001693 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1694 }
tk.munb97d34c2012-01-06 10:43:52 +09001695 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1696 if (VDBG) {
1697 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1698 }
1699 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1700 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001701 }
1702
1703 @Override
1704 public void setPolicyDataEnable(int networkType, boolean enabled) {
1705 // only someone like NPMS should only be calling us
1706 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1707
1708 mHandler.sendMessage(mHandler.obtainMessage(
1709 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1710 }
1711
1712 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1713 if (isNetworkTypeValid(networkType)) {
1714 final NetworkStateTracker tracker = mNetTrackers[networkType];
1715 if (tracker != null) {
1716 tracker.setPolicyDataEnable(enabled);
1717 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001718 }
1719 }
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001722 mContext.enforceCallingOrSelfPermission(
1723 android.Manifest.permission.ACCESS_NETWORK_STATE,
1724 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726
1727 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001728 mContext.enforceCallingOrSelfPermission(
1729 android.Manifest.permission.CHANGE_NETWORK_STATE,
1730 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001733 // TODO Make this a special check when it goes public
1734 private void enforceTetherChangePermission() {
1735 mContext.enforceCallingOrSelfPermission(
1736 android.Manifest.permission.CHANGE_NETWORK_STATE,
1737 "ConnectivityService");
1738 }
1739
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001740 private void enforceTetherAccessPermission() {
1741 mContext.enforceCallingOrSelfPermission(
1742 android.Manifest.permission.ACCESS_NETWORK_STATE,
1743 "ConnectivityService");
1744 }
1745
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001746 private void enforceConnectivityInternalPermission() {
1747 mContext.enforceCallingOrSelfPermission(
1748 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1749 "ConnectivityService");
1750 }
1751
Chad Brubakerd475c702013-07-11 13:29:30 -07001752 private void enforceMarkNetworkSocketPermission() {
1753 //Media server special case
1754 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1755 return;
1756 }
1757 mContext.enforceCallingOrSelfPermission(
1758 android.Manifest.permission.MARK_NETWORK_SOCKET,
1759 "ConnectivityService");
1760 }
1761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001763 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1764 * network, we ignore it. If it is for the active network, we send out a
1765 * broadcast. But first, we check whether it might be possible to connect
1766 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 * @param info the {@code NetworkInfo} for the network
1768 */
1769 private void handleDisconnect(NetworkInfo info) {
1770
Robert Greenwalt42acef32009-08-12 16:08:25 -07001771 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772
Robert Greenwalt42acef32009-08-12 16:08:25 -07001773 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001774
1775 // Remove idletimer previously setup in {@code handleConnect}
1776 removeDataActivityTracking(prevNetType);
1777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 /*
1779 * If the disconnected network is not the active one, then don't report
1780 * this as a loss of connectivity. What probably happened is that we're
1781 * getting the disconnect for a network that we explicitly disabled
1782 * in accordance with network preference policies.
1783 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001784 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001785 List<Integer> pids = mNetRequestersPids[prevNetType];
1786 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001787 // will remove them because the net's no longer connected
1788 // need to do this now as only now do we know the pids and
1789 // can properly null things that are no longer referenced.
1790 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001795 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001796 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 if (info.isFailover()) {
1798 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1799 info.setFailover(false);
1800 }
1801 if (info.getReason() != null) {
1802 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1803 }
1804 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001805 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1806 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001808
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001809 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001810 tryFailover(prevNetType);
1811 if (mActiveDefaultNetwork != -1) {
1812 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001813 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1814 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001815 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001816 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1817 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001818 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001819 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001820
1821 // Reset interface if no other connections are using the same interface
1822 boolean doReset = true;
1823 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1824 if (linkProperties != null) {
1825 String oldIface = linkProperties.getInterfaceName();
1826 if (TextUtils.isEmpty(oldIface) == false) {
1827 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1828 if (networkStateTracker == null) continue;
1829 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1830 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1831 LinkProperties l = networkStateTracker.getLinkProperties();
1832 if (l == null) continue;
1833 if (oldIface.equals(l.getInterfaceName())) {
1834 doReset = false;
1835 break;
1836 }
1837 }
1838 }
1839 }
1840 }
1841
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001842 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001843 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001844
Jeff Sharkey961e3042011-08-29 16:02:57 -07001845 final Intent immediateIntent = new Intent(intent);
1846 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1847 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001848 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001849 /*
1850 * If the failover network is already connected, then immediately send
1851 * out a followup broadcast indicating successful failover
1852 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001853 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001854 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1855 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001856 }
1857 }
1858
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001859 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001860 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001861 * If this is a default network, check if other defaults are available.
1862 * Try to reconnect on all available and let them hash it out when
1863 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001864 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001865 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001866 if (mActiveDefaultNetwork == prevNetType) {
1867 mActiveDefaultNetwork = -1;
1868 }
1869
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001870 // don't signal a reconnect for anything lower or equal priority than our
1871 // current connected default
1872 // TODO - don't filter by priority now - nice optimization but risky
1873// int currentPriority = -1;
1874// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001875// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001876// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001877 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001878 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001879 if (mNetConfigs[checkType] == null) continue;
1880 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001881 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001882
1883// Enabling the isAvailable() optimization caused mobile to not get
1884// selected if it was in the middle of error handling. Specifically
1885// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1886// would not be available and we wouldn't get connected to anything.
1887// So removing the isAvailable() optimization below for now. TODO: This
1888// optimization should work and we need to investigate why it doesn't work.
1889// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1890// complete before it is really complete.
1891// if (!mNetTrackers[checkType].isAvailable()) continue;
1892
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001893// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001894
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001895 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1896 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1897 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1898 checkInfo.setFailover(true);
1899 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001900 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001901 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
1905
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001906 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001907 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001908 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1909 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001910 }
1911
Wink Saville628b0852011-08-04 15:01:58 -07001912 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001913 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1914 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001915 }
1916
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001917 private void sendInetConditionBroadcast(NetworkInfo info) {
1918 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1919 }
1920
Wink Saville628b0852011-08-04 15:01:58 -07001921 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001922 if (mLockdownTracker != null) {
1923 info = mLockdownTracker.augmentNetworkInfo(info);
1924 }
1925
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001926 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001927 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001928 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 if (info.isFailover()) {
1930 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1931 info.setFailover(false);
1932 }
1933 if (info.getReason() != null) {
1934 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1935 }
1936 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001937 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1938 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001940 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001941 return intent;
1942 }
1943
1944 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1945 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1946 }
1947
1948 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1949 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
1951
Haoyu Baidb3c8672012-06-20 14:29:57 -07001952 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1953 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1954 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1955 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001956 final long ident = Binder.clearCallingIdentity();
1957 try {
1958 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1959 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1960 } finally {
1961 Binder.restoreCallingIdentity(ident);
1962 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001963 }
1964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 /**
1966 * Called when an attempt to fail over to another network has failed.
1967 * @param info the {@link NetworkInfo} for the failed network
1968 */
1969 private void handleConnectionFailure(NetworkInfo info) {
1970 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971
Robert Greenwalt42acef32009-08-12 16:08:25 -07001972 String reason = info.getReason();
1973 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001974
Robert Greenwalt572172b2010-10-08 16:35:52 -07001975 String reasonText;
1976 if (reason == null) {
1977 reasonText = ".";
1978 } else {
1979 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001981 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001982
1983 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001984 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001985 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001986 if (getActiveNetworkInfo() == null) {
1987 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1988 }
1989 if (reason != null) {
1990 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1991 }
1992 if (extraInfo != null) {
1993 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1994 }
1995 if (info.isFailover()) {
1996 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1997 info.setFailover(false);
1998 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001999
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002000 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002001 tryFailover(info.getType());
2002 if (mActiveDefaultNetwork != -1) {
2003 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002004 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2005 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07002006 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002007 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2008 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002009 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002010
Robert Greenwalt029be812010-09-20 18:01:43 -07002011 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07002012
2013 final Intent immediateIntent = new Intent(intent);
2014 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2015 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002016 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002017 /*
2018 * If the failover network is already connected, then immediately send
2019 * out a followup broadcast indicating successful failover
2020 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002021 if (mActiveDefaultNetwork != -1) {
2022 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002023 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002024 }
2025
2026 private void sendStickyBroadcast(Intent intent) {
2027 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002028 if (!mSystemReady) {
2029 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002030 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002031 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07002032 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002033 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002034 }
2035
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002036 final long ident = Binder.clearCallingIdentity();
2037 try {
2038 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2039 } finally {
2040 Binder.restoreCallingIdentity(ident);
2041 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002042 }
2043 }
2044
Wink Saville628b0852011-08-04 15:01:58 -07002045 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2046 if (delayMs <= 0) {
2047 sendStickyBroadcast(intent);
2048 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002049 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002050 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2051 + intent.getAction());
2052 }
Wink Saville628b0852011-08-04 15:01:58 -07002053 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2054 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2055 }
2056 }
2057
Mike Lockwood0f79b542009-08-14 14:18:49 -04002058 void systemReady() {
2059 synchronized(this) {
2060 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002061 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002062 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002063 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002064 }
2065 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002066 // load the global proxy at startup
2067 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002068
2069 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2070 // for user to unlock device.
2071 if (!updateLockdownVpn()) {
2072 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2073 mContext.registerReceiver(mUserPresentReceiver, filter);
2074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002077 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2078 @Override
2079 public void onReceive(Context context, Intent intent) {
2080 // Try creating lockdown tracker, since user present usually means
2081 // unlocked keystore.
2082 if (updateLockdownVpn()) {
2083 mContext.unregisterReceiver(this);
2084 }
2085 }
2086 };
2087
Irfan Sheriffda6da092012-08-16 12:49:23 -07002088 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2089 if ((type != mNetworkPreference &&
2090 mNetConfigs[mActiveDefaultNetwork].priority >
2091 mNetConfigs[type].priority) ||
2092 mNetworkPreference == mActiveDefaultNetwork) return false;
2093 return true;
2094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095
Irfan Sheriffda6da092012-08-16 12:49:23 -07002096 private void handleConnect(NetworkInfo info) {
2097 final int newNetType = info.getType();
2098
2099 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 // snapshot isFailover, because sendConnectedBroadcast() resets it
2102 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002103 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002104 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105
Robert Greenwalt42acef32009-08-12 16:08:25 -07002106 // if this is a default net and other default is running
2107 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002108 if (mNetConfigs[newNetType].isDefault()) {
2109 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2110 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002111 // tear down the other
2112 NetworkStateTracker otherNet =
2113 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002114 if (DBG) {
2115 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002116 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002117 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002118 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002119 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002120 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002121 return;
2122 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002123 } else {
2124 // don't accept this one
2125 if (VDBG) {
2126 log("Not broadcasting CONNECT_ACTION " +
2127 "to torn down network " + info.getTypeName());
2128 }
2129 teardown(thisNet);
2130 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002131 }
2132 }
2133 synchronized (ConnectivityService.this) {
2134 // have a new default network, release the transition wakelock in a second
2135 // if it's held. The second pause is to allow apps to reconnect over the
2136 // new network
2137 if (mNetTransitionWakeLock.isHeld()) {
2138 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002139 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002140 mNetTransitionWakeLockSerialNumber, 0),
2141 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002142 }
2143 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002144 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002145 // this will cause us to come up initially as unconnected and switching
2146 // to connected after our normal pause unless somebody reports us as reall
2147 // disconnected
2148 mDefaultInetConditionPublished = 0;
2149 mDefaultConnectionSequence++;
2150 mInetConditionChangeInFlight = false;
2151 // Don't do this - if we never sign in stay, grey
2152 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002155 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002156 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002157 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002158
2159 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002160 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002161 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002162 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002163 } catch (RemoteException e) {
2164 // ignored; service lives in system_server
2165 }
2166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
2168
Irfan Sheriffda6da092012-08-16 12:49:23 -07002169 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2170 if (DBG) log("Captive portal check " + info);
2171 int type = info.getType();
2172 final NetworkStateTracker thisNet = mNetTrackers[type];
2173 if (mNetConfigs[type].isDefault()) {
2174 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2175 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2176 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002177 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002178 return;
2179 } else {
2180 if (DBG) log("Tear down low priority net " + info.getTypeName());
2181 teardown(thisNet);
2182 return;
2183 }
2184 }
2185 }
2186
2187 thisNet.captivePortalCheckComplete();
2188 }
2189
2190 /** @hide */
2191 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002192 enforceConnectivityInternalPermission();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002193 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002194 }
2195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002197 * Setup data activity tracking for the given network interface.
2198 *
2199 * Every {@code setupDataActivityTracking} should be paired with a
2200 * {@link removeDataActivityTracking} for cleanup.
2201 */
2202 private void setupDataActivityTracking(int type) {
2203 final NetworkStateTracker thisNet = mNetTrackers[type];
2204 final String iface = thisNet.getLinkProperties().getInterfaceName();
2205
2206 final int timeout;
2207
2208 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002209 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2210 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002211 0);
2212 // Canonicalize mobile network type
2213 type = ConnectivityManager.TYPE_MOBILE;
2214 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002215 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2216 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002217 0);
2218 } else {
2219 // do not track any other networks
2220 timeout = 0;
2221 }
2222
2223 if (timeout > 0 && iface != null) {
2224 try {
2225 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2226 } catch (RemoteException e) {
2227 }
2228 }
2229 }
2230
2231 /**
2232 * Remove data activity tracking when network disconnects.
2233 */
2234 private void removeDataActivityTracking(int type) {
2235 final NetworkStateTracker net = mNetTrackers[type];
2236 final String iface = net.getLinkProperties().getInterfaceName();
2237
2238 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2239 ConnectivityManager.TYPE_WIFI == type)) {
2240 try {
2241 // the call fails silently if no idletimer setup for this interface
2242 mNetd.removeIdleTimer(iface);
2243 } catch (RemoteException e) {
2244 }
2245 }
2246 }
2247
2248 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002249 * After a change in the connectivity state of a network. We're mainly
2250 * concerned with making sure that the list of DNS servers is set up
2251 * according to which networks are connected, and ensuring that the
2252 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002254 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002255 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002258 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002259 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002261 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002262
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002263 LinkProperties curLp = mCurrentLinkProperties[netType];
2264 LinkProperties newLp = null;
2265
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002266 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002267 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002268 if (VDBG) {
2269 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2270 " doReset=" + doReset + " resetMask=" + resetMask +
2271 "\n curLp=" + curLp +
2272 "\n newLp=" + newLp);
2273 }
2274
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002275 if (curLp != null) {
2276 if (curLp.isIdenticalInterfaceName(newLp)) {
2277 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2278 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2279 for (LinkAddress linkAddr : car.removed) {
2280 if (linkAddr.getAddress() instanceof Inet4Address) {
2281 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2282 }
2283 if (linkAddr.getAddress() instanceof Inet6Address) {
2284 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2285 }
Wink Savillee8222252011-07-13 13:44:13 -07002286 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002287 if (DBG) {
2288 log("handleConnectivityChange: addresses changed" +
2289 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2290 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002291 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002292 } else {
2293 if (DBG) {
2294 log("handleConnectivityChange: address are the same reset per doReset" +
2295 " linkProperty[" + netType + "]:" +
2296 " resetMask=" + resetMask);
2297 }
Wink Savillee8222252011-07-13 13:44:13 -07002298 }
2299 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002300 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002301 if (DBG) {
2302 log("handleConnectivityChange: interface not not equivalent reset both" +
2303 " linkProperty[" + netType + "]:" +
2304 " resetMask=" + resetMask);
2305 }
Wink Savillee8222252011-07-13 13:44:13 -07002306 }
Wink Savillee8222252011-07-13 13:44:13 -07002307 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002308 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002309 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002310 }
2311 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002312 if (VDBG) {
2313 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2314 " doReset=" + doReset + " resetMask=" + resetMask +
2315 "\n curLp=" + curLp +
2316 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002319 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002320 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002321
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002322 if (resetMask != 0 || resetDns) {
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002323 if (curLp != null) {
2324 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002325 if (TextUtils.isEmpty(iface) == false) {
2326 if (resetMask != 0) {
2327 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2328 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002329
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002330 // Tell VPN the interface is down. It is a temporary
2331 // but effective fix to make VPN aware of the change.
2332 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002333 synchronized(mVpns) {
2334 for (int i = 0; i < mVpns.size(); i++) {
2335 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2336 }
2337 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002338 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002339 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002340 if (resetDns) {
2341 flushVmDnsCache();
2342 if (VDBG) log("resetting DNS cache for " + iface);
2343 try {
2344 mNetd.flushInterfaceDnsCache(iface);
2345 } catch (Exception e) {
2346 // never crash - catch them all
2347 if (DBG) loge("Exception resetting dns cache: " + e);
2348 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002349 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002350 } else {
2351 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002352 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002353 }
2354 }
2355 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002356
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002357 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002358 NetworkStateTracker tracker = mNetTrackers[netType];
2359 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002360 // If the connection was previously using clat, but is not using it now, stop the clat
2361 // daemon. Normally, this happens automatically when the connection disconnects, but if
2362 // the disconnect is not reported, or if the connection's LinkProperties changed for
2363 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2364 // still be running. If it's not running, then stopping it is a no-op.
2365 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2366 mClat.stopClat();
2367 }
2368 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002369 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2370 mClat.startClat(tracker);
2371 } else {
2372 mClat.stopClat();
2373 }
2374 }
2375
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002376 // TODO: Temporary notifying upstread change to Tethering.
2377 // @see bug/4455071
2378 /** Notify TetheringService if interface name has been changed. */
2379 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002380 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002381 if (isTetheringSupported()) {
2382 mTethering.handleTetherIfaceChange();
2383 }
2384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 }
2386
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002387 /**
2388 * Add and remove routes using the old properties (null if not previously connected),
2389 * new properties (null if becoming disconnected). May even be double null, which
2390 * is a noop.
2391 * Uses isLinkDefault to determine if default routes should be set or conversely if
2392 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002393 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002394 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002395 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2396 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002397 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002398 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2399 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002400 if (curLp != null) {
2401 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002402 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002403 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002404 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002405 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002406 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002407 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002408
Robert Greenwaltf125a092011-08-15 12:31:55 -07002409 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2410
Robert Greenwaltad55d352011-07-22 11:55:33 -07002411 for (RouteInfo r : routeDiff.removed) {
2412 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002413 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2414 }
2415 if (isLinkDefault == false) {
2416 // remove from a secondary route table
2417 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002418 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002419 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002420
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002421 if (!isLinkDefault) {
2422 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002423 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002424 // routes changed - remove all old dns entries and add new
2425 if (curLp != null) {
2426 for (InetAddress oldDns : curLp.getDnses()) {
2427 removeRouteToAddress(curLp, oldDns);
2428 }
2429 }
2430 if (newLp != null) {
2431 for (InetAddress newDns : newLp.getDnses()) {
2432 addRouteToAddress(newLp, newDns);
2433 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002434 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002435 } else {
2436 // no change in routes, check for change in dns themselves
2437 for (InetAddress oldDns : dnsDiff.removed) {
2438 removeRouteToAddress(curLp, oldDns);
2439 }
2440 for (InetAddress newDns : dnsDiff.added) {
2441 addRouteToAddress(newLp, newDns);
2442 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002443 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002444 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002445
2446 for (RouteInfo r : routeDiff.added) {
2447 if (isLinkDefault || ! r.isDefaultRoute()) {
2448 addRoute(newLp, r, TO_DEFAULT_TABLE);
2449 } else {
2450 // add to a secondary route table
2451 addRoute(newLp, r, TO_SECONDARY_TABLE);
2452
2453 // many radios add a default route even when we don't want one.
2454 // remove the default route unless somebody else has asked for it
2455 String ifaceName = newLp.getInterfaceName();
2456 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2457 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2458 try {
2459 mNetd.removeRoute(ifaceName, r);
2460 } catch (Exception e) {
2461 // never crash - catch them all
2462 if (DBG) loge("Exception trying to remove a route: " + e);
2463 }
2464 }
2465 }
2466 }
2467
Robert Greenwaltf125a092011-08-15 12:31:55 -07002468 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002469 }
2470
2471
Irfan Sheriffd649c122010-06-09 15:39:36 -07002472 /**
2473 * Reads the network specific TCP buffer sizes from SystemProperties
2474 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2475 * wide use
2476 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002477 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002478 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002479 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002480
Jeff Sharkey899223b2012-08-04 15:24:58 -07002481 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002482 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002483
2484 // Setting to default values so we won't be stuck to previous values
2485 key = "net.tcp.buffersize.default";
2486 bufferSizes = SystemProperties.get(key);
2487 }
2488
2489 // Set values in kernel
2490 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002491 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002492 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002493 + "] which comes from [" + key + "]");
2494 }
2495 setBufferSize(bufferSizes);
2496 }
2497 }
2498
2499 /**
2500 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2501 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2502 *
2503 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2504 * writeMin, writeInitial, writeMax"
2505 */
2506 private void setBufferSize(String bufferSizes) {
2507 try {
2508 String[] values = bufferSizes.split(",");
2509
2510 if (values.length == 6) {
2511 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002512 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2513 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2514 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2515 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2516 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2517 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002518 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002519 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002520 }
2521 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002522 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002523 }
2524 }
2525
Robert Greenwalt42acef32009-08-12 16:08:25 -07002526 /**
2527 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2528 * on the highest priority active net which this process requested.
2529 * If there aren't any, clear it out
2530 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002531 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002532 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002533 if (VDBG) log("reassessPidDns for pid " + pid);
2534 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002535 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002536 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002537 continue;
2538 }
2539 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002540 if (nt.getNetworkInfo().isConnected() &&
2541 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002542 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002543 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002544 if (mNetRequestersPids[i].contains(myPid)) {
2545 try {
2546 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2547 } catch (Exception e) {
2548 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002549 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002550 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002551 }
2552 }
2553 }
2554 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002555 try {
2556 mNetd.clearDnsInterfaceForPid(pid);
2557 } catch (Exception e) {
2558 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002559 }
2560 }
2561
Mattias Falk8b47b362011-08-23 14:15:13 +02002562 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002563 /*
2564 * Tell the VMs to toss their DNS caches
2565 */
2566 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2567 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002568 /*
2569 * Connectivity events can happen before boot has completed ...
2570 */
2571 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002572 final long ident = Binder.clearCallingIdentity();
2573 try {
2574 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2575 } finally {
2576 Binder.restoreCallingIdentity(ident);
2577 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002578 }
2579
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002580 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002581 private void updateDnsLocked(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002582 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002583 int last = 0;
2584 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002585 dnses = new ArrayList();
2586 dnses.add(mDefaultDns);
2587 if (DBG) {
2588 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002589 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002590 }
2591
Mattias Falk8b47b362011-08-23 14:15:13 +02002592 try {
2593 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002594 for (InetAddress dns : dnses) {
2595 ++last;
2596 String key = "net.dns" + last;
2597 String value = dns.getHostAddress();
2598 SystemProperties.set(key, value);
2599 }
2600 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2601 String key = "net.dns" + i;
2602 SystemProperties.set(key, "");
2603 }
2604 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002605 } catch (Exception e) {
2606 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002607 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002608 }
2609
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002610 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002611 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002612 NetworkStateTracker nt = mNetTrackers[netType];
2613 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002614 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002615 if (p == null) return;
2616 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002617 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002618 String network = nt.getNetworkInfo().getTypeName();
2619 synchronized (mDnsLock) {
2620 if (!mDnsOverridden) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002621 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002622 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002623 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002624 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002625 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002626 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002627 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002628 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002629 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002630 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002631 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002632 List<Integer> pids = mNetRequestersPids[netType];
2633 for (Integer pid : pids) {
2634 try {
2635 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2636 } catch (Exception e) {
2637 Slog.e(TAG, "exception setting interface for pid: " + e);
2638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
2640 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002641 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002643 }
2644
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002645 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002646 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2647 NETWORK_RESTORE_DELAY_PROP_NAME);
2648 if(restoreDefaultNetworkDelayStr != null &&
2649 restoreDefaultNetworkDelayStr.length() != 0) {
2650 try {
2651 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2652 } catch (NumberFormatException e) {
2653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002655 // if the system property isn't set, use the value for the apn type
2656 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2657
2658 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2659 (mNetConfigs[networkType] != null)) {
2660 ret = mNetConfigs[networkType].restoreTime;
2661 }
2662 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664
2665 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002666 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2667 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002668 if (mContext.checkCallingOrSelfPermission(
2669 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002671 pw.println("Permission Denial: can't dump ConnectivityService " +
2672 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2673 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 return;
2675 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002676
2677 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002679 for (int i = 0; i < mNetTrackers.length; i++) {
2680 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002681 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002682 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2683 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002684 if (nst.getNetworkInfo().isConnected()) {
2685 pw.println("Active network: " + nst.getNetworkInfo().
2686 getTypeName());
2687 }
2688 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002689 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002690 pw.println(nst);
2691 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002692 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002695
2696 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002697 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002698 for (int net : mPriorityList) {
2699 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002700 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002701 pidString = pidString + pid.toString() + ", ";
2702 }
2703 pw.println(pidString);
2704 }
2705 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002706 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002707
2708 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002709 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002710 for (Object requester : mFeatureUsers) {
2711 pw.println(requester.toString());
2712 }
2713 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002714 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002715
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002716 synchronized (this) {
2717 pw.println("NetworkTranstionWakeLock is currently " +
2718 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2719 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2720 }
2721 pw.println();
2722
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002723 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002724
2725 if (mInetLog != null) {
2726 pw.println();
2727 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002728 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002729 for(int i = 0; i < mInetLog.size(); i++) {
2730 pw.println(mInetLog.get(i));
2731 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002732 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735
Robert Greenwalt42acef32009-08-12 16:08:25 -07002736 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002737 private class NetworkStateTrackerHandler extends Handler {
2738 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002739 super(looper);
2740 }
2741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 @Override
2743 public void handleMessage(Message msg) {
2744 NetworkInfo info;
2745 switch (msg.what) {
2746 case NetworkStateTracker.EVENT_STATE_CHANGED:
2747 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002748 int type = info.getType();
2749 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002750
Wink Savillec9acde92011-09-21 11:05:43 -07002751 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2752 (state == NetworkInfo.State.DISCONNECTED)) {
2753 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002754 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002755 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757
Jeff Sharkey2528b502012-11-09 15:57:02 -08002758 EventLogTags.writeConnectivityStateChanged(
2759 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002760
2761 if (info.getDetailedState() ==
2762 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002764 } else if (info.getDetailedState() ==
2765 DetailedState.CAPTIVE_PORTAL_CHECK) {
2766 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002767 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002769 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002771 // the logic here is, handle SUSPENDED the same as
2772 // DISCONNECTED. The only difference being we are
2773 // broadcasting an intent with NetworkInfo that's
2774 // suspended. This allows the applications an
2775 // opportunity to handle DISCONNECTED and SUSPENDED
2776 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002778 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 handleConnect(info);
2780 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002781 if (mLockdownTracker != null) {
2782 mLockdownTracker.onNetworkInfoChanged(info);
2783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002786 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002787 // TODO: Temporary allowing network configuration
2788 // change not resetting sockets.
2789 // @see bug/4455071
2790 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002792 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2793 info = (NetworkInfo) msg.obj;
2794 type = info.getType();
2795 updateNetworkSettings(mNetTrackers[type]);
2796 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002797 }
2798 }
2799 }
2800
2801 private class InternalHandler extends Handler {
2802 public InternalHandler(Looper looper) {
2803 super(looper);
2804 }
2805
2806 @Override
2807 public void handleMessage(Message msg) {
2808 NetworkInfo info;
2809 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002810 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002811 String causedBy = null;
2812 synchronized (ConnectivityService.this) {
2813 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2814 mNetTransitionWakeLock.isHeld()) {
2815 mNetTransitionWakeLock.release();
2816 causedBy = mNetTransitionWakeLockCausedBy;
2817 }
2818 }
2819 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002820 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002821 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002822 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002823 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002824 FeatureUser u = (FeatureUser)msg.obj;
2825 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002826 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002827 case EVENT_INET_CONDITION_CHANGE:
2828 {
2829 int netType = msg.arg1;
2830 int condition = msg.arg2;
2831 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002832 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002833 }
2834 case EVENT_INET_CONDITION_HOLD_END:
2835 {
2836 int netType = msg.arg1;
2837 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002838 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002839 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002840 }
2841 case EVENT_SET_NETWORK_PREFERENCE:
2842 {
2843 int preference = msg.arg1;
2844 handleSetNetworkPreference(preference);
2845 break;
2846 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002847 case EVENT_SET_MOBILE_DATA:
2848 {
2849 boolean enabled = (msg.arg1 == ENABLED);
2850 handleSetMobileData(enabled);
2851 break;
2852 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002853 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2854 {
2855 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002856 break;
2857 }
2858 case EVENT_SET_DEPENDENCY_MET:
2859 {
2860 boolean met = (msg.arg1 == ENABLED);
2861 handleSetDependencyMet(msg.arg2, met);
2862 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002863 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002864 case EVENT_RESTORE_DNS:
2865 {
2866 if (mActiveDefaultNetwork != -1) {
2867 handleDnsConfigurationChange(mActiveDefaultNetwork);
2868 }
2869 break;
2870 }
Wink Saville628b0852011-08-04 15:01:58 -07002871 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2872 {
2873 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002874 sendStickyBroadcast(intent);
2875 break;
2876 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002877 case EVENT_SET_POLICY_DATA_ENABLE: {
2878 final int networkType = msg.arg1;
2879 final boolean enabled = msg.arg2 == ENABLED;
2880 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002881 break;
2882 }
2883 case EVENT_VPN_STATE_CHANGED: {
2884 if (mLockdownTracker != null) {
2885 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2886 }
2887 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002888 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002889 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2890 int tag = mEnableFailFastMobileDataTag.get();
2891 if (msg.arg1 == tag) {
2892 MobileDataStateTracker mobileDst =
2893 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2894 if (mobileDst != null) {
2895 mobileDst.setEnableFailFastMobileData(msg.arg2);
2896 }
2897 } else {
2898 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2899 + " != tag:" + tag);
2900 }
2901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903 }
2904 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002905
2906 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002907 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002908 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002909
2910 if (isTetheringSupported()) {
2911 return mTethering.tether(iface);
2912 } else {
2913 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2914 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002915 }
2916
2917 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002918 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002919 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002920
2921 if (isTetheringSupported()) {
2922 return mTethering.untether(iface);
2923 } else {
2924 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2925 }
2926 }
2927
2928 // javadoc from interface
2929 public int getLastTetherError(String iface) {
2930 enforceTetherAccessPermission();
2931
2932 if (isTetheringSupported()) {
2933 return mTethering.getLastTetherError(iface);
2934 } else {
2935 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2936 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002937 }
2938
2939 // TODO - proper iface API for selection by property, inspection, etc
2940 public String[] getTetherableUsbRegexs() {
2941 enforceTetherAccessPermission();
2942 if (isTetheringSupported()) {
2943 return mTethering.getTetherableUsbRegexs();
2944 } else {
2945 return new String[0];
2946 }
2947 }
2948
2949 public String[] getTetherableWifiRegexs() {
2950 enforceTetherAccessPermission();
2951 if (isTetheringSupported()) {
2952 return mTethering.getTetherableWifiRegexs();
2953 } else {
2954 return new String[0];
2955 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002956 }
2957
Danica Chang6fdd0c62010-08-11 14:54:43 -07002958 public String[] getTetherableBluetoothRegexs() {
2959 enforceTetherAccessPermission();
2960 if (isTetheringSupported()) {
2961 return mTethering.getTetherableBluetoothRegexs();
2962 } else {
2963 return new String[0];
2964 }
2965 }
2966
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002967 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002968 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002969 if (isTetheringSupported()) {
2970 return mTethering.setUsbTethering(enable);
2971 } else {
2972 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2973 }
2974 }
2975
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002976 // TODO - move iface listing, queries, etc to new module
2977 // javadoc from interface
2978 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002979 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002980 return mTethering.getTetherableIfaces();
2981 }
2982
2983 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002984 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002985 return mTethering.getTetheredIfaces();
2986 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002987
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002988 @Override
2989 public String[] getTetheredIfacePairs() {
2990 enforceTetherAccessPermission();
2991 return mTethering.getTetheredIfacePairs();
2992 }
2993
Robert Greenwalt5a735062010-03-02 17:25:02 -08002994 public String[] getTetheringErroredIfaces() {
2995 enforceTetherAccessPermission();
2996 return mTethering.getErroredIfaces();
2997 }
2998
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002999 // if ro.tether.denied = true we default to no tethering
3000 // gservices could set the secure setting to 1 though to enable it on a build where it
3001 // had previously been turned off.
3002 public boolean isTetheringSupported() {
3003 enforceTetherAccessPermission();
3004 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003005 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3006 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08003007 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003008 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003009
3010 // An API NetworkStateTrackers can call when they lose their network.
3011 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3012 // whichever happens first. The timer is started by the first caller and not
3013 // restarted by subsequent callers.
3014 public void requestNetworkTransitionWakelock(String forWhom) {
3015 enforceConnectivityInternalPermission();
3016 synchronized (this) {
3017 if (mNetTransitionWakeLock.isHeld()) return;
3018 mNetTransitionWakeLockSerialNumber++;
3019 mNetTransitionWakeLock.acquire();
3020 mNetTransitionWakeLockCausedBy = forWhom;
3021 }
3022 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003023 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003024 mNetTransitionWakeLockSerialNumber, 0),
3025 mNetTransitionWakeLockTimeout);
3026 return;
3027 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003028
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003029 // 100 percent is full good, 0 is full bad.
3030 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003031 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003032 mContext.enforceCallingOrSelfPermission(
3033 android.Manifest.permission.STATUS_BAR,
3034 "ConnectivityService");
3035
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003036 if (DBG) {
3037 int pid = getCallingPid();
3038 int uid = getCallingUid();
3039 String s = pid + "(" + uid + ") reports inet is " +
3040 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3041 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3042 mInetLog.add(s);
3043 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3044 mInetLog.remove(0);
3045 }
3046 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003047 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003048 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3049 }
3050
3051 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003052 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003053 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003054 return;
3055 }
3056 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003057 if (DBG) log("handleInetConditionChange: net=" + netType +
3058 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003059 return;
3060 }
Wink Savillec9acde92011-09-21 11:05:43 -07003061 if (VDBG) {
3062 log("handleInetConditionChange: net=" +
3063 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003064 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003065 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003066 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003067 int delay;
3068 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003069 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003070 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003071 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003072 delay = Settings.Global.getInt(mContext.getContentResolver(),
3073 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003074 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003075 delay = Settings.Global.getInt(mContext.getContentResolver(),
3076 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003077 }
3078 mInetConditionChangeInFlight = true;
3079 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003080 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003081 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003082 // we've set the new condition, when this hold ends that will get picked up
3083 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003084 }
3085 }
3086
Wink Saville5b7573e2013-01-31 00:30:13 +00003087 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003088 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003089 log("handleInetConditionHoldEnd: net=" + netType +
3090 ", condition=" + mDefaultInetCondition +
3091 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003092 }
3093 mInetConditionChangeInFlight = false;
3094
3095 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003096 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003097 return;
3098 }
3099 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003100 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003101 return;
3102 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003103 // TODO: Figure out why this optimization sometimes causes a
3104 // change in mDefaultInetCondition to be missed and the
3105 // UI to not be updated.
3106 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3107 // if (DBG) log("no change in condition - aborting");
3108 // return;
3109 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003110 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3111 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003112 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003113 return;
3114 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003115 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003116 sendInetConditionBroadcast(networkInfo);
3117 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003118 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003119
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003120 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003121 // this information is already available as a world read/writable jvm property
3122 // so this API change wouldn't have a benifit. It also breaks the passing
3123 // of proxy info to all the JVMs.
3124 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003125 synchronized (mProxyLock) {
3126 if (mGlobalProxy != null) return mGlobalProxy;
3127 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003128 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003129 }
3130
3131 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003132 enforceConnectivityInternalPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003133 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003134 if (proxyProperties == mGlobalProxy) return;
3135 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3136 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3137
3138 String host = "";
3139 int port = 0;
3140 String exclList = "";
3141 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3142 mGlobalProxy = new ProxyProperties(proxyProperties);
3143 host = mGlobalProxy.getHost();
3144 port = mGlobalProxy.getPort();
3145 exclList = mGlobalProxy.getExclusionList();
3146 } else {
3147 mGlobalProxy = null;
3148 }
3149 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003150 final long token = Binder.clearCallingIdentity();
3151 try {
3152 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3153 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3154 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3155 exclList);
3156 } finally {
3157 Binder.restoreCallingIdentity(token);
3158 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003159 }
3160
3161 if (mGlobalProxy == null) {
3162 proxyProperties = mDefaultProxy;
3163 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003164 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003165 }
3166
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003167 private void loadGlobalProxy() {
3168 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003169 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3170 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3171 String exclList = Settings.Global.getString(res,
3172 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003173 if (!TextUtils.isEmpty(host)) {
3174 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003175 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003176 mGlobalProxy = proxyProperties;
3177 }
3178 }
3179 }
3180
Robert Greenwalt434203a2010-10-11 16:00:27 -07003181 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003182 // this information is already available as a world read/writable jvm property
3183 // so this API change wouldn't have a benifit. It also breaks the passing
3184 // of proxy info to all the JVMs.
3185 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003186 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003187 return mGlobalProxy;
3188 }
3189 }
3190
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003191 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3192 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3193 proxy = null;
3194 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003195 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003196 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003197 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003198 mDefaultProxy = proxy;
3199
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003200 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003201 if (!mDefaultProxyDisabled) {
3202 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003203 }
3204 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003205 }
3206
3207 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003208 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3209 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003210 if (!TextUtils.isEmpty(proxy)) {
3211 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003212 if (data.length == 0) {
3213 return;
3214 }
3215
Robert Greenwalt434203a2010-10-11 16:00:27 -07003216 String proxyHost = data[0];
3217 int proxyPort = 8080;
3218 if (data.length > 1) {
3219 try {
3220 proxyPort = Integer.parseInt(data[1]);
3221 } catch (NumberFormatException e) {
3222 return;
3223 }
3224 }
3225 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3226 setGlobalProxy(p);
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003227 } else {
3228 setGlobalProxy(null);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003229 }
3230 }
3231
3232 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003233 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003234 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003235 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003236 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3237 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003238 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003239 final long ident = Binder.clearCallingIdentity();
3240 try {
3241 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3242 } finally {
3243 Binder.restoreCallingIdentity(ident);
3244 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003245 }
3246
3247 private static class SettingsObserver extends ContentObserver {
3248 private int mWhat;
3249 private Handler mHandler;
3250 SettingsObserver(Handler handler, int what) {
3251 super(handler);
3252 mHandler = handler;
3253 mWhat = what;
3254 }
3255
3256 void observe(Context context) {
3257 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003258 resolver.registerContentObserver(Settings.Global.getUriFor(
3259 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003260 }
3261
3262 @Override
3263 public void onChange(boolean selfChange) {
3264 mHandler.obtainMessage(mWhat).sendToTarget();
3265 }
3266 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003267
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003268 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003269 Slog.d(TAG, s);
3270 }
3271
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003272 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003273 Slog.e(TAG, s);
3274 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003275
repo syncaea743a2011-07-29 23:55:49 -07003276 int convertFeatureToNetworkType(int networkType, String feature) {
3277 int usedNetworkType = networkType;
3278
3279 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3280 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3281 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3282 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3283 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3284 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3285 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3286 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3287 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3288 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3289 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3290 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3291 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3292 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3293 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3294 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3295 } else {
3296 Slog.e(TAG, "Can't match any mobile netTracker!");
3297 }
3298 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3299 if (TextUtils.equals(feature, "p2p")) {
3300 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3301 } else {
3302 Slog.e(TAG, "Can't match any wifi netTracker!");
3303 }
3304 } else {
3305 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003306 }
repo syncaea743a2011-07-29 23:55:49 -07003307 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003308 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003309
3310 private static <T> T checkNotNull(T value, String message) {
3311 if (value == null) {
3312 throw new NullPointerException(message);
3313 }
3314 return value;
3315 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003316
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003317 /**
3318 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003319 * VpnBuilder and not available in ConnectivityManager. Permissions
3320 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003321 * @hide
3322 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003323 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003324 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003325 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003326 try {
3327 int type = mActiveDefaultNetwork;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003328 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003329 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003330 synchronized(mVpns) {
3331 mVpns.get(user).protect(socket,
3332 mNetTrackers[type].getLinkProperties().getInterfaceName());
3333 }
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003334 return true;
3335 }
3336 } catch (Exception e) {
3337 // ignore
3338 } finally {
3339 try {
3340 socket.close();
3341 } catch (Exception e) {
3342 // ignore
3343 }
3344 }
3345 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003346 }
3347
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003348 /**
3349 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003350 * and not available in ConnectivityManager. Permissions are checked
3351 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003352 * @hide
3353 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003354 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003355 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003356 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003357 int user = UserHandle.getUserId(Binder.getCallingUid());
3358 synchronized(mVpns) {
3359 return mVpns.get(user).prepare(oldPackage, newPackage);
3360 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003361 }
3362
Chad Brubakerd475c702013-07-11 13:29:30 -07003363 @Override
3364 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3365 enforceMarkNetworkSocketPermission();
3366 final long token = Binder.clearCallingIdentity();
3367 try {
3368 int mark = mNetd.getMarkForUid(uid);
3369 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3370 if (mark == -1) {
3371 mark = 0;
3372 }
3373 NetworkUtils.markSocket(socket.getFd(), mark);
3374 } catch (RemoteException e) {
3375 } finally {
3376 Binder.restoreCallingIdentity(token);
3377 }
3378 }
3379
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003380 /**
3381 * Configure a TUN interface and return its file descriptor. Parameters
3382 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003383 * and not available in ConnectivityManager. Permissions are checked in
3384 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003385 * @hide
3386 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003387 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003388 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003389 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003390 int user = UserHandle.getUserId(Binder.getCallingUid());
3391 synchronized(mVpns) {
3392 return mVpns.get(user).establish(config);
3393 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003394 }
3395
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003396 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003397 * Start legacy VPN, controlling native daemons as needed. Creates a
3398 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003399 */
3400 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003401 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003402 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003403 final LinkProperties egress = getActiveLinkProperties();
3404 if (egress == null) {
3405 throw new IllegalStateException("Missing active network connection");
3406 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003407 int user = UserHandle.getUserId(Binder.getCallingUid());
3408 synchronized(mVpns) {
3409 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3410 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003411 }
3412
3413 /**
3414 * Return the information of the ongoing legacy VPN. This method is used
3415 * by VpnSettings and not available in ConnectivityManager. Permissions
3416 * are checked in Vpn class.
3417 * @hide
3418 */
3419 @Override
3420 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003421 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003422 int user = UserHandle.getUserId(Binder.getCallingUid());
3423 synchronized(mVpns) {
3424 return mVpns.get(user).getLegacyVpnInfo();
3425 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003426 }
3427
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003428 /**
3429 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3430 * through NetworkStateTracker since it works differently. For example, it
3431 * needs to override DNS servers but never takes the default routes. It
3432 * relies on another data network, and it could keep existing connections
3433 * alive after reconnecting, switching between networks, or even resuming
3434 * from deep sleep. Calls from applications should be done synchronously
3435 * to avoid race conditions. As these are all hidden APIs, refactoring can
3436 * be done whenever a better abstraction is developed.
3437 */
3438 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003439 private VpnCallback() {
3440 }
3441
Jeff Sharkey899223b2012-08-04 15:24:58 -07003442 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003443 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003444 }
3445
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003446 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003447 if (dnsServers == null) {
3448 restore();
3449 return;
3450 }
3451
3452 // Convert DNS servers into addresses.
3453 List<InetAddress> addresses = new ArrayList<InetAddress>();
3454 for (String address : dnsServers) {
3455 // Double check the addresses and remove invalid ones.
3456 try {
3457 addresses.add(InetAddress.parseNumericAddress(address));
3458 } catch (Exception e) {
3459 // ignore
3460 }
3461 }
3462 if (addresses.isEmpty()) {
3463 restore();
3464 return;
3465 }
3466
3467 // Concatenate search domains into a string.
3468 StringBuilder buffer = new StringBuilder();
3469 if (searchDomains != null) {
3470 for (String domain : searchDomains) {
3471 buffer.append(domain).append(' ');
3472 }
3473 }
3474 String domains = buffer.toString().trim();
3475
3476 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003477 synchronized (mDnsLock) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003478 updateDnsLocked("VPN", iface, addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003479 mDnsOverridden = true;
3480 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003481
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003482 // Temporarily disable the default proxy (not global).
3483 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003484 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003485 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003486 sendProxyBroadcast(null);
3487 }
3488 }
3489
3490 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003491 }
3492
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003493 public void restore() {
3494 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003495 if (mDnsOverridden) {
3496 mDnsOverridden = false;
3497 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003498 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003499 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003500 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003501 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003502 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003503 sendProxyBroadcast(mDefaultProxy);
3504 }
3505 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003506 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003507
3508 public void protect(ParcelFileDescriptor socket) {
3509 try {
3510 final int mark = mNetd.getMarkForProtect();
3511 NetworkUtils.markSocket(socket.getFd(), mark);
3512 } catch (RemoteException e) {
3513 }
3514 }
3515
3516 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3517 for (RouteInfo route : routes) {
3518 try {
3519 mNetd.setMarkedForwardingRoute(interfaze, route);
3520 } catch (RemoteException e) {
3521 }
3522 }
3523 }
3524
3525 public void setMarkedForwarding(String interfaze) {
3526 try {
3527 mNetd.setMarkedForwarding(interfaze);
3528 } catch (RemoteException e) {
3529 }
3530 }
3531
3532 public void clearMarkedForwarding(String interfaze) {
3533 try {
3534 mNetd.clearMarkedForwarding(interfaze);
3535 } catch (RemoteException e) {
3536 }
3537 }
3538
3539 public void addUserForwarding(String interfaze, int uid) {
3540 int uidStart = uid * UserHandle.PER_USER_RANGE;
3541 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3542 addUidForwarding(interfaze, uidStart, uidEnd);
3543 }
3544
3545 public void clearUserForwarding(String interfaze, int uid) {
3546 int uidStart = uid * UserHandle.PER_USER_RANGE;
3547 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3548 clearUidForwarding(interfaze, uidStart, uidEnd);
3549 }
3550
3551 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3552 try {
3553 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3554 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3555 } catch (RemoteException e) {
3556 }
3557
3558 }
3559
3560 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3561 try {
3562 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3563 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3564 } catch (RemoteException e) {
3565 }
3566
3567 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003568 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003569
3570 @Override
3571 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003572 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3573 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3574 return false;
3575 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003576
3577 // Tear down existing lockdown if profile was removed
3578 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3579 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003580 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003581 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3582 return false;
3583 }
3584
3585 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3586 final VpnProfile profile = VpnProfile.decode(
3587 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003588 int user = UserHandle.getUserId(Binder.getCallingUid());
3589 synchronized(mVpns) {
3590 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3591 profile));
3592 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003593 } else {
3594 setLockdownTracker(null);
3595 }
3596
3597 return true;
3598 }
3599
3600 /**
3601 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3602 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3603 */
3604 private void setLockdownTracker(LockdownVpnTracker tracker) {
3605 // Shutdown any existing tracker
3606 final LockdownVpnTracker existing = mLockdownTracker;
3607 mLockdownTracker = null;
3608 if (existing != null) {
3609 existing.shutdown();
3610 }
3611
3612 try {
3613 if (tracker != null) {
3614 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003615 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003616 mLockdownTracker = tracker;
3617 mLockdownTracker.init();
3618 } else {
3619 mNetd.setFirewallEnabled(false);
3620 }
3621 } catch (RemoteException e) {
3622 // ignored; NMS lives inside system_server
3623 }
3624 }
3625
3626 private void throwIfLockdownEnabled() {
3627 if (mLockdownEnabled) {
3628 throw new IllegalStateException("Unavailable in lockdown mode");
3629 }
3630 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003631
3632 public void supplyMessenger(int networkType, Messenger messenger) {
3633 enforceConnectivityInternalPermission();
3634
3635 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3636 mNetTrackers[networkType].supplyMessenger(messenger);
3637 }
3638 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003639
3640 public int findConnectionTypeForIface(String iface) {
3641 enforceConnectivityInternalPermission();
3642
3643 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3644 for (NetworkStateTracker tracker : mNetTrackers) {
3645 if (tracker != null) {
3646 LinkProperties lp = tracker.getLinkProperties();
3647 if (lp != null && iface.equals(lp.getInterfaceName())) {
3648 return tracker.getNetworkInfo().getType();
3649 }
3650 }
3651 }
3652 return ConnectivityManager.TYPE_NONE;
3653 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003654
3655 /**
3656 * Have mobile data fail fast if enabled.
3657 *
3658 * @param enabled DctConstants.ENABLED/DISABLED
3659 */
3660 private void setEnableFailFastMobileData(int enabled) {
3661 int tag;
3662
3663 if (enabled == DctConstants.ENABLED) {
3664 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3665 } else {
3666 tag = mEnableFailFastMobileDataTag.get();
3667 }
3668 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3669 enabled));
3670 }
3671
3672 @Override
Wink Savillec2fee242013-07-19 09:27:56 -07003673 public int checkMobileProvisioning(final boolean sendNotification, int suggestedTimeOutMs,
Wink Savilleab9321d2013-06-29 21:10:57 -07003674 final ResultReceiver resultReceiver) {
3675 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3676 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3677 + " resultReceiver=" + resultReceiver);
3678 enforceChangePermission();
3679
3680 int timeOutMs = suggestedTimeOutMs;
3681 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3682 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3683 }
3684
Wink Saville68e6c642013-07-02 10:55:14 -07003685 // Check that mobile networks are supported
3686 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3687 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3688 log("checkMobileProvisioning: X no mobile network");
3689 if (resultReceiver != null) {
3690 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3691 }
3692 return timeOutMs;
3693 }
3694
Wink Savilleab9321d2013-06-29 21:10:57 -07003695 final long token = Binder.clearCallingIdentity();
3696 try {
3697 CheckMp checkMp = new CheckMp(mContext, this);
3698 CheckMp.CallBack cb = new CheckMp.CallBack() {
3699 @Override
3700 void onComplete(Integer result) {
3701 log("CheckMp.onComplete: result=" + result);
3702 if (resultReceiver != null) {
3703 log("CheckMp.onComplete: send result");
3704 resultReceiver.send(result, null);
3705 }
Wink Savillec2fee242013-07-19 09:27:56 -07003706 if (!sendNotification) {
3707 log("CheckMp.onComplete: done, not sending notification");
3708 return;
3709 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003710 NetworkInfo ni =
3711 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3712 switch(result) {
3713 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3714 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3715 log("CheckMp.onComplete: ignore, connected or no connection");
3716 break;
3717 }
3718 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3719 log("CheckMp.onComplete: warm sim");
3720 String url = getProvisioningUrl();
3721 if (TextUtils.isEmpty(url)) {
3722 url = mContext.getResources()
3723 .getString(R.string.mobile_redirected_provisioning_url);
3724 }
3725 if (TextUtils.isEmpty(url) == false) {
3726 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3727 setNotificationVisible(true, ni, url);
3728 } else {
3729 log("CheckMp.onComplete: warm sim (redirected), no url");
3730 }
3731 break;
3732 }
3733 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3734 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3735 String url = getProvisioningUrl();
3736 if (TextUtils.isEmpty(url) == false) {
3737 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3738 setNotificationVisible(true, ni, url);
3739 } else {
3740 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3741 }
3742 break;
3743 }
3744 default: {
3745 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3746 break;
3747 }
3748 }
3749 }
3750 };
3751 CheckMp.Params params =
3752 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3753 log("checkMobileProvisioning: params=" + params);
3754 setNotificationVisible(false, null, null);
3755 checkMp.execute(params);
3756 } finally {
3757 Binder.restoreCallingIdentity(token);
3758 log("checkMobileProvisioning: X");
3759 }
3760 return timeOutMs;
3761 }
3762
3763 static class CheckMp extends
3764 AsyncTask<CheckMp.Params, Void, Integer> {
3765 private static final String CHECKMP_TAG = "CheckMp";
3766 public static final int MAX_TIMEOUT_MS = 60000;
3767 private static final int SOCKET_TIMEOUT_MS = 5000;
3768 private Context mContext;
3769 private ConnectivityService mCs;
3770 private TelephonyManager mTm;
3771 private Params mParams;
3772
3773 /**
3774 * Parameters for AsyncTask.execute
3775 */
3776 static class Params {
3777 private String mUrl;
3778 private long mTimeOutMs;
3779 private CallBack mCb;
3780
3781 Params(String url, long timeOutMs, CallBack cb) {
3782 mUrl = url;
3783 mTimeOutMs = timeOutMs;
3784 mCb = cb;
3785 }
3786
3787 @Override
3788 public String toString() {
3789 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3790 }
3791 }
3792
3793 /**
3794 * The call back object passed in Params. onComplete will be called
3795 * on the main thread.
3796 */
3797 abstract static class CallBack {
3798 // Called on the main thread.
3799 abstract void onComplete(Integer result);
3800 }
3801
3802 public CheckMp(Context context, ConnectivityService cs) {
3803 mContext = context;
3804 mCs = cs;
3805
3806 // Setup access to TelephonyService we'll be using.
3807 mTm = (TelephonyManager) mContext.getSystemService(
3808 Context.TELEPHONY_SERVICE);
3809 }
3810
3811 /**
3812 * Get the default url to use for the test.
3813 */
3814 public String getDefaultUrl() {
3815 // See http://go/clientsdns for usage approval
3816 String server = Settings.Global.getString(mContext.getContentResolver(),
3817 Settings.Global.CAPTIVE_PORTAL_SERVER);
3818 if (server == null) {
3819 server = "clients3.google.com";
3820 }
3821 return "http://" + server + "/generate_204";
3822 }
3823
3824 /**
3825 * Detect if its possible to connect to the http url. DNS based detection techniques
3826 * do not work at all hotspots. The best way to check is to perform a request to
3827 * a known address that fetches the data we expect.
3828 */
3829 private synchronized Integer isMobileOk(Params params) {
3830 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3831 Uri orgUri = Uri.parse(params.mUrl);
3832 Random rand = new Random();
3833 mParams = params;
3834
3835 try {
3836 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3837 log("isMobileOk: not mobile capable");
3838 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3839 return result;
3840 }
3841
3842 // Enable fail fast as we'll do retries here and use a
3843 // hipri connection so the default connection stays active.
3844 log("isMobileOk: start hipri url=" + params.mUrl);
3845 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3846 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3847 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3848
3849 // Continue trying to connect until time has run out
3850 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3851 while(SystemClock.elapsedRealtime() < endTime) {
3852 try {
3853 // Wait for hipri to connect.
3854 // TODO: Don't poll and handle situation where hipri fails
3855 // because default is retrying. See b/9569540
3856 NetworkInfo.State state = mCs
3857 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3858 if (state != NetworkInfo.State.CONNECTED) {
3859 log("isMobileOk: not connected ni=" +
3860 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3861 sleep(1);
3862 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3863 continue;
3864 }
3865
3866 // Get of the addresses associated with the url host. We need to use the
3867 // address otherwise HttpURLConnection object will use the name to get
3868 // the addresses and is will try every address but that will bypass the
3869 // route to host we setup and the connection could succeed as the default
3870 // interface might be connected to the internet via wifi or other interface.
3871 InetAddress[] addresses;
3872 try {
3873 addresses = InetAddress.getAllByName(orgUri.getHost());
3874 } catch (UnknownHostException e) {
3875 log("isMobileOk: UnknownHostException");
3876 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3877 return result;
3878 }
3879 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3880
3881 // Get the type of addresses supported by this link
3882 LinkProperties lp = mCs.getLinkProperties(
3883 ConnectivityManager.TYPE_MOBILE_HIPRI);
3884 boolean linkHasIpv4 = hasIPv4Address(lp);
3885 boolean linkHasIpv6 = hasIPv6Address(lp);
3886 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3887 + " linkHasIpv6=" + linkHasIpv6);
3888
3889 // Loop through at most 3 valid addresses or all of the address or until
3890 // we run out of time
3891 int loops = Math.min(3, addresses.length);
3892 for(int validAddr=0, addrTried=0;
3893 (validAddr < loops) && (addrTried < addresses.length)
3894 && (SystemClock.elapsedRealtime() < endTime);
3895 addrTried ++) {
3896
3897 // Choose the address at random but make sure its type is supported
3898 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3899 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3900 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3901 // Valid address, so use it
3902 validAddr += 1;
3903 } else {
3904 // Invalid address so try next address
3905 continue;
3906 }
3907
3908 // Make a route to host so we check the specific interface.
3909 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3910 hostAddr.getAddress())) {
3911 // Wait a short time to be sure the route is established ??
3912 log("isMobileOk:"
3913 + " wait to establish route to hostAddr=" + hostAddr);
3914 sleep(3);
3915 } else {
3916 log("isMobileOk:"
3917 + " could not establish route to hostAddr=" + hostAddr);
3918 continue;
3919 }
3920
3921 // Rewrite the url to have numeric address to use the specific route.
3922 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3923 // is used which is useless in this case.
3924 URL newUrl = new URL(orgUri.getScheme() + "://"
3925 + hostAddr.getHostAddress() + orgUri.getPath());
3926 log("isMobileOk: newUrl=" + newUrl);
3927
3928 HttpURLConnection urlConn = null;
3929 try {
3930 // Open the connection set the request header and get the response
3931 urlConn = (HttpURLConnection) newUrl.openConnection(
3932 java.net.Proxy.NO_PROXY);
3933 urlConn.setInstanceFollowRedirects(false);
3934 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3935 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3936 urlConn.setUseCaches(false);
3937 urlConn.setAllowUserInteraction(false);
3938 urlConn.setRequestProperty("Connection", "close");
3939 int responseCode = urlConn.getResponseCode();
3940 if (responseCode == 204) {
3941 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3942 } else {
3943 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3944 }
3945 log("isMobileOk: connected responseCode=" + responseCode);
3946 urlConn.disconnect();
3947 urlConn = null;
3948 return result;
3949 } catch (Exception e) {
3950 log("isMobileOk: HttpURLConnection Exception e=" + e);
3951 if (urlConn != null) {
3952 urlConn.disconnect();
3953 urlConn = null;
3954 }
3955 }
3956 }
3957 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3958 log("isMobileOk: loops|timed out");
3959 return result;
3960 } catch (Exception e) {
3961 log("isMobileOk: Exception e=" + e);
3962 continue;
3963 }
3964 }
3965 log("isMobileOk: timed out");
3966 } finally {
3967 log("isMobileOk: F stop hipri");
3968 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3969 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3970 Phone.FEATURE_ENABLE_HIPRI);
3971 log("isMobileOk: X result=" + result);
3972 }
3973 return result;
3974 }
3975
3976 @Override
3977 protected Integer doInBackground(Params... params) {
3978 return isMobileOk(params[0]);
3979 }
3980
3981 @Override
3982 protected void onPostExecute(Integer result) {
3983 log("onPostExecute: result=" + result);
3984 if ((mParams != null) && (mParams.mCb != null)) {
3985 mParams.mCb.onComplete(result);
3986 }
3987 }
3988
3989 private String inetAddressesToString(InetAddress[] addresses) {
3990 StringBuffer sb = new StringBuffer();
3991 boolean firstTime = true;
3992 for(InetAddress addr : addresses) {
3993 if (firstTime) {
3994 firstTime = false;
3995 } else {
3996 sb.append(",");
3997 }
3998 sb.append(addr);
3999 }
4000 return sb.toString();
4001 }
4002
4003 private void printNetworkInfo() {
4004 boolean hasIccCard = mTm.hasIccCard();
4005 int simState = mTm.getSimState();
4006 log("hasIccCard=" + hasIccCard
4007 + " simState=" + simState);
4008 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4009 if (ni != null) {
4010 log("ni.length=" + ni.length);
4011 for (NetworkInfo netInfo: ni) {
4012 log("netInfo=" + netInfo.toString());
4013 }
4014 } else {
4015 log("no network info ni=null");
4016 }
4017 }
4018
4019 /**
4020 * Sleep for a few seconds then return.
4021 * @param seconds
4022 */
4023 private static void sleep(int seconds) {
4024 try {
4025 Thread.sleep(seconds * 1000);
4026 } catch (InterruptedException e) {
4027 e.printStackTrace();
4028 }
4029 }
4030
4031 public boolean hasIPv4Address(LinkProperties lp) {
4032 return lp.hasIPv4Address();
4033 }
4034
4035 // Not implemented in LinkProperties, do it here.
4036 public boolean hasIPv6Address(LinkProperties lp) {
4037 for (LinkAddress address : lp.getLinkAddresses()) {
4038 if (address.getAddress() instanceof Inet6Address) {
4039 return true;
4040 }
4041 }
4042 return false;
4043 }
4044
4045 private void log(String s) {
4046 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4047 }
4048 }
4049
4050 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4051
4052 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4053 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4054
4055 Resources r = Resources.getSystem();
4056 NotificationManager notificationManager = (NotificationManager) mContext
4057 .getSystemService(Context.NOTIFICATION_SERVICE);
4058
4059 if (visible) {
4060 CharSequence title;
4061 CharSequence details;
4062 int icon;
4063 switch (networkInfo.getType()) {
4064 case ConnectivityManager.TYPE_WIFI:
4065 log("setNotificationVisible: TYPE_WIFI");
4066 title = r.getString(R.string.wifi_available_sign_in, 0);
4067 details = r.getString(R.string.network_available_sign_in_detailed,
4068 networkInfo.getExtraInfo());
4069 icon = R.drawable.stat_notify_wifi_in_range;
4070 break;
4071 case ConnectivityManager.TYPE_MOBILE:
4072 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4073 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4074 title = r.getString(R.string.network_available_sign_in, 0);
4075 // TODO: Change this to pull from NetworkInfo once a printable
4076 // name has been added to it
4077 details = mTelephonyManager.getNetworkOperatorName();
4078 icon = R.drawable.stat_notify_rssi_in_range;
4079 break;
4080 default:
4081 log("setNotificationVisible: other type=" + networkInfo.getType());
4082 title = r.getString(R.string.network_available_sign_in, 0);
4083 details = r.getString(R.string.network_available_sign_in_detailed,
4084 networkInfo.getExtraInfo());
4085 icon = R.drawable.stat_notify_rssi_in_range;
4086 break;
4087 }
4088
4089 Notification notification = new Notification();
4090 notification.when = 0;
4091 notification.icon = icon;
4092 notification.flags = Notification.FLAG_AUTO_CANCEL;
4093 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4094 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4095 Intent.FLAG_ACTIVITY_NEW_TASK);
4096 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4097 notification.tickerText = title;
4098 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4099
4100 log("setNotificaitionVisible: notify notificaiton=" + notification);
4101 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4102 } else {
4103 log("setNotificaitionVisible: cancel");
4104 notificationManager.cancel(NOTIFICATION_ID, 1);
4105 }
4106 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4107 }
4108
4109 private String getProvisioningUrl() {
4110 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8cf35602013-07-10 23:00:07 -07004111 log("getProvisioningUrl: mobile_provisioning_url=" + url);
Wink Savilleab9321d2013-06-29 21:10:57 -07004112
Wink Saville8cf35602013-07-10 23:00:07 -07004113 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004114 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004115 String phoneNumber = mTelephonyManager.getLine1Number();
4116 if (TextUtils.isEmpty(phoneNumber)) {
4117 phoneNumber = "0000000000";
4118 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004119 url = String.format(url,
4120 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4121 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004122 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004123 }
4124
Wink Savilleab9321d2013-06-29 21:10:57 -07004125 return url;
4126 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004127
4128 private void onUserStart(int userId) {
4129 synchronized(mVpns) {
4130 Vpn userVpn = mVpns.get(userId);
4131 if (userVpn != null) {
4132 loge("Starting user already has a VPN");
4133 return;
4134 }
4135 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4136 mVpns.put(userId, userVpn);
4137 userVpn.startMonitoring(mContext, mTrackerHandler);
4138 }
4139 }
4140
4141 private void onUserStop(int userId) {
4142 synchronized(mVpns) {
4143 Vpn userVpn = mVpns.get(userId);
4144 if (userVpn == null) {
4145 loge("Stopping user has no VPN");
4146 return;
4147 }
4148 mVpns.delete(userId);
4149 }
4150 }
4151
4152 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4153 @Override
4154 public void onReceive(Context context, Intent intent) {
4155 final String action = intent.getAction();
4156 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4157 if (userId == UserHandle.USER_NULL) return;
4158
4159 if (Intent.ACTION_USER_STARTING.equals(action)) {
4160 onUserStart(userId);
4161 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4162 onUserStop(userId);
4163 }
4164 }
4165 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166}