blob: cbbfda18c325e70c73e1b19a9b3852f9b35a135c [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070020import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070021import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070022import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
23import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
25import static android.net.ConnectivityManager.TYPE_DUMMY;
26import static android.net.ConnectivityManager.TYPE_ETHERNET;
27import static android.net.ConnectivityManager.TYPE_MOBILE;
28import static android.net.ConnectivityManager.TYPE_WIFI;
29import static android.net.ConnectivityManager.TYPE_WIMAX;
30import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070031import static android.net.ConnectivityManager.isNetworkTypeValid;
32import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080035import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070036import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080037import android.content.ContentResolver;
38import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090039import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080040import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070041import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090043import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070044import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070045import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080047import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080048import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080049import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070054import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080055import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070056import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070058import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070060import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070061import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070062import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070064import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070065import android.net.Proxy;
66import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070067import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090069import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project28527d22009-03-03 19:31:44 -080070import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040071import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070073import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070074import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070075import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.os.Looper;
77import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070078import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070079import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070080import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070082import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080083import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070084import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070086import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070087import android.security.KeyStore;
Robert Greenwalt2034b912009-08-12 16:08:25 -070088import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080089import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080090import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070091import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070093import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070094import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070095import com.android.internal.net.VpnProfile;
Robert Greenwalt2034b912009-08-12 16:08:25 -070096import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -070097import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -070098import com.android.server.am.BatteryStatsService;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080099import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700100import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700101import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700102import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700103import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700104import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700105
tk.mun093f55c2011-10-13 22:51:57 +0900106import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700107
The Android Open Source Project28527d22009-03-03 19:31:44 -0800108import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700109import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900111import java.lang.reflect.Constructor;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700112import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700113import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700114import java.net.InetAddress;
115import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700116import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700117import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700118import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700119import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700120import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700121import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122
123/**
124 * @hide
125 */
126public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700127 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800128
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700129 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700130 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800131
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700132 private static final boolean LOGD_RULES = false;
133
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700134 // TODO: create better separation between radio types and network types
135
Robert Greenwalt2034b912009-08-12 16:08:25 -0700136 // how long to wait before switching back to a radio's default network
137 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
138 // system property that can override the above value
139 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
140 "android.telephony.apn-restore";
141
Robert Greenwaltbd492212011-05-06 17:10:53 -0700142 // used in recursive route setting to add gateways for the host for which
143 // a host route was requested.
144 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
145
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800146 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800147 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800148
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700149 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700150
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700151 private Vpn mVpn;
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700152 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700153
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700154 private boolean mLockdownEnabled;
155 private LockdownVpnTracker mLockdownTracker;
156
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700157 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
158 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700159 /** Currently active network rules by UID. */
160 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700161 /** Set of ifaces that are costly. */
162 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700163
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164 /**
165 * Sometimes we want to refer to the individual network state
166 * trackers separately, and sometimes we just want to treat them
167 * abstractly.
168 */
169 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700170
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700171 /* Handles captive portal check on a network */
172 private CaptivePortalTracker mCaptivePortalTracker;
173
Robert Greenwalt2034b912009-08-12 16:08:25 -0700174 /**
Wink Saville051a6642011-07-13 13:44:13 -0700175 * The link properties that define the current links
176 */
177 private LinkProperties mCurrentLinkProperties[];
178
179 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700180 * A per Net list of the PID's that requested access to the net
181 * used both as a refcount and for per-PID DNS selection
182 */
183 private List mNetRequestersPids[];
184
Robert Greenwalt2034b912009-08-12 16:08:25 -0700185 // priority order of the nettrackers
186 // (excluding dynamically set mNetworkPreference)
187 // TODO - move mNetworkTypePreference into this
188 private int[] mPriorityList;
189
The Android Open Source Project28527d22009-03-03 19:31:44 -0800190 private Context mContext;
191 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700192 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700193 // 0 is full bad, 100 is full good
194 private int mDefaultInetCondition = 0;
195 private int mDefaultInetConditionPublished = 0;
196 private boolean mInetConditionChangeInFlight = false;
197 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198
Chia-chi Yehcc844502011-07-14 18:01:57 -0700199 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700201 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202
203 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700204 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800205
Robert Greenwalt355205c2011-05-10 15:05:02 -0700206 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700207 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700208
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700209 private static final int ENABLED = 1;
210 private static final int DISABLED = 0;
211
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700212 private static final boolean ADD = true;
213 private static final boolean REMOVE = false;
214
215 private static final boolean TO_DEFAULT_TABLE = true;
216 private static final boolean TO_SECONDARY_TABLE = false;
217
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700218 /**
219 * used internally as a delayed event to make us switch back to the
220 * default network
221 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700222 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700223
224 /**
225 * used internally to change our mobile data enabled flag
226 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700227 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700228
229 /**
230 * used internally to change our network preference setting
231 * arg1 = networkType to prefer
232 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700233 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700234
235 /**
236 * used internally to synchronize inet condition reports
237 * arg1 = networkType
238 * arg2 = condition (0 bad, 100 good)
239 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700240 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700241
242 /**
243 * used internally to mark the end of inet condition hold periods
244 * arg1 = networkType
245 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700246 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700247
248 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700249 * used internally to set enable/disable cellular data
250 * arg1 = ENBALED or DISABLED
251 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700252 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700253
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700254 /**
255 * used internally to clear a wakelock when transitioning
256 * from one net to another
257 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700258 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700259
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700260 /**
261 * used internally to reload global proxy settings
262 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700263 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700264
Robert Greenwalt34848c02011-03-25 13:09:25 -0700265 /**
266 * used internally to set external dependency met/unmet
267 * arg1 = ENABLED (met) or DISABLED (unmet)
268 * arg2 = NetworkType
269 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700270 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700271
Chia-chi Yehcc844502011-07-14 18:01:57 -0700272 /**
273 * used internally to restore DNS properties back to the
274 * default network
275 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700276 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700277
Wink Saville7e4333c2011-08-05 11:40:22 -0700278 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700279 * used internally to send a sticky broadcast delayed.
280 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700281 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700282
Jeff Sharkey805662d2011-08-19 02:24:24 -0700283 /**
284 * Used internally to
285 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
286 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700287 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700288
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700289 private static final int EVENT_VPN_STATE_CHANGED = 14;
290
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700291 /** Handler used for internal events. */
292 private InternalHandler mHandler;
293 /** Handler used for incoming {@link NetworkStateTracker} events. */
294 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700295
296 // list of DeathRecipients used to make sure features are turned off when
297 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500298 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700299
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400300 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800301 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400302
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700303 private PowerManager.WakeLock mNetTransitionWakeLock;
304 private String mNetTransitionWakeLockCausedBy = "";
305 private int mNetTransitionWakeLockSerialNumber;
306 private int mNetTransitionWakeLockTimeout;
307
Robert Greenwalt94daa182010-09-01 11:34:05 -0700308 private InetAddress mDefaultDns;
309
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700310 // this collection is used to refcount the added routes - if there are none left
311 // it's time to remove the route from the route table
312 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
313
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700314 // used in DBG mode to track inet condition reports
315 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
316 private ArrayList mInetLog;
317
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700318 // track the current default http proxy - tell the world if we get a new one (real change)
319 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700320 private Object mDefaultProxyLock = new Object();
321 private boolean mDefaultProxyDisabled = false;
322
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700323 // track the global proxy.
324 private ProxyProperties mGlobalProxy = null;
325 private final Object mGlobalProxyLock = new Object();
326
327 private SettingsObserver mSettingsObserver;
328
Robert Greenwalt34848c02011-03-25 13:09:25 -0700329 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700330 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700331
Robert Greenwalt12c44552009-12-07 11:33:18 -0800332 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700333 public int mSimultaneity;
334 public int mType;
335 public RadioAttributes(String init) {
336 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700337 mType = Integer.parseInt(fragments[0]);
338 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700339 }
340 }
341 RadioAttributes[] mRadioAttributes;
342
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700343 // the set of network types that can only be enabled by system/sig apps
344 List mProtectedNetworks;
345
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700346 public ConnectivityService(Context context, INetworkManagementService netd,
347 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700348 // Currently, omitting a NetworkFactory will create one internally
349 // TODO: create here when we have cleaner WiMAX support
350 this(context, netd, statsService, policyManager, null);
351 }
352
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700353 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700354 INetworkStatsService statsService, INetworkPolicyManager policyManager,
355 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800356 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800357
Wink Saville775aad62010-09-02 19:23:52 -0700358 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
359 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700360 mHandler = new InternalHandler(handlerThread.getLooper());
361 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700362
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700363 if (netFactory == null) {
364 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
365 }
366
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800367 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800368 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
369 String id = Settings.Secure.getString(context.getContentResolver(),
370 Settings.Secure.ANDROID_ID);
371 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700372 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800373 SystemProperties.set("net.hostname", name);
374 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800375 }
376
Robert Greenwalt94daa182010-09-01 11:34:05 -0700377 // read our default dns server ip
378 String dns = Settings.Secure.getString(context.getContentResolver(),
379 Settings.Secure.DEFAULT_DNS_SERVER);
380 if (dns == null || dns.length() == 0) {
381 dns = context.getResources().getString(
382 com.android.internal.R.string.config_default_dns_server);
383 }
384 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800385 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
386 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800387 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700388 }
389
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700390 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700391 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700392 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700393 mKeyStore = KeyStore.getInstance();
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700394
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700395 try {
396 mPolicyManager.registerListener(mPolicyListener);
397 } catch (RemoteException e) {
398 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700399 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700400 }
401
402 final PowerManager powerManager = (PowerManager) context.getSystemService(
403 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700404 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
405 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
406 com.android.internal.R.integer.config_networkTransitionTimeout);
407
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408 mNetTrackers = new NetworkStateTracker[
409 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700410 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700411
The Android Open Source Project28527d22009-03-03 19:31:44 -0800412 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700413
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700414 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700415 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700416
Robert Greenwalt2034b912009-08-12 16:08:25 -0700417 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700418 String[] raStrings = context.getResources().getStringArray(
419 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700420 for (String raString : raStrings) {
421 RadioAttributes r = new RadioAttributes(raString);
422 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800423 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700424 continue;
425 }
426 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800427 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 r.mType);
429 continue;
430 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700431 mRadioAttributes[r.mType] = r;
432 }
433
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700434 String[] naStrings = context.getResources().getStringArray(
435 com.android.internal.R.array.networkAttributes);
436 for (String naString : naStrings) {
437 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700438 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700439 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800440 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700441 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700442 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700443 }
Wink Savillef2a62832011-04-07 14:23:45 -0700444 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800445 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700446 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447 continue;
448 }
Wink Savillef2a62832011-04-07 14:23:45 -0700449 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800450 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700451 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 continue;
453 }
Wink Savillef2a62832011-04-07 14:23:45 -0700454 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700455 mNetworksDefined++;
456 } catch(Exception e) {
457 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700458 }
459 }
460
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700461 mProtectedNetworks = new ArrayList<Integer>();
462 int[] protectedNetworks = context.getResources().getIntArray(
463 com.android.internal.R.array.config_protectedNetworks);
464 for (int p : protectedNetworks) {
465 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
466 mProtectedNetworks.add(p);
467 } else {
468 if (DBG) loge("Ignoring protectedNetwork " + p);
469 }
470 }
471
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700472 // high priority first
473 mPriorityList = new int[mNetworksDefined];
474 {
475 int insertionPoint = mNetworksDefined-1;
476 int currentLowest = 0;
477 int nextLowest = 0;
478 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700479 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700480 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700481 if (na.priority < currentLowest) continue;
482 if (na.priority > currentLowest) {
483 if (na.priority < nextLowest || nextLowest == 0) {
484 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700485 }
486 continue;
487 }
Wink Savillef2a62832011-04-07 14:23:45 -0700488 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700489 }
490 currentLowest = nextLowest;
491 nextLowest = 0;
492 }
493 }
494
495 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
496 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700497 mNetRequestersPids[i] = new ArrayList();
498 }
499
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500500 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700501
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700502 mNumDnsEntries = 0;
503
504 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
505 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700506
507 // Create and start trackers for hard-coded networks
508 for (int targetNetworkType : mPriorityList) {
509 final NetworkConfig config = mNetConfigs[targetNetworkType];
510 final NetworkStateTracker tracker;
511 try {
512 tracker = netFactory.createTracker(targetNetworkType, config);
513 mNetTrackers[targetNetworkType] = tracker;
514 } catch (IllegalArgumentException e) {
515 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
516 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700517 continue;
518 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700519
520 tracker.startMonitoring(context, mTrackerHandler);
521 if (config.isDefault()) {
522 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800523 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700524 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800525
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700526 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700527 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700528 mTethering.getTetherableWifiRegexs().length != 0 ||
529 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700530 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800531
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700532 mVpn = new Vpn(mContext, mVpnCallback, mNetd);
533 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700534
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700535 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700536 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700537 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700538 } catch (RemoteException e) {
539 loge("Error registering observer :" + e);
540 }
541
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700542 if (DBG) {
543 mInetLog = new ArrayList();
544 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700545
546 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
547 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800548
549 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800550 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700551
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700552 /**
553 * Factory that creates {@link NetworkStateTracker} instances using given
554 * {@link NetworkConfig}.
555 */
556 public interface NetworkFactory {
557 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
558 }
559
560 private static class DefaultNetworkFactory implements NetworkFactory {
561 private final Context mContext;
562 private final Handler mTrackerHandler;
563
564 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
565 mContext = context;
566 mTrackerHandler = trackerHandler;
567 }
568
569 @Override
570 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
571 switch (config.radio) {
572 case TYPE_WIFI:
573 return new WifiStateTracker(targetNetworkType, config.name);
574 case TYPE_MOBILE:
575 return new MobileDataStateTracker(targetNetworkType, config.name);
576 case TYPE_DUMMY:
577 return new DummyDataStateTracker(targetNetworkType, config.name);
578 case TYPE_BLUETOOTH:
579 return BluetoothTetheringDataTracker.getInstance();
580 case TYPE_WIMAX:
581 return makeWimaxStateTracker(mContext, mTrackerHandler);
582 case TYPE_ETHERNET:
583 return EthernetDataTracker.getInstance();
584 default:
585 throw new IllegalArgumentException(
586 "Trying to create a NetworkStateTracker for an unknown radio type: "
587 + config.radio);
588 }
589 }
590 }
591
592 /**
593 * Loads external WiMAX library and registers as system service, returning a
594 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
595 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
596 */
597 private static NetworkStateTracker makeWimaxStateTracker(
598 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700599 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900600 DexClassLoader wimaxClassLoader;
601 Class wimaxStateTrackerClass = null;
602 Class wimaxServiceClass = null;
603 Class wimaxManagerClass;
604 String wimaxJarLocation;
605 String wimaxLibLocation;
606 String wimaxManagerClassName;
607 String wimaxServiceClassName;
608 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800609
tk.mun093f55c2011-10-13 22:51:57 +0900610 NetworkStateTracker wimaxStateTracker = null;
611
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700612 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900613 com.android.internal.R.bool.config_wimaxEnabled);
614
615 if (isWimaxEnabled) {
616 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700617 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900618 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700619 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900620 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700621 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900622 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700623 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900624 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700625 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900626 com.android.internal.R.string.config_wimaxStateTrackerClassname);
627
628 log("wimaxJarLocation: " + wimaxJarLocation);
629 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700630 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900631 wimaxLibLocation, ClassLoader.getSystemClassLoader());
632
633 try {
634 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
635 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
636 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
637 } catch (ClassNotFoundException ex) {
638 loge("Exception finding Wimax classes: " + ex.toString());
639 return null;
640 }
641 } catch(Resources.NotFoundException ex) {
642 loge("Wimax Resources does not exist!!! ");
643 return null;
644 }
645
646 try {
647 log("Starting Wimax Service... ");
648
649 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
650 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700651 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
652 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900653
654 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
655 (new Class[] {Context.class, wimaxStateTrackerClass});
656 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700657 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900658 wmxSrvConst.setAccessible(false);
659
660 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
661
662 } catch(Exception ex) {
663 loge("Exception creating Wimax classes: " + ex.toString());
664 return null;
665 }
666 } else {
667 loge("Wimax is not enabled or not added to the network attributes!!! ");
668 return null;
669 }
670
671 return wimaxStateTracker;
672 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700673
The Android Open Source Project28527d22009-03-03 19:31:44 -0800674 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700675 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800676 * @param preference the new preference
677 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700678 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800679 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700680
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700681 mHandler.sendMessage(
682 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800683 }
684
685 public int getNetworkPreference() {
686 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700687 int preference;
688 synchronized(this) {
689 preference = mNetworkPreference;
690 }
691 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800692 }
693
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700694 private void handleSetNetworkPreference(int preference) {
695 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700696 mNetConfigs[preference] != null &&
697 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700698 if (mNetworkPreference != preference) {
699 final ContentResolver cr = mContext.getContentResolver();
700 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
701 synchronized(this) {
702 mNetworkPreference = preference;
703 }
704 enforcePreference();
705 }
706 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800707 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700708
Wink Saville4f0de1e2011-08-04 15:01:58 -0700709 private int getConnectivityChangeDelay() {
710 final ContentResolver cr = mContext.getContentResolver();
711
712 /** Check system properties for the default value then use secure settings value, if any. */
713 int defaultDelay = SystemProperties.getInt(
714 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
715 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
716 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
717 defaultDelay);
718 }
719
The Android Open Source Project28527d22009-03-03 19:31:44 -0800720 private int getPersistedNetworkPreference() {
721 final ContentResolver cr = mContext.getContentResolver();
722
723 final int networkPrefSetting = Settings.Secure
724 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
725 if (networkPrefSetting != -1) {
726 return networkPrefSetting;
727 }
728
729 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
730 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700731
The Android Open Source Project28527d22009-03-03 19:31:44 -0800732 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700733 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800734 * In this method, we only tear down a non-preferred network. Establishing
735 * a connection to the preferred network is taken care of when we handle
736 * the disconnect event from the non-preferred network
737 * (see {@link #handleDisconnect(NetworkInfo)}).
738 */
739 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700740 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800741 return;
742
Robert Greenwalt2034b912009-08-12 16:08:25 -0700743 if (!mNetTrackers[mNetworkPreference].isAvailable())
744 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800745
Robert Greenwalt2034b912009-08-12 16:08:25 -0700746 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700747 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700748 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700749 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800750 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700751 " in enforcePreference");
752 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700753 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800754 }
755 }
756 }
757
758 private boolean teardown(NetworkStateTracker netTracker) {
759 if (netTracker.teardown()) {
760 netTracker.setTeardownRequested(true);
761 return true;
762 } else {
763 return false;
764 }
765 }
766
767 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700768 * Check if UID should be blocked from using the network represented by the
769 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700770 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700771 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
772 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700773
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700774 final boolean networkCostly;
775 final int uidRules;
776 synchronized (mRulesLock) {
777 networkCostly = mMeteredIfaces.contains(iface);
778 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700779 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700780
781 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
782 return true;
783 }
784
785 // no restrictive rules; network is visible
786 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700787 }
788
789 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700790 * Return a filtered {@link NetworkInfo}, potentially marked
791 * {@link DetailedState#BLOCKED} based on
792 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700793 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700794 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
795 NetworkInfo info = tracker.getNetworkInfo();
796 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700797 // network is blocked; clone and override state
798 info = new NetworkInfo(info);
799 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700800 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700801 if (mLockdownTracker != null) {
802 info = mLockdownTracker.augmentNetworkInfo(info);
803 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700804 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700805 }
806
807 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800808 * Return NetworkInfo for the active (i.e., connected) network interface.
809 * It is assumed that at most one network is active at a time. If more
810 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700811 * @return the info for the active network, or {@code null} if none is
812 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700814 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800815 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700816 enforceAccessPermission();
817 final int uid = Binder.getCallingUid();
818 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800819 }
820
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700821 public NetworkInfo getActiveNetworkInfoUnfiltered() {
822 enforceAccessPermission();
823 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
824 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
825 if (tracker != null) {
826 return tracker.getNetworkInfo();
827 }
828 }
829 return null;
830 }
831
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700832 @Override
833 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
834 enforceConnectivityInternalPermission();
835 return getNetworkInfo(mActiveDefaultNetwork, uid);
836 }
837
838 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800839 public NetworkInfo getNetworkInfo(int networkType) {
840 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700841 final int uid = Binder.getCallingUid();
842 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800843 }
844
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700845 private NetworkInfo getNetworkInfo(int networkType, int uid) {
846 NetworkInfo info = null;
847 if (isNetworkTypeValid(networkType)) {
848 final NetworkStateTracker tracker = mNetTrackers[networkType];
849 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700850 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700851 }
852 }
853 return info;
854 }
855
856 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800857 public NetworkInfo[] getAllNetworkInfo() {
858 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700859 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700860 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700861 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700862 for (NetworkStateTracker tracker : mNetTrackers) {
863 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700864 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700865 }
866 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800867 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700868 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 }
870
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700871 @Override
872 public boolean isNetworkSupported(int networkType) {
873 enforceAccessPermission();
874 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
875 }
876
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700877 /**
878 * Return LinkProperties for the active (i.e., connected) default
879 * network interface. It is assumed that at most one default network
880 * is active at a time. If more than one is active, it is indeterminate
881 * which will be returned.
882 * @return the ip properties for the active network, or {@code null} if
883 * none is active
884 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700885 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700886 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700887 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700888 }
889
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700890 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700891 public LinkProperties getLinkProperties(int networkType) {
892 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700893 if (isNetworkTypeValid(networkType)) {
894 final NetworkStateTracker tracker = mNetTrackers[networkType];
895 if (tracker != null) {
896 return tracker.getLinkProperties();
897 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700898 }
899 return null;
900 }
901
Jeff Sharkey21062e72011-05-28 20:56:34 -0700902 @Override
903 public NetworkState[] getAllNetworkState() {
904 enforceAccessPermission();
905 final int uid = Binder.getCallingUid();
906 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700907 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700908 for (NetworkStateTracker tracker : mNetTrackers) {
909 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700910 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700911 result.add(new NetworkState(
912 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
913 }
914 }
915 }
916 return result.toArray(new NetworkState[result.size()]);
917 }
918
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700919 private NetworkState getNetworkStateUnchecked(int networkType) {
920 if (isNetworkTypeValid(networkType)) {
921 final NetworkStateTracker tracker = mNetTrackers[networkType];
922 if (tracker != null) {
923 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
924 tracker.getLinkCapabilities());
925 }
926 }
927 return null;
928 }
929
930 @Override
931 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
932 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700933
934 final long token = Binder.clearCallingIdentity();
935 try {
936 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
937 if (state != null) {
938 try {
939 return mPolicyManager.getNetworkQuotaInfo(state);
940 } catch (RemoteException e) {
941 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700942 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700943 return null;
944 } finally {
945 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700946 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700947 }
948
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700949 @Override
950 public boolean isActiveNetworkMetered() {
951 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700952 final long token = Binder.clearCallingIdentity();
953 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700954 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700955 } finally {
956 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700957 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700958 }
959
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700960 private boolean isNetworkMeteredUnchecked(int networkType) {
961 final NetworkState state = getNetworkStateUnchecked(networkType);
962 if (state != null) {
963 try {
964 return mPolicyManager.isNetworkMetered(state);
965 } catch (RemoteException e) {
966 }
967 }
968 return false;
969 }
970
The Android Open Source Project28527d22009-03-03 19:31:44 -0800971 public boolean setRadios(boolean turnOn) {
972 boolean result = true;
973 enforceChangePermission();
974 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700975 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800976 }
977 return result;
978 }
979
980 public boolean setRadio(int netType, boolean turnOn) {
981 enforceChangePermission();
982 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
983 return false;
984 }
985 NetworkStateTracker tracker = mNetTrackers[netType];
986 return tracker != null && tracker.setRadio(turnOn);
987 }
988
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700989 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
990 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -0700991 public void interfaceClassDataActivityChanged(String label, boolean active) {
992 int deviceType = Integer.parseInt(label);
993 sendDataActivityBroadcast(deviceType, active);
994 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700995 };
Haoyu Baib5da5752012-06-20 14:29:57 -0700996
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700997 /**
998 * Used to notice when the calling process dies so we can self-expire
999 *
1000 * Also used to know if the process has cleaned up after itself when
1001 * our auto-expire timer goes off. The timer has a link to an object.
1002 *
1003 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001004 private class FeatureUser implements IBinder.DeathRecipient {
1005 int mNetworkType;
1006 String mFeature;
1007 IBinder mBinder;
1008 int mPid;
1009 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001010 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001011
1012 FeatureUser(int type, String feature, IBinder binder) {
1013 super();
1014 mNetworkType = type;
1015 mFeature = feature;
1016 mBinder = binder;
1017 mPid = getCallingPid();
1018 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001019 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001020
Robert Greenwalt2034b912009-08-12 16:08:25 -07001021 try {
1022 mBinder.linkToDeath(this, 0);
1023 } catch (RemoteException e) {
1024 binderDied();
1025 }
1026 }
1027
1028 void unlinkDeathRecipient() {
1029 mBinder.unlinkToDeath(this, 0);
1030 }
1031
1032 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001033 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001034 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1035 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001036 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001037 }
1038
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001039 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001040 if (VDBG) {
1041 log("ConnectivityService FeatureUser expire(" +
1042 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1043 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1044 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001045 stopUsingNetworkFeature(this, false);
1046 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001047
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001048 public boolean isSameUser(FeatureUser u) {
1049 if (u == null) return false;
1050
1051 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1052 }
1053
1054 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1055 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1056 TextUtils.equals(mFeature, feature)) {
1057 return true;
1058 }
1059 return false;
1060 }
1061
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001062 public String toString() {
1063 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1064 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1065 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001066 }
1067
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001068 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001069 public int startUsingNetworkFeature(int networkType, String feature,
1070 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001071 long startTime = 0;
1072 if (DBG) {
1073 startTime = SystemClock.elapsedRealtime();
1074 }
Wink Savillea7d56572011-09-21 11:05:43 -07001075 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001076 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1077 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001078 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001079 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001080 try {
1081 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1082 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001083 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001084 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001085
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001086 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001087
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001088 // TODO - move this into individual networktrackers
1089 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001090
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001091 if (mLockdownEnabled) {
1092 // Since carrier APNs usually aren't available from VPN
1093 // endpoint, mark them as unavailable.
1094 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1095 }
1096
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001097 if (mProtectedNetworks.contains(usedNetworkType)) {
1098 enforceConnectivityInternalPermission();
1099 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001100
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001101 // if UID is restricted, don't allow them to bring up metered APNs
1102 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1103 final int uidRules;
1104 synchronized (mRulesLock) {
1105 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1106 }
1107 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001108 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001109 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001110
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001111 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1112 if (network != null) {
1113 Integer currentPid = new Integer(getCallingPid());
1114 if (usedNetworkType != networkType) {
1115 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001116
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001117 if (ni.isAvailable() == false) {
1118 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1119 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001120 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001121 } else {
1122 // else make the attempt anyway - probably giving REQUEST_STARTED below
1123 if (DBG) {
1124 log("special network not available, but try anyway ni=" +
1125 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001126 }
1127 }
1128 }
1129
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001130 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001131
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001132 synchronized(this) {
1133 boolean addToList = true;
1134 if (restoreTimer < 0) {
1135 // In case there is no timer is specified for the feature,
1136 // make sure we don't add duplicate entry with the same request.
1137 for (FeatureUser u : mFeatureUsers) {
1138 if (u.isSameUser(f)) {
1139 // Duplicate user is found. Do not add.
1140 addToList = false;
1141 break;
1142 }
1143 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001144 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001145
1146 if (addToList) mFeatureUsers.add(f);
1147 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1148 // this gets used for per-pid dns when connected
1149 mNetRequestersPids[usedNetworkType].add(currentPid);
1150 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001151 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001152
1153 if (restoreTimer >= 0) {
1154 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1155 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1156 }
1157
1158 if ((ni.isConnectedOrConnecting() == true) &&
1159 !network.isTeardownRequested()) {
1160 if (ni.isConnected() == true) {
1161 final long token = Binder.clearCallingIdentity();
1162 try {
1163 // add the pid-specific dns
1164 handleDnsConfigurationChange(usedNetworkType);
1165 if (VDBG) log("special network already active");
1166 } finally {
1167 Binder.restoreCallingIdentity(token);
1168 }
Wink Saville64e3f782012-07-10 12:37:54 -07001169 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001170 }
1171 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001172 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001173 }
1174
1175 // check if the radio in play can make another contact
1176 // assume if cannot for now
1177
1178 if (DBG) {
1179 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1180 feature);
1181 }
1182 network.reconnect();
Wink Saville64e3f782012-07-10 12:37:54 -07001183 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001184 } else {
1185 // need to remember this unsupported request so we respond appropriately on stop
1186 synchronized(this) {
1187 mFeatureUsers.add(f);
1188 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1189 // this gets used for per-pid dns when connected
1190 mNetRequestersPids[usedNetworkType].add(currentPid);
1191 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001192 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001193 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001194 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195 }
Wink Saville64e3f782012-07-10 12:37:54 -07001196 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001197 } finally {
1198 if (DBG) {
1199 final long execTime = SystemClock.elapsedRealtime() - startTime;
1200 if (execTime > 250) {
1201 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1202 } else {
1203 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1204 }
1205 }
1206 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001207 }
1208
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001209 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001210 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001211 enforceChangePermission();
1212
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001213 int pid = getCallingPid();
1214 int uid = getCallingUid();
1215
1216 FeatureUser u = null;
1217 boolean found = false;
1218
1219 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001220 for (FeatureUser x : mFeatureUsers) {
1221 if (x.isSameUser(pid, uid, networkType, feature)) {
1222 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001223 found = true;
1224 break;
1225 }
1226 }
1227 }
1228 if (found && u != null) {
1229 // stop regardless of how many other time this proc had called start
1230 return stopUsingNetworkFeature(u, true);
1231 } else {
1232 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001233 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001234 return 1;
1235 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001236 }
1237
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001238 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1239 int networkType = u.mNetworkType;
1240 String feature = u.mFeature;
1241 int pid = u.mPid;
1242 int uid = u.mUid;
1243
1244 NetworkStateTracker tracker = null;
1245 boolean callTeardown = false; // used to carry our decision outside of sync block
1246
Wink Savillea7d56572011-09-21 11:05:43 -07001247 if (VDBG) {
1248 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001249 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001250
The Android Open Source Project28527d22009-03-03 19:31:44 -08001251 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001252 if (DBG) {
1253 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1254 ", net is invalid");
1255 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001256 return -1;
1257 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001258
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001259 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1260 // sync block
1261 synchronized(this) {
1262 // check if this process still has an outstanding start request
1263 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001264 if (VDBG) {
1265 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1266 ", ignoring");
1267 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001268 return 1;
1269 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001270 u.unlinkDeathRecipient();
1271 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1272 // If we care about duplicate requests, check for that here.
1273 //
1274 // This is done to support the extension of a request - the app
1275 // can request we start the network feature again and renew the
1276 // auto-shutoff delay. Normal "stop" calls from the app though
1277 // do not pay attention to duplicate requests - in effect the
1278 // API does not refcount and a single stop will counter multiple starts.
1279 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001280 for (FeatureUser x : mFeatureUsers) {
1281 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001282 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001283 return 1;
1284 }
1285 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001286 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001287
repo syncf5de5572011-07-29 23:55:49 -07001288 // TODO - move to individual network trackers
1289 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1290
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001291 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001292 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001293 if (DBG) {
1294 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1295 " no known tracker for used net type " + usedNetworkType);
1296 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001297 return -1;
1298 }
1299 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001300 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001301 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001302 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001303 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001304 if (VDBG) {
1305 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1306 " others still using it");
1307 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001308 return 1;
1309 }
1310 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001311 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001312 if (DBG) {
1313 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1314 " not a known feature - dropping");
1315 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001316 }
1317 }
Wink Savillea7d56572011-09-21 11:05:43 -07001318
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001319 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001320 if (DBG) {
1321 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1322 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001323 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001324 return 1;
1325 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001326 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001327 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001328 }
1329
1330 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001331 * @deprecated use requestRouteToHostAddress instead
1332 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001333 * Ensure that a network route exists to deliver traffic to the specified
1334 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001335 * @param networkType the type of the network over which traffic to the
1336 * specified host is to be routed
1337 * @param hostAddress the IP address of the host to which the route is
1338 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001339 * @return {@code true} on success, {@code false} on failure
1340 */
1341 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001342 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1343
1344 if (inetAddress == null) {
1345 return false;
1346 }
1347
1348 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1349 }
1350
1351 /**
1352 * Ensure that a network route exists to deliver traffic to the specified
1353 * host via the specified network interface.
1354 * @param networkType the type of the network over which traffic to the
1355 * specified host is to be routed
1356 * @param hostAddress the IP address of the host to which the route is
1357 * desired
1358 * @return {@code true} on success, {@code false} on failure
1359 */
1360 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001361 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001362 if (mProtectedNetworks.contains(networkType)) {
1363 enforceConnectivityInternalPermission();
1364 }
1365
The Android Open Source Project28527d22009-03-03 19:31:44 -08001366 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001367 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001368 return false;
1369 }
1370 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001371 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001372
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001373 if (tracker == null || (netState != DetailedState.CONNECTED &&
1374 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001375 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001376 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001377 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001378 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001379 }
1380 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001381 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001382 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001383 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001384 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001385 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001386 return addRouteToAddress(lp, addr);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001387 } catch (UnknownHostException e) {
1388 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1389 } finally {
1390 Binder.restoreCallingIdentity(token);
1391 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001392 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001393 }
1394
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001395 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1396 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001397 }
1398
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001399 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1400 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001401 }
1402
Robert Greenwalt98107422011-07-22 11:55:33 -07001403 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001404 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001405 }
1406
1407 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001408 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001409 }
1410
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001411 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1412 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001413 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1414 if (bestRoute == null) {
1415 bestRoute = RouteInfo.makeHostRoute(addr);
1416 } else {
1417 if (bestRoute.getGateway().equals(addr)) {
1418 // if there is no better route, add the implied hostroute for our gateway
1419 bestRoute = RouteInfo.makeHostRoute(addr);
1420 } else {
1421 // if we will connect to this through another route, add a direct route
1422 // to it's gateway
1423 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1424 }
1425 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001426 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001427 }
1428
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001429 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001430 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001431 if ((ifaceName == null) || (lp == null) || (r == null)) {
1432 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1433 return false;
1434 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001435
1436 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001437 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001438 return false;
1439 }
1440
1441 if (r.isHostRoute() == false) {
1442 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1443 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001444 if (bestRoute.getGateway().equals(r.getGateway())) {
1445 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001446 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001447 } else {
1448 // if we will connect to our gateway through another route, add a direct
1449 // route to it's gateway
1450 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001451 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001452 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001453 }
1454 }
1455 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001456 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001457 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001458 if (toDefaultTable) {
1459 mAddedRoutes.add(r); // only track default table - only one apps can effect
1460 mNetd.addRoute(ifaceName, r);
1461 } else {
1462 mNetd.addSecondaryRoute(ifaceName, r);
1463 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001464 } catch (Exception e) {
1465 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001466 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001467 return false;
1468 }
1469 } else {
1470 // if we remove this one and there are no more like it, then refcount==0 and
1471 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001472 if (toDefaultTable) {
1473 mAddedRoutes.remove(r);
1474 if (mAddedRoutes.contains(r) == false) {
1475 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1476 try {
1477 mNetd.removeRoute(ifaceName, r);
1478 } catch (Exception e) {
1479 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001480 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001481 return false;
1482 }
1483 } else {
1484 if (VDBG) log("not removing " + r + " as it's still in use");
1485 }
1486 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001487 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001488 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001489 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001490 } catch (Exception e) {
1491 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001492 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001493 return false;
1494 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001495 }
1496 }
1497 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001498 }
1499
1500 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001501 * @see ConnectivityManager#getMobileDataEnabled()
1502 */
1503 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001504 // TODO: This detail should probably be in DataConnectionTracker's
1505 // which is where we store the value and maybe make this
1506 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001507 enforceAccessPermission();
1508 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1509 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001510 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001511 return retVal;
1512 }
1513
Robert Greenwalt34848c02011-03-25 13:09:25 -07001514 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001515 enforceConnectivityInternalPermission();
1516
Robert Greenwalt34848c02011-03-25 13:09:25 -07001517 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1518 (met ? ENABLED : DISABLED), networkType));
1519 }
1520
1521 private void handleSetDependencyMet(int networkType, boolean met) {
1522 if (mNetTrackers[networkType] != null) {
1523 if (DBG) {
1524 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1525 }
1526 mNetTrackers[networkType].setDependencyMet(met);
1527 }
1528 }
1529
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001530 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1531 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001532 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001533 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001534 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001535 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001536 }
1537
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001538 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001539 // skip update when we've already applied rules
1540 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1541 if (oldRules == uidRules) return;
1542
1543 mUidRules.put(uid, uidRules);
1544 }
1545
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001546 // TODO: notify UID when it has requested targeted updates
1547 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001548
1549 @Override
1550 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001551 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001552 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001553 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001554 }
1555
1556 synchronized (mRulesLock) {
1557 mMeteredIfaces.clear();
1558 for (String iface : meteredIfaces) {
1559 mMeteredIfaces.add(iface);
1560 }
1561 }
1562 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001563
1564 @Override
1565 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1566 // caller is NPMS, since we only register with them
1567 if (LOGD_RULES) {
1568 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1569 }
1570
1571 // kick off connectivity change broadcast for active network, since
1572 // global background policy change is radical.
1573 final int networkType = mActiveDefaultNetwork;
1574 if (isNetworkTypeValid(networkType)) {
1575 final NetworkStateTracker tracker = mNetTrackers[networkType];
1576 if (tracker != null) {
1577 final NetworkInfo info = tracker.getNetworkInfo();
1578 if (info != null && info.isConnected()) {
1579 sendConnectedBroadcast(info);
1580 }
1581 }
1582 }
1583 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001584 };
1585
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001586 /**
1587 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1588 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001589 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001590 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001591 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001592
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001593 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001594 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001595 }
1596
1597 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001598 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001599 if (VDBG) {
1600 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001601 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001602 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1603 }
tk.mun5eee1042012-01-06 10:43:52 +09001604 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1605 if (VDBG) {
1606 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1607 }
1608 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1609 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001610 }
1611
1612 @Override
1613 public void setPolicyDataEnable(int networkType, boolean enabled) {
1614 // only someone like NPMS should only be calling us
1615 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1616
1617 mHandler.sendMessage(mHandler.obtainMessage(
1618 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1619 }
1620
1621 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1622 if (isNetworkTypeValid(networkType)) {
1623 final NetworkStateTracker tracker = mNetTrackers[networkType];
1624 if (tracker != null) {
1625 tracker.setPolicyDataEnable(enabled);
1626 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001627 }
1628 }
1629
The Android Open Source Project28527d22009-03-03 19:31:44 -08001630 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001631 mContext.enforceCallingOrSelfPermission(
1632 android.Manifest.permission.ACCESS_NETWORK_STATE,
1633 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001634 }
1635
1636 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001637 mContext.enforceCallingOrSelfPermission(
1638 android.Manifest.permission.CHANGE_NETWORK_STATE,
1639 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001640 }
1641
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001642 // TODO Make this a special check when it goes public
1643 private void enforceTetherChangePermission() {
1644 mContext.enforceCallingOrSelfPermission(
1645 android.Manifest.permission.CHANGE_NETWORK_STATE,
1646 "ConnectivityService");
1647 }
1648
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001649 private void enforceTetherAccessPermission() {
1650 mContext.enforceCallingOrSelfPermission(
1651 android.Manifest.permission.ACCESS_NETWORK_STATE,
1652 "ConnectivityService");
1653 }
1654
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001655 private void enforceConnectivityInternalPermission() {
1656 mContext.enforceCallingOrSelfPermission(
1657 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1658 "ConnectivityService");
1659 }
1660
The Android Open Source Project28527d22009-03-03 19:31:44 -08001661 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001662 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1663 * network, we ignore it. If it is for the active network, we send out a
1664 * broadcast. But first, we check whether it might be possible to connect
1665 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001666 * @param info the {@code NetworkInfo} for the network
1667 */
1668 private void handleDisconnect(NetworkInfo info) {
1669
Robert Greenwalt2034b912009-08-12 16:08:25 -07001670 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001671
Robert Greenwalt2034b912009-08-12 16:08:25 -07001672 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001673
1674 // Remove idletimer previously setup in {@code handleConnect}
1675 removeDataActivityTracking(prevNetType);
1676
The Android Open Source Project28527d22009-03-03 19:31:44 -08001677 /*
1678 * If the disconnected network is not the active one, then don't report
1679 * this as a loss of connectivity. What probably happened is that we're
1680 * getting the disconnect for a network that we explicitly disabled
1681 * in accordance with network preference policies.
1682 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001683 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001684 List pids = mNetRequestersPids[prevNetType];
1685 for (int i = 0; i<pids.size(); i++) {
1686 Integer pid = (Integer)pids.get(i);
1687 // will remove them because the net's no longer connected
1688 // need to do this now as only now do we know the pids and
1689 // can properly null things that are no longer referenced.
1690 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001691 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001692 }
1693
The Android Open Source Project28527d22009-03-03 19:31:44 -08001694 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1695 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
Jeff Sharkey47905d12012-08-06 11:41:50 -07001696 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001697 if (info.isFailover()) {
1698 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1699 info.setFailover(false);
1700 }
1701 if (info.getReason() != null) {
1702 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1703 }
1704 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001705 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1706 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001707 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001708
Robert Greenwalt34848c02011-03-25 13:09:25 -07001709 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001710 tryFailover(prevNetType);
1711 if (mActiveDefaultNetwork != -1) {
1712 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001713 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1714 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001715 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001716 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1717 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001718 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001719 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001720
1721 // Reset interface if no other connections are using the same interface
1722 boolean doReset = true;
1723 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1724 if (linkProperties != null) {
1725 String oldIface = linkProperties.getInterfaceName();
1726 if (TextUtils.isEmpty(oldIface) == false) {
1727 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1728 if (networkStateTracker == null) continue;
1729 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1730 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1731 LinkProperties l = networkStateTracker.getLinkProperties();
1732 if (l == null) continue;
1733 if (oldIface.equals(l.getInterfaceName())) {
1734 doReset = false;
1735 break;
1736 }
1737 }
1738 }
1739 }
1740 }
1741
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001742 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001743 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001744
Jeff Sharkey971cd162011-08-29 16:02:57 -07001745 final Intent immediateIntent = new Intent(intent);
1746 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1747 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001748 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001749 /*
1750 * If the failover network is already connected, then immediately send
1751 * out a followup broadcast indicating successful failover
1752 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001753 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001754 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1755 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001756 }
1757 }
1758
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001759 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001760 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001761 * If this is a default network, check if other defaults are available.
1762 * Try to reconnect on all available and let them hash it out when
1763 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001764 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001765 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001766 if (mActiveDefaultNetwork == prevNetType) {
1767 mActiveDefaultNetwork = -1;
1768 }
1769
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001770 // don't signal a reconnect for anything lower or equal priority than our
1771 // current connected default
1772 // TODO - don't filter by priority now - nice optimization but risky
1773// int currentPriority = -1;
1774// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001775// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001776// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001777 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001778 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001779 if (mNetConfigs[checkType] == null) continue;
1780 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001781 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001782
1783// Enabling the isAvailable() optimization caused mobile to not get
1784// selected if it was in the middle of error handling. Specifically
1785// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1786// would not be available and we wouldn't get connected to anything.
1787// So removing the isAvailable() optimization below for now. TODO: This
1788// optimization should work and we need to investigate why it doesn't work.
1789// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1790// complete before it is really complete.
1791// if (!mNetTrackers[checkType].isAvailable()) continue;
1792
Robert Greenwalt34848c02011-03-25 13:09:25 -07001793// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001794
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001795 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1796 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1797 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1798 checkInfo.setFailover(true);
1799 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001800 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001801 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001802 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001803 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001804 }
1805
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001806 public void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001807 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1808 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001809 }
1810
Wink Saville4f0de1e2011-08-04 15:01:58 -07001811 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001812 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1813 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001814 }
1815
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001816 private void sendInetConditionBroadcast(NetworkInfo info) {
1817 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1818 }
1819
Wink Saville4f0de1e2011-08-04 15:01:58 -07001820 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001821 if (mLockdownTracker != null) {
1822 info = mLockdownTracker.augmentNetworkInfo(info);
1823 }
1824
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001825 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001826 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
Jeff Sharkey47905d12012-08-06 11:41:50 -07001827 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001828 if (info.isFailover()) {
1829 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1830 info.setFailover(false);
1831 }
1832 if (info.getReason() != null) {
1833 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1834 }
1835 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001836 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1837 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001838 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001839 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001840 return intent;
1841 }
1842
1843 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1844 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1845 }
1846
1847 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1848 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001849 }
1850
Haoyu Baib5da5752012-06-20 14:29:57 -07001851 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1852 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1853 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1854 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001855 final long ident = Binder.clearCallingIdentity();
1856 try {
1857 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1858 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1859 } finally {
1860 Binder.restoreCallingIdentity(ident);
1861 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001862 }
1863
The Android Open Source Project28527d22009-03-03 19:31:44 -08001864 /**
1865 * Called when an attempt to fail over to another network has failed.
1866 * @param info the {@link NetworkInfo} for the failed network
1867 */
1868 private void handleConnectionFailure(NetworkInfo info) {
1869 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001870
Robert Greenwalt2034b912009-08-12 16:08:25 -07001871 String reason = info.getReason();
1872 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001873
Robert Greenwalte981bc52010-10-08 16:35:52 -07001874 String reasonText;
1875 if (reason == null) {
1876 reasonText = ".";
1877 } else {
1878 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001879 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001880 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001881
1882 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1883 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
Jeff Sharkey47905d12012-08-06 11:41:50 -07001884 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001885 if (getActiveNetworkInfo() == null) {
1886 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1887 }
1888 if (reason != null) {
1889 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1890 }
1891 if (extraInfo != null) {
1892 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1893 }
1894 if (info.isFailover()) {
1895 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1896 info.setFailover(false);
1897 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001898
Robert Greenwalt34848c02011-03-25 13:09:25 -07001899 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001900 tryFailover(info.getType());
1901 if (mActiveDefaultNetwork != -1) {
1902 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001903 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1904 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001905 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001906 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1907 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001908 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001909
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001910 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001911
1912 final Intent immediateIntent = new Intent(intent);
1913 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1914 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001915 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001916 /*
1917 * If the failover network is already connected, then immediately send
1918 * out a followup broadcast indicating successful failover
1919 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001920 if (mActiveDefaultNetwork != -1) {
1921 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001922 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001923 }
1924
1925 private void sendStickyBroadcast(Intent intent) {
1926 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001927 if (!mSystemReady) {
1928 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001929 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001930 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001931 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001932 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001933 }
1934
Dianne Hackborne588ca12012-09-04 18:48:37 -07001935 final long ident = Binder.clearCallingIdentity();
1936 try {
1937 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1938 } finally {
1939 Binder.restoreCallingIdentity(ident);
1940 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001941 }
1942 }
1943
Wink Saville4f0de1e2011-08-04 15:01:58 -07001944 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1945 if (delayMs <= 0) {
1946 sendStickyBroadcast(intent);
1947 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001948 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001949 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1950 + intent.getAction());
1951 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001952 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1953 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1954 }
1955 }
1956
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001957 void systemReady() {
1958 synchronized(this) {
1959 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001960 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07001961 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08001962 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001963 }
1964 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001965 // load the global proxy at startup
1966 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001967
1968 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1969 // for user to unlock device.
1970 if (!updateLockdownVpn()) {
1971 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1972 mContext.registerReceiver(mUserPresentReceiver, filter);
1973 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001974 }
1975
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001976 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1977 @Override
1978 public void onReceive(Context context, Intent intent) {
1979 // Try creating lockdown tracker, since user present usually means
1980 // unlocked keystore.
1981 if (updateLockdownVpn()) {
1982 mContext.unregisterReceiver(this);
1983 }
1984 }
1985 };
1986
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001987 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
1988 if ((type != mNetworkPreference &&
1989 mNetConfigs[mActiveDefaultNetwork].priority >
1990 mNetConfigs[type].priority) ||
1991 mNetworkPreference == mActiveDefaultNetwork) return false;
1992 return true;
1993 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001994
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001995 private void handleConnect(NetworkInfo info) {
1996 final int newNetType = info.getType();
1997
1998 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07001999
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 // snapshot isFailover, because sendConnectedBroadcast() resets it
2001 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002002 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002003 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002004
Robert Greenwalt2034b912009-08-12 16:08:25 -07002005 // if this is a default net and other default is running
2006 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002007 if (mNetConfigs[newNetType].isDefault()) {
2008 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2009 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002010 // tear down the other
2011 NetworkStateTracker otherNet =
2012 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002013 if (DBG) {
2014 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002015 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002016 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002017 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002018 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002019 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002020 return;
2021 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002022 } else {
2023 // don't accept this one
2024 if (VDBG) {
2025 log("Not broadcasting CONNECT_ACTION " +
2026 "to torn down network " + info.getTypeName());
2027 }
2028 teardown(thisNet);
2029 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002030 }
2031 }
2032 synchronized (ConnectivityService.this) {
2033 // have a new default network, release the transition wakelock in a second
2034 // if it's held. The second pause is to allow apps to reconnect over the
2035 // new network
2036 if (mNetTransitionWakeLock.isHeld()) {
2037 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002038 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002039 mNetTransitionWakeLockSerialNumber, 0),
2040 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002041 }
2042 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002043 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002044 // this will cause us to come up initially as unconnected and switching
2045 // to connected after our normal pause unless somebody reports us as reall
2046 // disconnected
2047 mDefaultInetConditionPublished = 0;
2048 mDefaultConnectionSequence++;
2049 mInetConditionChangeInFlight = false;
2050 // Don't do this - if we never sign in stay, grey
2051 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002052 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002053 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002054 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002055 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002056 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002057
2058 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002059 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002060 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002061 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002062 } catch (RemoteException e) {
2063 // ignored; service lives in system_server
2064 }
2065 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002066 }
2067
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002068 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2069 if (DBG) log("Captive portal check " + info);
2070 int type = info.getType();
2071 final NetworkStateTracker thisNet = mNetTrackers[type];
2072 if (mNetConfigs[type].isDefault()) {
2073 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2074 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2075 if (DBG) log("Captive check on " + info.getTypeName());
2076 mCaptivePortalTracker = CaptivePortalTracker.detect(mContext, info,
2077 ConnectivityService.this);
2078 return;
2079 } else {
2080 if (DBG) log("Tear down low priority net " + info.getTypeName());
2081 teardown(thisNet);
2082 return;
2083 }
2084 }
2085 }
2086
2087 thisNet.captivePortalCheckComplete();
2088 }
2089
2090 /** @hide */
2091 public void captivePortalCheckComplete(NetworkInfo info) {
2092 mNetTrackers[info.getType()].captivePortalCheckComplete();
2093 mCaptivePortalTracker = null;
2094 }
2095
The Android Open Source Project28527d22009-03-03 19:31:44 -08002096 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002097 * Setup data activity tracking for the given network interface.
2098 *
2099 * Every {@code setupDataActivityTracking} should be paired with a
2100 * {@link removeDataActivityTracking} for cleanup.
2101 */
2102 private void setupDataActivityTracking(int type) {
2103 final NetworkStateTracker thisNet = mNetTrackers[type];
2104 final String iface = thisNet.getLinkProperties().getInterfaceName();
2105
2106 final int timeout;
2107
2108 if (ConnectivityManager.isNetworkTypeMobile(type)) {
2109 timeout = Settings.Secure.getInt(mContext.getContentResolver(),
2110 Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE,
2111 0);
2112 // Canonicalize mobile network type
2113 type = ConnectivityManager.TYPE_MOBILE;
2114 } else if (ConnectivityManager.TYPE_WIFI == type) {
2115 timeout = Settings.Secure.getInt(mContext.getContentResolver(),
2116 Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI,
2117 0);
2118 } else {
2119 // do not track any other networks
2120 timeout = 0;
2121 }
2122
2123 if (timeout > 0 && iface != null) {
2124 try {
2125 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2126 } catch (RemoteException e) {
2127 }
2128 }
2129 }
2130
2131 /**
2132 * Remove data activity tracking when network disconnects.
2133 */
2134 private void removeDataActivityTracking(int type) {
2135 final NetworkStateTracker net = mNetTrackers[type];
2136 final String iface = net.getLinkProperties().getInterfaceName();
2137
2138 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2139 ConnectivityManager.TYPE_WIFI == type)) {
2140 try {
2141 // the call fails silently if no idletimer setup for this interface
2142 mNetd.removeIdleTimer(iface);
2143 } catch (RemoteException e) {
2144 }
2145 }
2146 }
2147
2148 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002149 * After a change in the connectivity state of a network. We're mainly
2150 * concerned with making sure that the list of DNS servers is set up
2151 * according to which networks are connected, and ensuring that the
2152 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002153 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002154 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002155 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2156
The Android Open Source Project28527d22009-03-03 19:31:44 -08002157 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002158 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002159 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002160 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002161 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002162
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002163 LinkProperties curLp = mCurrentLinkProperties[netType];
2164 LinkProperties newLp = null;
2165
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002166 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002167 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002168 if (VDBG) {
2169 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2170 " doReset=" + doReset + " resetMask=" + resetMask +
2171 "\n curLp=" + curLp +
2172 "\n newLp=" + newLp);
2173 }
2174
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002175 if (curLp != null) {
2176 if (curLp.isIdenticalInterfaceName(newLp)) {
2177 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2178 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2179 for (LinkAddress linkAddr : car.removed) {
2180 if (linkAddr.getAddress() instanceof Inet4Address) {
2181 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2182 }
2183 if (linkAddr.getAddress() instanceof Inet6Address) {
2184 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2185 }
Wink Saville051a6642011-07-13 13:44:13 -07002186 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002187 if (DBG) {
2188 log("handleConnectivityChange: addresses changed" +
2189 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2190 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002191 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002192 } else {
2193 if (DBG) {
2194 log("handleConnectivityChange: address are the same reset per doReset" +
2195 " linkProperty[" + netType + "]:" +
2196 " resetMask=" + resetMask);
2197 }
Wink Saville051a6642011-07-13 13:44:13 -07002198 }
2199 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002200 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002201 if (DBG) {
2202 log("handleConnectivityChange: interface not not equivalent reset both" +
2203 " linkProperty[" + netType + "]:" +
2204 " resetMask=" + resetMask);
2205 }
Wink Saville051a6642011-07-13 13:44:13 -07002206 }
Wink Saville051a6642011-07-13 13:44:13 -07002207 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002208 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002209 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002210 }
2211 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002212 if (VDBG) {
2213 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2214 " doReset=" + doReset + " resetMask=" + resetMask +
2215 "\n curLp=" + curLp +
2216 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002217 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002218 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002219 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002220 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002221
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002222 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002223 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2224 if (linkProperties != null) {
2225 String iface = linkProperties.getInterfaceName();
2226 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002227 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07002228 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2229 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002230
2231 // Tell VPN the interface is down. It is a temporary
2232 // but effective fix to make VPN aware of the change.
2233 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2234 mVpn.interfaceStatusChanged(iface, false);
2235 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002236 }
2237 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07002238 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002239 try {
2240 mNetd.flushInterfaceDnsCache(iface);
2241 } catch (Exception e) {
2242 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07002243 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002244 }
2245 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002246 }
2247 }
2248 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002249
2250 // TODO: Temporary notifying upstread change to Tethering.
2251 // @see bug/4455071
2252 /** Notify TetheringService if interface name has been changed. */
2253 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002254 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002255 if (isTetheringSupported()) {
2256 mTethering.handleTetherIfaceChange();
2257 }
2258 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 }
2260
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002261 /**
2262 * Add and remove routes using the old properties (null if not previously connected),
2263 * new properties (null if becoming disconnected). May even be double null, which
2264 * is a noop.
2265 * Uses isLinkDefault to determine if default routes should be set or conversely if
2266 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002267 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002268 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002269 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2270 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002271 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002272 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2273 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002274 if (curLp != null) {
2275 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002276 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002277 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002278 } else if (newLp != null) {
2279 routeDiff.added = newLp.getRoutes();
2280 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002281 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002282
Robert Greenwalt8d777252011-08-15 12:31:55 -07002283 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2284
Robert Greenwalt98107422011-07-22 11:55:33 -07002285 for (RouteInfo r : routeDiff.removed) {
2286 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002287 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2288 }
2289 if (isLinkDefault == false) {
2290 // remove from a secondary route table
2291 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002292 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002293 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002294
Robert Greenwalt98107422011-07-22 11:55:33 -07002295 for (RouteInfo r : routeDiff.added) {
2296 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002297 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002298 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002299 // add to a secondary route table
2300 addRoute(newLp, r, TO_SECONDARY_TABLE);
2301
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002302 // many radios add a default route even when we don't want one.
2303 // remove the default route unless somebody else has asked for it
2304 String ifaceName = newLp.getInterfaceName();
2305 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002306 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002307 try {
2308 mNetd.removeRoute(ifaceName, r);
2309 } catch (Exception e) {
2310 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002311 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002312 }
2313 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002314 }
2315 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002316
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002317 if (!isLinkDefault) {
2318 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002319 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002320 // routes changed - remove all old dns entries and add new
2321 if (curLp != null) {
2322 for (InetAddress oldDns : curLp.getDnses()) {
2323 removeRouteToAddress(curLp, oldDns);
2324 }
2325 }
2326 if (newLp != null) {
2327 for (InetAddress newDns : newLp.getDnses()) {
2328 addRouteToAddress(newLp, newDns);
2329 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002330 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002331 } else {
2332 // no change in routes, check for change in dns themselves
2333 for (InetAddress oldDns : dnsDiff.removed) {
2334 removeRouteToAddress(curLp, oldDns);
2335 }
2336 for (InetAddress newDns : dnsDiff.added) {
2337 addRouteToAddress(newLp, newDns);
2338 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002339 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002340 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002341 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002342 }
2343
2344
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002345 /**
2346 * Reads the network specific TCP buffer sizes from SystemProperties
2347 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2348 * wide use
2349 */
2350 public void updateNetworkSettings(NetworkStateTracker nt) {
2351 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002352 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002353
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002354 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002355 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002356
2357 // Setting to default values so we won't be stuck to previous values
2358 key = "net.tcp.buffersize.default";
2359 bufferSizes = SystemProperties.get(key);
2360 }
2361
2362 // Set values in kernel
2363 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002364 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002365 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002366 + "] which comes from [" + key + "]");
2367 }
2368 setBufferSize(bufferSizes);
2369 }
2370 }
2371
2372 /**
2373 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2374 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2375 *
2376 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2377 * writeMin, writeInitial, writeMax"
2378 */
2379 private void setBufferSize(String bufferSizes) {
2380 try {
2381 String[] values = bufferSizes.split(",");
2382
2383 if (values.length == 6) {
2384 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002385 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2386 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2387 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2388 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2389 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2390 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002391 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002392 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002393 }
2394 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002395 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002396 }
2397 }
2398
Robert Greenwalt2034b912009-08-12 16:08:25 -07002399 /**
2400 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2401 * on the highest priority active net which this process requested.
2402 * If there aren't any, clear it out
2403 */
2404 private void reassessPidDns(int myPid, boolean doBump)
2405 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002406 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002407 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002408 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002409 continue;
2410 }
2411 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002412 if (nt.getNetworkInfo().isConnected() &&
2413 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002414 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002415 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002416 List pids = mNetRequestersPids[i];
2417 for (int j=0; j<pids.size(); j++) {
2418 Integer pid = (Integer)pids.get(j);
2419 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002420 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002421 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002422 if (doBump) {
2423 bumpDns();
2424 }
2425 return;
2426 }
2427 }
2428 }
2429 }
2430 // nothing found - delete
2431 for (int i = 1; ; i++) {
2432 String prop = "net.dns" + i + "." + myPid;
2433 if (SystemProperties.get(prop).length() == 0) {
2434 if (doBump) {
2435 bumpDns();
2436 }
2437 return;
2438 }
2439 SystemProperties.set(prop, "");
2440 }
2441 }
2442
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002443 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002444 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002445 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002446 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002447 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002448 String dnsString = dns.getHostAddress();
2449 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2450 changed = true;
yoonsung.nam48d18332012-03-02 19:56:16 +09002451 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002452 }
yoonsung.nam48d18332012-03-02 19:56:16 +09002453 j++;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002454 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002455 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002456 }
2457
2458 private void bumpDns() {
2459 /*
2460 * Bump the property that tells the name resolver library to reread
2461 * the DNS server list from the properties.
2462 */
2463 String propVal = SystemProperties.get("net.dnschange");
2464 int n = 0;
2465 if (propVal.length() != 0) {
2466 try {
2467 n = Integer.parseInt(propVal);
2468 } catch (NumberFormatException e) {}
2469 }
2470 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002471 /*
2472 * Tell the VMs to toss their DNS caches
2473 */
2474 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2475 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002476 /*
2477 * Connectivity events can happen before boot has completed ...
2478 */
2479 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002480 final long ident = Binder.clearCallingIdentity();
2481 try {
2482 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2483 } finally {
2484 Binder.restoreCallingIdentity(ident);
2485 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002486 }
2487
Chia-chi Yehcc844502011-07-14 18:01:57 -07002488 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002489 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002490 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002491 boolean changed = false;
2492 int last = 0;
2493 if (dnses.size() == 0 && mDefaultDns != null) {
2494 ++last;
2495 String value = mDefaultDns.getHostAddress();
2496 if (!value.equals(SystemProperties.get("net.dns1"))) {
2497 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002498 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002499 }
2500 changed = true;
2501 SystemProperties.set("net.dns1", value);
2502 }
2503 } else {
2504 for (InetAddress dns : dnses) {
2505 ++last;
2506 String key = "net.dns" + last;
2507 String value = dns.getHostAddress();
2508 if (!changed && value.equals(SystemProperties.get(key))) {
2509 continue;
2510 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002511 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002512 log("adding dns " + value + " for " + network);
2513 }
2514 changed = true;
2515 SystemProperties.set(key, value);
2516 }
2517 }
2518 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2519 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002520 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002521 changed = true;
2522 SystemProperties.set(key, "");
2523 }
2524 mNumDnsEntries = last;
2525
Robert Greenwaltfce71862011-07-25 16:06:25 -07002526 if (changed) {
2527 try {
2528 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2529 mNetd.setDefaultInterfaceForDns(iface);
2530 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002531 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002532 }
2533 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002534 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2535 SystemProperties.set("net.dns.search", domains);
2536 changed = true;
2537 }
2538 return changed;
2539 }
2540
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002541 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002542 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002543 NetworkStateTracker nt = mNetTrackers[netType];
2544 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002545 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002546 if (p == null) return;
2547 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002548 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002549 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002550 String network = nt.getNetworkInfo().getTypeName();
2551 synchronized (mDnsLock) {
2552 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002553 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002554 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002555 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002556 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002557 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002558 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002559 NetworkUtils.makeStrings(dnses));
2560 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002561 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002562 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002563 // set per-pid dns for attached secondary nets
2564 List pids = mNetRequestersPids[netType];
2565 for (int y=0; y< pids.size(); y++) {
2566 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002567 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002568 }
2569 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002570 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002571 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002572 }
2573
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002574 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002575 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2576 NETWORK_RESTORE_DELAY_PROP_NAME);
2577 if(restoreDefaultNetworkDelayStr != null &&
2578 restoreDefaultNetworkDelayStr.length() != 0) {
2579 try {
2580 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2581 } catch (NumberFormatException e) {
2582 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002583 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002584 // if the system property isn't set, use the value for the apn type
2585 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2586
2587 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2588 (mNetConfigs[networkType] != null)) {
2589 ret = mNetConfigs[networkType].restoreTime;
2590 }
2591 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002592 }
2593
2594 @Override
2595 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002596 if (mContext.checkCallingOrSelfPermission(
2597 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002598 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002599 pw.println("Permission Denial: can't dump ConnectivityService " +
2600 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2601 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002602 return;
2603 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002604 pw.println();
2605 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002606 if (nst != null) {
2607 if (nst.getNetworkInfo().isConnected()) {
2608 pw.println("Active network: " + nst.getNetworkInfo().
2609 getTypeName());
2610 }
2611 pw.println(nst.getNetworkInfo());
2612 pw.println(nst);
2613 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002614 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002615 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002616
2617 pw.println("Network Requester Pids:");
2618 for (int net : mPriorityList) {
2619 String pidString = net + ": ";
2620 for (Object pid : mNetRequestersPids[net]) {
2621 pidString = pidString + pid.toString() + ", ";
2622 }
2623 pw.println(pidString);
2624 }
2625 pw.println();
2626
2627 pw.println("FeatureUsers:");
2628 for (Object requester : mFeatureUsers) {
2629 pw.println(requester.toString());
2630 }
2631 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002632
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002633 synchronized (this) {
2634 pw.println("NetworkTranstionWakeLock is currently " +
2635 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2636 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2637 }
2638 pw.println();
2639
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002640 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002641
2642 if (mInetLog != null) {
2643 pw.println();
2644 pw.println("Inet condition reports:");
2645 for(int i = 0; i < mInetLog.size(); i++) {
2646 pw.println(mInetLog.get(i));
2647 }
2648 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002649 }
2650
Robert Greenwalt2034b912009-08-12 16:08:25 -07002651 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002652 private class NetworkStateTrackerHandler extends Handler {
2653 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002654 super(looper);
2655 }
2656
The Android Open Source Project28527d22009-03-03 19:31:44 -08002657 @Override
2658 public void handleMessage(Message msg) {
2659 NetworkInfo info;
2660 switch (msg.what) {
2661 case NetworkStateTracker.EVENT_STATE_CHANGED:
2662 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002663 int type = info.getType();
2664 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002665
Wink Savillea7d56572011-09-21 11:05:43 -07002666 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2667 (state == NetworkInfo.State.DISCONNECTED)) {
2668 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002669 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002670 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002671 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002672
2673 // Connectivity state changed:
Robert Greenwalt310fa082012-04-25 13:45:02 -07002674 // [31-14] Reserved for future use
2675 // [13-10] Network subtype (for mobile network, as defined
Robert Greenwalt0659da32009-07-16 17:21:39 -07002676 // by TelephonyManager)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002677 // [9-4] Detailed state ordinal (as defined by
Robert Greenwalt0659da32009-07-16 17:21:39 -07002678 // NetworkInfo.DetailedState)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002679 // [3-0] Network type (as defined by ConnectivityManager)
2680 int eventLogParam = (info.getType() & 0xf) |
2681 ((info.getDetailedState().ordinal() & 0x3f) << 4) |
2682 (info.getSubtype() << 10);
Doug Zongker2fc96232009-12-04 10:31:43 -08002683 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002684 eventLogParam);
2685
2686 if (info.getDetailedState() ==
2687 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002688 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002689 } else if (info.getDetailedState() ==
2690 DetailedState.CAPTIVE_PORTAL_CHECK) {
2691 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002692 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002693 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002694 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002695 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002696 // the logic here is, handle SUSPENDED the same as
2697 // DISCONNECTED. The only difference being we are
2698 // broadcasting an intent with NetworkInfo that's
2699 // suspended. This allows the applications an
2700 // opportunity to handle DISCONNECTED and SUSPENDED
2701 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002702 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002703 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002704 handleConnect(info);
2705 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002706 if (mLockdownTracker != null) {
2707 mLockdownTracker.onNetworkInfoChanged(info);
2708 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002709 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002710 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002711 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002712 // TODO: Temporary allowing network configuration
2713 // change not resetting sockets.
2714 // @see bug/4455071
2715 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002716 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002717 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2718 info = (NetworkInfo) msg.obj;
2719 type = info.getType();
2720 updateNetworkSettings(mNetTrackers[type]);
2721 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002722 }
2723 }
2724 }
2725
2726 private class InternalHandler extends Handler {
2727 public InternalHandler(Looper looper) {
2728 super(looper);
2729 }
2730
2731 @Override
2732 public void handleMessage(Message msg) {
2733 NetworkInfo info;
2734 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002735 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002736 String causedBy = null;
2737 synchronized (ConnectivityService.this) {
2738 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2739 mNetTransitionWakeLock.isHeld()) {
2740 mNetTransitionWakeLock.release();
2741 causedBy = mNetTransitionWakeLockCausedBy;
2742 }
2743 }
2744 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002745 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002746 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002747 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002748 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002749 FeatureUser u = (FeatureUser)msg.obj;
2750 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002751 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002752 case EVENT_INET_CONDITION_CHANGE:
2753 {
2754 int netType = msg.arg1;
2755 int condition = msg.arg2;
2756 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002757 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002758 }
2759 case EVENT_INET_CONDITION_HOLD_END:
2760 {
2761 int netType = msg.arg1;
2762 int sequence = msg.arg2;
2763 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002764 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002765 }
2766 case EVENT_SET_NETWORK_PREFERENCE:
2767 {
2768 int preference = msg.arg1;
2769 handleSetNetworkPreference(preference);
2770 break;
2771 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002772 case EVENT_SET_MOBILE_DATA:
2773 {
2774 boolean enabled = (msg.arg1 == ENABLED);
2775 handleSetMobileData(enabled);
2776 break;
2777 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002778 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2779 {
2780 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002781 break;
2782 }
2783 case EVENT_SET_DEPENDENCY_MET:
2784 {
2785 boolean met = (msg.arg1 == ENABLED);
2786 handleSetDependencyMet(msg.arg2, met);
2787 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002788 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002789 case EVENT_RESTORE_DNS:
2790 {
2791 if (mActiveDefaultNetwork != -1) {
2792 handleDnsConfigurationChange(mActiveDefaultNetwork);
2793 }
2794 break;
2795 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002796 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2797 {
2798 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002799 sendStickyBroadcast(intent);
2800 break;
2801 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002802 case EVENT_SET_POLICY_DATA_ENABLE: {
2803 final int networkType = msg.arg1;
2804 final boolean enabled = msg.arg2 == ENABLED;
2805 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002806 break;
2807 }
2808 case EVENT_VPN_STATE_CHANGED: {
2809 if (mLockdownTracker != null) {
2810 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2811 }
2812 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002813 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002814 }
2815 }
2816 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002817
2818 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002819 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002820 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002821
2822 if (isTetheringSupported()) {
2823 return mTethering.tether(iface);
2824 } else {
2825 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2826 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002827 }
2828
2829 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002830 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002831 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002832
2833 if (isTetheringSupported()) {
2834 return mTethering.untether(iface);
2835 } else {
2836 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2837 }
2838 }
2839
2840 // javadoc from interface
2841 public int getLastTetherError(String iface) {
2842 enforceTetherAccessPermission();
2843
2844 if (isTetheringSupported()) {
2845 return mTethering.getLastTetherError(iface);
2846 } else {
2847 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2848 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002849 }
2850
2851 // TODO - proper iface API for selection by property, inspection, etc
2852 public String[] getTetherableUsbRegexs() {
2853 enforceTetherAccessPermission();
2854 if (isTetheringSupported()) {
2855 return mTethering.getTetherableUsbRegexs();
2856 } else {
2857 return new String[0];
2858 }
2859 }
2860
2861 public String[] getTetherableWifiRegexs() {
2862 enforceTetherAccessPermission();
2863 if (isTetheringSupported()) {
2864 return mTethering.getTetherableWifiRegexs();
2865 } else {
2866 return new String[0];
2867 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002868 }
2869
Danica Chang96567052010-08-11 14:54:43 -07002870 public String[] getTetherableBluetoothRegexs() {
2871 enforceTetherAccessPermission();
2872 if (isTetheringSupported()) {
2873 return mTethering.getTetherableBluetoothRegexs();
2874 } else {
2875 return new String[0];
2876 }
2877 }
2878
Mike Lockwooded4a1742011-07-19 13:04:47 -07002879 public int setUsbTethering(boolean enable) {
2880 enforceTetherAccessPermission();
2881 if (isTetheringSupported()) {
2882 return mTethering.setUsbTethering(enable);
2883 } else {
2884 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2885 }
2886 }
2887
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002888 // TODO - move iface listing, queries, etc to new module
2889 // javadoc from interface
2890 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002891 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002892 return mTethering.getTetherableIfaces();
2893 }
2894
2895 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002896 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002897 return mTethering.getTetheredIfaces();
2898 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002899
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002900 @Override
2901 public String[] getTetheredIfacePairs() {
2902 enforceTetherAccessPermission();
2903 return mTethering.getTetheredIfacePairs();
2904 }
2905
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002906 public String[] getTetheringErroredIfaces() {
2907 enforceTetherAccessPermission();
2908 return mTethering.getErroredIfaces();
2909 }
2910
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002911 // if ro.tether.denied = true we default to no tethering
2912 // gservices could set the secure setting to 1 though to enable it on a build where it
2913 // had previously been turned off.
2914 public boolean isTetheringSupported() {
2915 enforceTetherAccessPermission();
2916 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002917 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2918 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2919 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002920 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002921
2922 // An API NetworkStateTrackers can call when they lose their network.
2923 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2924 // whichever happens first. The timer is started by the first caller and not
2925 // restarted by subsequent callers.
2926 public void requestNetworkTransitionWakelock(String forWhom) {
2927 enforceConnectivityInternalPermission();
2928 synchronized (this) {
2929 if (mNetTransitionWakeLock.isHeld()) return;
2930 mNetTransitionWakeLockSerialNumber++;
2931 mNetTransitionWakeLock.acquire();
2932 mNetTransitionWakeLockCausedBy = forWhom;
2933 }
2934 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002935 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002936 mNetTransitionWakeLockSerialNumber, 0),
2937 mNetTransitionWakeLockTimeout);
2938 return;
2939 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002940
Robert Greenwalt986c7412010-09-08 15:24:47 -07002941 // 100 percent is full good, 0 is full bad.
2942 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002943 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002944 mContext.enforceCallingOrSelfPermission(
2945 android.Manifest.permission.STATUS_BAR,
2946 "ConnectivityService");
2947
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002948 if (DBG) {
2949 int pid = getCallingPid();
2950 int uid = getCallingUid();
2951 String s = pid + "(" + uid + ") reports inet is " +
2952 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2953 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2954 mInetLog.add(s);
2955 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2956 mInetLog.remove(0);
2957 }
2958 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002959 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002960 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2961 }
2962
2963 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002964 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002965 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002966 return;
2967 }
2968 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002969 if (DBG) log("handleInetConditionChange: net=" + netType +
2970 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002971 return;
2972 }
Wink Savillea7d56572011-09-21 11:05:43 -07002973 if (VDBG) {
2974 log("handleInetConditionChange: net=" +
2975 netType + ", condition=" + condition +
2976 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2977 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002978 mDefaultInetCondition = condition;
2979 int delay;
2980 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002981 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002982 // setup a new hold to debounce this
2983 if (mDefaultInetCondition > 50) {
2984 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2985 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2986 } else {
2987 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2988 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2989 }
2990 mInetConditionChangeInFlight = true;
2991 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2992 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2993 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002994 // we've set the new condition, when this hold ends that will get picked up
2995 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002996 }
2997 }
2998
2999 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003000 if (DBG) {
3001 log("handleInetConditionHoldEnd: net=" + netType +
3002 ", condition=" + mDefaultInetCondition +
3003 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003004 }
3005 mInetConditionChangeInFlight = false;
3006
3007 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003008 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003009 return;
3010 }
3011 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003012 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003013 return;
3014 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07003015 // TODO: Figure out why this optimization sometimes causes a
3016 // change in mDefaultInetCondition to be missed and the
3017 // UI to not be updated.
3018 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3019 // if (DBG) log("no change in condition - aborting");
3020 // return;
3021 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003022 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3023 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003024 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003025 return;
3026 }
3027 mDefaultInetConditionPublished = mDefaultInetCondition;
3028 sendInetConditionBroadcast(networkInfo);
3029 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003030 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003031
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003032 public ProxyProperties getProxy() {
3033 synchronized (mDefaultProxyLock) {
3034 return mDefaultProxyDisabled ? null : mDefaultProxy;
3035 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003036 }
3037
3038 public void setGlobalProxy(ProxyProperties proxyProperties) {
3039 enforceChangePermission();
3040 synchronized (mGlobalProxyLock) {
3041 if (proxyProperties == mGlobalProxy) return;
3042 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3043 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3044
3045 String host = "";
3046 int port = 0;
3047 String exclList = "";
3048 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3049 mGlobalProxy = new ProxyProperties(proxyProperties);
3050 host = mGlobalProxy.getHost();
3051 port = mGlobalProxy.getPort();
3052 exclList = mGlobalProxy.getExclusionList();
3053 } else {
3054 mGlobalProxy = null;
3055 }
3056 ContentResolver res = mContext.getContentResolver();
3057 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
3058 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003059 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003060 exclList);
3061 }
3062
3063 if (mGlobalProxy == null) {
3064 proxyProperties = mDefaultProxy;
3065 }
Chia-chi Yehae166612011-09-28 16:38:18 -07003066 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003067 }
3068
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003069 private void loadGlobalProxy() {
3070 ContentResolver res = mContext.getContentResolver();
3071 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
3072 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
3073 String exclList = Settings.Secure.getString(res,
3074 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3075 if (!TextUtils.isEmpty(host)) {
3076 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3077 synchronized (mGlobalProxyLock) {
3078 mGlobalProxy = proxyProperties;
3079 }
3080 }
3081 }
3082
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003083 public ProxyProperties getGlobalProxy() {
3084 synchronized (mGlobalProxyLock) {
3085 return mGlobalProxy;
3086 }
3087 }
3088
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003089 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3090 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3091 proxy = null;
3092 }
3093 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003094 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3095 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003096 mDefaultProxy = proxy;
3097
3098 if (!mDefaultProxyDisabled) {
3099 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003100 }
3101 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003102 }
3103
3104 private void handleDeprecatedGlobalHttpProxy() {
3105 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
3106 Settings.Secure.HTTP_PROXY);
3107 if (!TextUtils.isEmpty(proxy)) {
3108 String data[] = proxy.split(":");
3109 String proxyHost = data[0];
3110 int proxyPort = 8080;
3111 if (data.length > 1) {
3112 try {
3113 proxyPort = Integer.parseInt(data[1]);
3114 } catch (NumberFormatException e) {
3115 return;
3116 }
3117 }
3118 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3119 setGlobalProxy(p);
3120 }
3121 }
3122
3123 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003124 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003125 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003126 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003127 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3128 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003129 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003130 final long ident = Binder.clearCallingIdentity();
3131 try {
3132 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3133 } finally {
3134 Binder.restoreCallingIdentity(ident);
3135 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003136 }
3137
3138 private static class SettingsObserver extends ContentObserver {
3139 private int mWhat;
3140 private Handler mHandler;
3141 SettingsObserver(Handler handler, int what) {
3142 super(handler);
3143 mHandler = handler;
3144 mWhat = what;
3145 }
3146
3147 void observe(Context context) {
3148 ContentResolver resolver = context.getContentResolver();
3149 resolver.registerContentObserver(Settings.Secure.getUriFor(
3150 Settings.Secure.HTTP_PROXY), false, this);
3151 }
3152
3153 @Override
3154 public void onChange(boolean selfChange) {
3155 mHandler.obtainMessage(mWhat).sendToTarget();
3156 }
3157 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003158
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003159 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003160 Slog.d(TAG, s);
3161 }
3162
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003163 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003164 Slog.e(TAG, s);
3165 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003166
repo syncf5de5572011-07-29 23:55:49 -07003167 int convertFeatureToNetworkType(int networkType, String feature) {
3168 int usedNetworkType = networkType;
3169
3170 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3171 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3172 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3173 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3174 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3175 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3176 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3177 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3178 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3179 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3180 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3181 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3182 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3183 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3184 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3185 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3186 } else {
3187 Slog.e(TAG, "Can't match any mobile netTracker!");
3188 }
3189 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3190 if (TextUtils.equals(feature, "p2p")) {
3191 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3192 } else {
3193 Slog.e(TAG, "Can't match any wifi netTracker!");
3194 }
3195 } else {
3196 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003197 }
repo syncf5de5572011-07-29 23:55:49 -07003198 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003199 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003200
3201 private static <T> T checkNotNull(T value, String message) {
3202 if (value == null) {
3203 throw new NullPointerException(message);
3204 }
3205 return value;
3206 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003207
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003208 /**
3209 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003210 * VpnBuilder and not available in ConnectivityManager. Permissions
3211 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003212 * @hide
3213 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003214 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003215 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003216 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003217 try {
3218 int type = mActiveDefaultNetwork;
3219 if (ConnectivityManager.isNetworkTypeValid(type)) {
3220 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3221 return true;
3222 }
3223 } catch (Exception e) {
3224 // ignore
3225 } finally {
3226 try {
3227 socket.close();
3228 } catch (Exception e) {
3229 // ignore
3230 }
3231 }
3232 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003233 }
3234
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003235 /**
3236 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003237 * and not available in ConnectivityManager. Permissions are checked
3238 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003239 * @hide
3240 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003241 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003242 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003243 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003244 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003245 }
3246
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003247 /**
3248 * Configure a TUN interface and return its file descriptor. Parameters
3249 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003250 * and not available in ConnectivityManager. Permissions are checked in
3251 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003252 * @hide
3253 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003254 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003255 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003256 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003257 return mVpn.establish(config);
3258 }
3259
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003260 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003261 * Start legacy VPN, controlling native daemons as needed. Creates a
3262 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003263 */
3264 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003265 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003266 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003267 final LinkProperties egress = getActiveLinkProperties();
3268 if (egress == null) {
3269 throw new IllegalStateException("Missing active network connection");
3270 }
3271 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003272 }
3273
3274 /**
3275 * Return the information of the ongoing legacy VPN. This method is used
3276 * by VpnSettings and not available in ConnectivityManager. Permissions
3277 * are checked in Vpn class.
3278 * @hide
3279 */
3280 @Override
3281 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003282 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003283 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003284 }
3285
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003286 /**
3287 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3288 * through NetworkStateTracker since it works differently. For example, it
3289 * needs to override DNS servers but never takes the default routes. It
3290 * relies on another data network, and it could keep existing connections
3291 * alive after reconnecting, switching between networks, or even resuming
3292 * from deep sleep. Calls from applications should be done synchronously
3293 * to avoid race conditions. As these are all hidden APIs, refactoring can
3294 * be done whenever a better abstraction is developed.
3295 */
3296 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003297 private VpnCallback() {
3298 }
3299
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003300 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003301 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003302 }
3303
Chia-chi Yehcc844502011-07-14 18:01:57 -07003304 public void override(List<String> dnsServers, List<String> searchDomains) {
3305 if (dnsServers == null) {
3306 restore();
3307 return;
3308 }
3309
3310 // Convert DNS servers into addresses.
3311 List<InetAddress> addresses = new ArrayList<InetAddress>();
3312 for (String address : dnsServers) {
3313 // Double check the addresses and remove invalid ones.
3314 try {
3315 addresses.add(InetAddress.parseNumericAddress(address));
3316 } catch (Exception e) {
3317 // ignore
3318 }
3319 }
3320 if (addresses.isEmpty()) {
3321 restore();
3322 return;
3323 }
3324
3325 // Concatenate search domains into a string.
3326 StringBuilder buffer = new StringBuilder();
3327 if (searchDomains != null) {
3328 for (String domain : searchDomains) {
3329 buffer.append(domain).append(' ');
3330 }
3331 }
3332 String domains = buffer.toString().trim();
3333
3334 // Apply DNS changes.
3335 boolean changed = false;
3336 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07003337 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003338 mDnsOverridden = true;
3339 }
3340 if (changed) {
3341 bumpDns();
3342 }
3343
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003344 // Temporarily disable the default proxy.
3345 synchronized (mDefaultProxyLock) {
3346 mDefaultProxyDisabled = true;
3347 if (mDefaultProxy != null) {
3348 sendProxyBroadcast(null);
3349 }
3350 }
3351
3352 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003353 }
3354
Chia-chi Yehcc844502011-07-14 18:01:57 -07003355 public void restore() {
3356 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003357 if (mDnsOverridden) {
3358 mDnsOverridden = false;
3359 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003360 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003361 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003362 synchronized (mDefaultProxyLock) {
3363 mDefaultProxyDisabled = false;
3364 if (mDefaultProxy != null) {
3365 sendProxyBroadcast(mDefaultProxy);
3366 }
3367 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003368 }
3369 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003370
3371 @Override
3372 public boolean updateLockdownVpn() {
3373 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3374
3375 // Tear down existing lockdown if profile was removed
3376 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3377 if (mLockdownEnabled) {
3378 if (mKeyStore.state() != KeyStore.State.UNLOCKED) {
3379 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3380 return false;
3381 }
3382
3383 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3384 final VpnProfile profile = VpnProfile.decode(
3385 profileName, mKeyStore.get(Credentials.VPN + profileName));
3386 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3387 } else {
3388 setLockdownTracker(null);
3389 }
3390
3391 return true;
3392 }
3393
3394 /**
3395 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3396 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3397 */
3398 private void setLockdownTracker(LockdownVpnTracker tracker) {
3399 // Shutdown any existing tracker
3400 final LockdownVpnTracker existing = mLockdownTracker;
3401 mLockdownTracker = null;
3402 if (existing != null) {
3403 existing.shutdown();
3404 }
3405
3406 try {
3407 if (tracker != null) {
3408 mNetd.setFirewallEnabled(true);
3409 mLockdownTracker = tracker;
3410 mLockdownTracker.init();
3411 } else {
3412 mNetd.setFirewallEnabled(false);
3413 }
3414 } catch (RemoteException e) {
3415 // ignored; NMS lives inside system_server
3416 }
3417 }
3418
3419 private void throwIfLockdownEnabled() {
3420 if (mLockdownEnabled) {
3421 throw new IllegalStateException("Unavailable in lockdown mode");
3422 }
3423 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003424}