blob: eaaf8c22f9fad05b74ddc317bca0eabfcb4c021d [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070036import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070038import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070040import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070042import android.net.NetworkInfo.DetailedState;
Jeff Sharkey21062e72011-05-28 20:56:34 -070043import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070045import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070046import android.net.Proxy;
47import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070048import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080049import android.net.wifi.WifiStateTracker;
50import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040051import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080052import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070053import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070054import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070055import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080056import android.os.Looper;
57import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070058import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070059import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070060import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080061import android.os.ServiceManager;
62import android.os.SystemProperties;
63import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070064import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080066import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070067import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070069import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070070import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070071import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080072import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070073import com.android.server.connectivity.Vpn;
74
Jeff Sharkey21062e72011-05-28 20:56:34 -070075import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070076import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080077
The Android Open Source Project28527d22009-03-03 19:31:44 -080078import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070079import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080080import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070081import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070082import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070083import java.net.InetAddress;
84import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070085import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070086import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070087import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070088import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070089import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070090import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070091import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092
93/**
94 * @hide
95 */
96public class ConnectivityService extends IConnectivityManager.Stub {
97
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070098 private static final boolean DBG = true;
Wink Saville051a6642011-07-13 13:44:13 -070099 private static final boolean VDBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100 private static final String TAG = "ConnectivityService";
101
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700102 private static final boolean LOGD_RULES = false;
103
Robert Greenwalt2034b912009-08-12 16:08:25 -0700104 // how long to wait before switching back to a radio's default network
105 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
106 // system property that can override the above value
107 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
108 "android.telephony.apn-restore";
109
Robert Greenwaltbd492212011-05-06 17:10:53 -0700110 // used in recursive route setting to add gateways for the host for which
111 // a host route was requested.
112 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
113
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800114 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800115 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800116
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700117 private Vpn mVpn;
118
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700119 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
120 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121 /** Currently active network rules by UID. */
122 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700123 /** Set of ifaces that are costly. */
124 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700125
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126 /**
127 * Sometimes we want to refer to the individual network state
128 * trackers separately, and sometimes we just want to treat them
129 * abstractly.
130 */
131 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700132
133 /**
Wink Saville051a6642011-07-13 13:44:13 -0700134 * The link properties that define the current links
135 */
136 private LinkProperties mCurrentLinkProperties[];
137
138 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700139 * A per Net list of the PID's that requested access to the net
140 * used both as a refcount and for per-PID DNS selection
141 */
142 private List mNetRequestersPids[];
143
Robert Greenwalt2034b912009-08-12 16:08:25 -0700144 // priority order of the nettrackers
145 // (excluding dynamically set mNetworkPreference)
146 // TODO - move mNetworkTypePreference into this
147 private int[] mPriorityList;
148
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149 private Context mContext;
150 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700151 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700152 // 0 is full bad, 100 is full good
153 private int mDefaultInetCondition = 0;
154 private int mDefaultInetConditionPublished = 0;
155 private boolean mInetConditionChangeInFlight = false;
156 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157
158 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159
160 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700161 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800163 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
164
Robert Greenwalt355205c2011-05-10 15:05:02 -0700165 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700166 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700167
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700168 private static final int ENABLED = 1;
169 private static final int DISABLED = 0;
170
171 // Share the event space with NetworkStateTracker (which can't see this
172 // internal class but sends us events). If you change these, change
173 // NetworkStateTracker.java too.
174 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
175 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
176
177 /**
178 * used internally as a delayed event to make us switch back to the
179 * default network
180 */
181 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
182 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
183
184 /**
185 * used internally to change our mobile data enabled flag
186 */
187 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
188 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
189
190 /**
191 * used internally to change our network preference setting
192 * arg1 = networkType to prefer
193 */
194 private static final int EVENT_SET_NETWORK_PREFERENCE =
195 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
196
197 /**
198 * used internally to synchronize inet condition reports
199 * arg1 = networkType
200 * arg2 = condition (0 bad, 100 good)
201 */
202 private static final int EVENT_INET_CONDITION_CHANGE =
203 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
204
205 /**
206 * used internally to mark the end of inet condition hold periods
207 * arg1 = networkType
208 */
209 private static final int EVENT_INET_CONDITION_HOLD_END =
210 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
211
212 /**
213 * used internally to set the background data preference
214 * arg1 = TRUE for enabled, FALSE for disabled
215 */
216 private static final int EVENT_SET_BACKGROUND_DATA =
217 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
218
219 /**
220 * used internally to set enable/disable cellular data
221 * arg1 = ENBALED or DISABLED
222 */
223 private static final int EVENT_SET_MOBILE_DATA =
224 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
225
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700226 /**
227 * used internally to clear a wakelock when transitioning
228 * from one net to another
229 */
230 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
231 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
232
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700233 /**
234 * used internally to reload global proxy settings
235 */
236 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
237 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
238
Robert Greenwalt34848c02011-03-25 13:09:25 -0700239 /**
240 * used internally to set external dependency met/unmet
241 * arg1 = ENABLED (met) or DISABLED (unmet)
242 * arg2 = NetworkType
243 */
244 private static final int EVENT_SET_DEPENDENCY_MET =
245 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
246
Robert Greenwalt2034b912009-08-12 16:08:25 -0700247 private Handler mHandler;
248
249 // list of DeathRecipients used to make sure features are turned off when
250 // a process dies
251 private List mFeatureUsers;
252
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400253 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800254 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400255
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700256 private PowerManager.WakeLock mNetTransitionWakeLock;
257 private String mNetTransitionWakeLockCausedBy = "";
258 private int mNetTransitionWakeLockSerialNumber;
259 private int mNetTransitionWakeLockTimeout;
260
Robert Greenwalt94daa182010-09-01 11:34:05 -0700261 private InetAddress mDefaultDns;
262
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700263 // this collection is used to refcount the added routes - if there are none left
264 // it's time to remove the route from the route table
265 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
266
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700267 // used in DBG mode to track inet condition reports
268 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
269 private ArrayList mInetLog;
270
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700271 // track the current default http proxy - tell the world if we get a new one (real change)
272 private ProxyProperties mDefaultProxy = null;
273 // track the global proxy.
274 private ProxyProperties mGlobalProxy = null;
275 private final Object mGlobalProxyLock = new Object();
276
277 private SettingsObserver mSettingsObserver;
278
Robert Greenwalt34848c02011-03-25 13:09:25 -0700279 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700280 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700281
Robert Greenwalt12c44552009-12-07 11:33:18 -0800282 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700283 public int mSimultaneity;
284 public int mType;
285 public RadioAttributes(String init) {
286 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700287 mType = Integer.parseInt(fragments[0]);
288 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700289 }
290 }
291 RadioAttributes[] mRadioAttributes;
292
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700293 // the set of network types that can only be enabled by system/sig apps
294 List mProtectedNetworks;
295
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700296 public ConnectivityService(
297 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800298 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800299
Wink Saville775aad62010-09-02 19:23:52 -0700300 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
301 handlerThread.start();
302 mHandler = new MyHandler(handlerThread.getLooper());
303
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800304 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
305 Settings.Secure.BACKGROUND_DATA, 1) == 1);
306
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800307 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800308 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
309 String id = Settings.Secure.getString(context.getContentResolver(),
310 Settings.Secure.ANDROID_ID);
311 if (id != null && id.length() > 0) {
312 String name = new String("android_").concat(id);
313 SystemProperties.set("net.hostname", name);
314 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800315 }
316
Robert Greenwalt94daa182010-09-01 11:34:05 -0700317 // read our default dns server ip
318 String dns = Settings.Secure.getString(context.getContentResolver(),
319 Settings.Secure.DEFAULT_DNS_SERVER);
320 if (dns == null || dns.length() == 0) {
321 dns = context.getResources().getString(
322 com.android.internal.R.string.config_default_dns_server);
323 }
324 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800325 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
326 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800327 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700328 }
329
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 mContext = checkNotNull(context, "missing Context");
331 mNetd = checkNotNull(netd, "missing INetworkManagementService");
332 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700333
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700334 try {
335 mPolicyManager.registerListener(mPolicyListener);
336 } catch (RemoteException e) {
337 // ouch, no rules updates means some processes may never get network
338 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
339 }
340
341 final PowerManager powerManager = (PowerManager) context.getSystemService(
342 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700343 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
344 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
345 com.android.internal.R.integer.config_networkTransitionTimeout);
346
Robert Greenwalt2034b912009-08-12 16:08:25 -0700347 mNetTrackers = new NetworkStateTracker[
348 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700349 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700350
The Android Open Source Project28527d22009-03-03 19:31:44 -0800351 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700352
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700353 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700354 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700355
Robert Greenwalt2034b912009-08-12 16:08:25 -0700356 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 String[] raStrings = context.getResources().getStringArray(
358 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700359 for (String raString : raStrings) {
360 RadioAttributes r = new RadioAttributes(raString);
361 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800362 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 continue;
364 }
365 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800366 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700367 r.mType);
368 continue;
369 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700370 mRadioAttributes[r.mType] = r;
371 }
372
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 String[] naStrings = context.getResources().getStringArray(
374 com.android.internal.R.array.networkAttributes);
375 for (String naString : naStrings) {
376 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700377 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700378 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800379 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700380 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700382 }
Wink Savillef2a62832011-04-07 14:23:45 -0700383 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800384 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700385 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700386 continue;
387 }
Wink Savillef2a62832011-04-07 14:23:45 -0700388 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700390 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 continue;
392 }
Wink Savillef2a62832011-04-07 14:23:45 -0700393 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700394 mNetworksDefined++;
395 } catch(Exception e) {
396 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700397 }
398 }
399
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700400 mProtectedNetworks = new ArrayList<Integer>();
401 int[] protectedNetworks = context.getResources().getIntArray(
402 com.android.internal.R.array.config_protectedNetworks);
403 for (int p : protectedNetworks) {
404 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
405 mProtectedNetworks.add(p);
406 } else {
407 if (DBG) loge("Ignoring protectedNetwork " + p);
408 }
409 }
410
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700411 // high priority first
412 mPriorityList = new int[mNetworksDefined];
413 {
414 int insertionPoint = mNetworksDefined-1;
415 int currentLowest = 0;
416 int nextLowest = 0;
417 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700418 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700419 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700420 if (na.priority < currentLowest) continue;
421 if (na.priority > currentLowest) {
422 if (na.priority < nextLowest || nextLowest == 0) {
423 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700424 }
425 continue;
426 }
Wink Savillef2a62832011-04-07 14:23:45 -0700427 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 }
429 currentLowest = nextLowest;
430 nextLowest = 0;
431 }
432 }
433
434 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
435 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700436 mNetRequestersPids[i] = new ArrayList();
437 }
438
439 mFeatureUsers = new ArrayList();
440
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700441 mNumDnsEntries = 0;
442
443 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
444 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800445 /*
446 * Create the network state trackers for Wi-Fi and mobile
447 * data. Maybe this could be done with a factory class,
448 * but it's not clear that it's worth it, given that
449 * the number of different network types is not going
450 * to change very often.
451 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700453 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700454 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800455 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700456 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700457 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700458 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700459 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700460 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700461 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 break;
463 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700464 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700465 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700466 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700467 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800468 case ConnectivityManager.TYPE_DUMMY:
469 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700470 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800471 mNetTrackers[netType].startMonitoring(context, mHandler);
472 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800473 case ConnectivityManager.TYPE_BLUETOOTH:
474 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
475 mNetTrackers[netType].startMonitoring(context, mHandler);
476 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800477 case ConnectivityManager.TYPE_ETHERNET:
478 mNetTrackers[netType] = EthernetDataTracker.getInstance();
479 mNetTrackers[netType].startMonitoring(context, mHandler);
480 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700481 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800482 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700483 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700484 continue;
485 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700486 mCurrentLinkProperties[netType] = null;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700487 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800488
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700489 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
490 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
491
492 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700493 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700494 mTethering.getTetherableWifiRegexs().length != 0 ||
495 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700496 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800497
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700498 mVpn = new Vpn(mContext, new VpnCallback());
499
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700500 try {
501 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700502 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700503 } catch (RemoteException e) {
504 loge("Error registering observer :" + e);
505 }
506
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700507 if (DBG) {
508 mInetLog = new ArrayList();
509 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700510
511 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
512 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800513
514 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800515 }
516
517 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700518 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800519 * @param preference the new preference
520 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700521 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800522 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700523
524 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800525 }
526
527 public int getNetworkPreference() {
528 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700529 int preference;
530 synchronized(this) {
531 preference = mNetworkPreference;
532 }
533 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800534 }
535
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700536 private void handleSetNetworkPreference(int preference) {
537 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700538 mNetConfigs[preference] != null &&
539 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700540 if (mNetworkPreference != preference) {
541 final ContentResolver cr = mContext.getContentResolver();
542 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
543 synchronized(this) {
544 mNetworkPreference = preference;
545 }
546 enforcePreference();
547 }
548 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800549 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700550
The Android Open Source Project28527d22009-03-03 19:31:44 -0800551 private int getPersistedNetworkPreference() {
552 final ContentResolver cr = mContext.getContentResolver();
553
554 final int networkPrefSetting = Settings.Secure
555 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
556 if (networkPrefSetting != -1) {
557 return networkPrefSetting;
558 }
559
560 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
561 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700562
The Android Open Source Project28527d22009-03-03 19:31:44 -0800563 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700564 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800565 * In this method, we only tear down a non-preferred network. Establishing
566 * a connection to the preferred network is taken care of when we handle
567 * the disconnect event from the non-preferred network
568 * (see {@link #handleDisconnect(NetworkInfo)}).
569 */
570 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800572 return;
573
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 if (!mNetTrackers[mNetworkPreference].isAvailable())
575 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800576
Robert Greenwalt2034b912009-08-12 16:08:25 -0700577 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700578 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700579 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700580 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800581 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700582 " in enforcePreference");
583 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800585 }
586 }
587 }
588
589 private boolean teardown(NetworkStateTracker netTracker) {
590 if (netTracker.teardown()) {
591 netTracker.setTeardownRequested(true);
592 return true;
593 } else {
594 return false;
595 }
596 }
597
598 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700599 * Check if UID should be blocked from using the network represented by the
600 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700601 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700602 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
603 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700604
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700605 final boolean networkCostly;
606 final int uidRules;
607 synchronized (mRulesLock) {
608 networkCostly = mMeteredIfaces.contains(iface);
609 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700610 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700611
612 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
613 return true;
614 }
615
616 // no restrictive rules; network is visible
617 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700618 }
619
620 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700621 * Return a filtered {@link NetworkInfo}, potentially marked
622 * {@link DetailedState#BLOCKED} based on
623 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700624 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700625 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
626 NetworkInfo info = tracker.getNetworkInfo();
627 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700628 // network is blocked; clone and override state
629 info = new NetworkInfo(info);
630 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700631 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700632 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700633 }
634
635 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800636 * Return NetworkInfo for the active (i.e., connected) network interface.
637 * It is assumed that at most one network is active at a time. If more
638 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700639 * @return the info for the active network, or {@code null} if none is
640 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800641 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700642 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800643 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700644 enforceAccessPermission();
645 final int uid = Binder.getCallingUid();
646 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800647 }
648
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700649 @Override
650 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
651 enforceConnectivityInternalPermission();
652 return getNetworkInfo(mActiveDefaultNetwork, uid);
653 }
654
655 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800656 public NetworkInfo getNetworkInfo(int networkType) {
657 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700658 final int uid = Binder.getCallingUid();
659 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800660 }
661
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700662 private NetworkInfo getNetworkInfo(int networkType, int uid) {
663 NetworkInfo info = null;
664 if (isNetworkTypeValid(networkType)) {
665 final NetworkStateTracker tracker = mNetTrackers[networkType];
666 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700667 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700668 }
669 }
670 return info;
671 }
672
673 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800674 public NetworkInfo[] getAllNetworkInfo() {
675 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700676 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700677 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700678 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700679 for (NetworkStateTracker tracker : mNetTrackers) {
680 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700681 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700682 }
683 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800684 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700685 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800686 }
687
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700688 /**
689 * Return LinkProperties for the active (i.e., connected) default
690 * network interface. It is assumed that at most one default network
691 * is active at a time. If more than one is active, it is indeterminate
692 * which will be returned.
693 * @return the ip properties for the active network, or {@code null} if
694 * none is active
695 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700696 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700697 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700698 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700699 }
700
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700701 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700702 public LinkProperties getLinkProperties(int networkType) {
703 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700704 if (isNetworkTypeValid(networkType)) {
705 final NetworkStateTracker tracker = mNetTrackers[networkType];
706 if (tracker != null) {
707 return tracker.getLinkProperties();
708 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700709 }
710 return null;
711 }
712
Jeff Sharkey21062e72011-05-28 20:56:34 -0700713 @Override
714 public NetworkState[] getAllNetworkState() {
715 enforceAccessPermission();
716 final int uid = Binder.getCallingUid();
717 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700718 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700719 for (NetworkStateTracker tracker : mNetTrackers) {
720 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700721 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700722 result.add(new NetworkState(
723 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
724 }
725 }
726 }
727 return result.toArray(new NetworkState[result.size()]);
728 }
729
The Android Open Source Project28527d22009-03-03 19:31:44 -0800730 public boolean setRadios(boolean turnOn) {
731 boolean result = true;
732 enforceChangePermission();
733 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700734 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800735 }
736 return result;
737 }
738
739 public boolean setRadio(int netType, boolean turnOn) {
740 enforceChangePermission();
741 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
742 return false;
743 }
744 NetworkStateTracker tracker = mNetTrackers[netType];
745 return tracker != null && tracker.setRadio(turnOn);
746 }
747
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700748 /**
749 * Used to notice when the calling process dies so we can self-expire
750 *
751 * Also used to know if the process has cleaned up after itself when
752 * our auto-expire timer goes off. The timer has a link to an object.
753 *
754 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700755 private class FeatureUser implements IBinder.DeathRecipient {
756 int mNetworkType;
757 String mFeature;
758 IBinder mBinder;
759 int mPid;
760 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800761 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700762
763 FeatureUser(int type, String feature, IBinder binder) {
764 super();
765 mNetworkType = type;
766 mFeature = feature;
767 mBinder = binder;
768 mPid = getCallingPid();
769 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800770 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700771
Robert Greenwalt2034b912009-08-12 16:08:25 -0700772 try {
773 mBinder.linkToDeath(this, 0);
774 } catch (RemoteException e) {
775 binderDied();
776 }
777 }
778
779 void unlinkDeathRecipient() {
780 mBinder.unlinkToDeath(this, 0);
781 }
782
783 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800784 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800785 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
786 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700787 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700788 }
789
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700790 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800791 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800792 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
793 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700794 stopUsingNetworkFeature(this, false);
795 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800796
797 public String toString() {
798 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
799 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
800 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700801 }
802
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700803 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700804 public int startUsingNetworkFeature(int networkType, String feature,
805 IBinder binder) {
806 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800807 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700808 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800809 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700810 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700811 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700812 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700815 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700816
817 // TODO - move this into the MobileDataStateTracker
818 int usedNetworkType = networkType;
819 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800820 usedNetworkType = convertFeatureToNetworkType(feature);
821 if (usedNetworkType < 0) {
822 Slog.e(TAG, "Can't match any netTracker!");
823 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700824 }
825 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700826
827 if (mProtectedNetworks.contains(usedNetworkType)) {
828 enforceConnectivityInternalPermission();
829 }
830
Robert Greenwalt2034b912009-08-12 16:08:25 -0700831 NetworkStateTracker network = mNetTrackers[usedNetworkType];
832 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800833 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700834 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700835 NetworkStateTracker radio = mNetTrackers[networkType];
836 NetworkInfo ni = network.getNetworkInfo();
837
838 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800839 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800840 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
841 return Phone.APN_TYPE_NOT_AVAILABLE;
842 } else {
843 // else make the attempt anyway - probably giving REQUEST_STARTED below
844 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700845 }
846
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700847 synchronized(this) {
848 mFeatureUsers.add(f);
849 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
850 // this gets used for per-pid dns when connected
851 mNetRequestersPids[usedNetworkType].add(currentPid);
852 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700853 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700854
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700855 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
856
857 if (restoreTimer >= 0) {
858 mHandler.sendMessageDelayed(
859 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
860 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700861
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700862 if ((ni.isConnectedOrConnecting() == true) &&
863 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700864 if (ni.isConnected() == true) {
865 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700866 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800867 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700868 return Phone.APN_ALREADY_ACTIVE;
869 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800870 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700871 return Phone.APN_REQUEST_STARTED;
872 }
873
874 // check if the radio in play can make another contact
875 // assume if cannot for now
876
Wink Savillee70c6f52010-12-03 12:01:38 -0800877 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700878 network.reconnect();
879 return Phone.APN_REQUEST_STARTED;
880 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800881 // need to remember this unsupported request so we respond appropriately on stop
882 synchronized(this) {
883 mFeatureUsers.add(f);
884 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
885 // this gets used for per-pid dns when connected
886 mNetRequestersPids[usedNetworkType].add(currentPid);
887 }
888 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700889 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700890 }
891 }
892 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800893 }
894
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700895 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800896 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700897 enforceChangePermission();
898
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700899 int pid = getCallingPid();
900 int uid = getCallingUid();
901
902 FeatureUser u = null;
903 boolean found = false;
904
905 synchronized(this) {
906 for (int i = 0; i < mFeatureUsers.size() ; i++) {
907 u = (FeatureUser)mFeatureUsers.get(i);
908 if (uid == u.mUid && pid == u.mPid &&
909 networkType == u.mNetworkType &&
910 TextUtils.equals(feature, u.mFeature)) {
911 found = true;
912 break;
913 }
914 }
915 }
916 if (found && u != null) {
917 // stop regardless of how many other time this proc had called start
918 return stopUsingNetworkFeature(u, true);
919 } else {
920 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800921 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700922 return 1;
923 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700924 }
925
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700926 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
927 int networkType = u.mNetworkType;
928 String feature = u.mFeature;
929 int pid = u.mPid;
930 int uid = u.mUid;
931
932 NetworkStateTracker tracker = null;
933 boolean callTeardown = false; // used to carry our decision outside of sync block
934
Robert Greenwalt2034b912009-08-12 16:08:25 -0700935 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800936 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700937 ": " + feature);
938 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700939
The Android Open Source Project28527d22009-03-03 19:31:44 -0800940 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
941 return -1;
942 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700943
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700944 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
945 // sync block
946 synchronized(this) {
947 // check if this process still has an outstanding start request
948 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800949 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700950 return 1;
951 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700952 u.unlinkDeathRecipient();
953 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
954 // If we care about duplicate requests, check for that here.
955 //
956 // This is done to support the extension of a request - the app
957 // can request we start the network feature again and renew the
958 // auto-shutoff delay. Normal "stop" calls from the app though
959 // do not pay attention to duplicate requests - in effect the
960 // API does not refcount and a single stop will counter multiple starts.
961 if (ignoreDups == false) {
962 for (int i = 0; i < mFeatureUsers.size() ; i++) {
963 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
964 if (x.mUid == u.mUid && x.mPid == u.mPid &&
965 x.mNetworkType == u.mNetworkType &&
966 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800967 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700968 return 1;
969 }
970 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700971 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700972
973 // TODO - move to MobileDataStateTracker
974 int usedNetworkType = networkType;
975 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800976 usedNetworkType = convertFeatureToNetworkType(feature);
977 if (usedNetworkType < 0) {
978 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700979 }
980 }
981 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700982 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800983 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700984 return -1;
985 }
986 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700987 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700988 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800989 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700990 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800991 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700992 "others still using it");
993 return 1;
994 }
995 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800996 } else {
997 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700998 }
999 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001000 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001001 if (callTeardown) {
1002 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001003 return 1;
1004 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001005 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001006 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001007 }
1008
1009 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001010 * @deprecated use requestRouteToHostAddress instead
1011 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 * Ensure that a network route exists to deliver traffic to the specified
1013 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001014 * @param networkType the type of the network over which traffic to the
1015 * specified host is to be routed
1016 * @param hostAddress the IP address of the host to which the route is
1017 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001018 * @return {@code true} on success, {@code false} on failure
1019 */
1020 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001021 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1022
1023 if (inetAddress == null) {
1024 return false;
1025 }
1026
1027 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1028 }
1029
1030 /**
1031 * Ensure that a network route exists to deliver traffic to the specified
1032 * host via the specified network interface.
1033 * @param networkType the type of the network over which traffic to the
1034 * specified host is to be routed
1035 * @param hostAddress the IP address of the host to which the route is
1036 * desired
1037 * @return {@code true} on success, {@code false} on failure
1038 */
1039 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001040 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001041 if (mProtectedNetworks.contains(networkType)) {
1042 enforceConnectivityInternalPermission();
1043 }
1044
The Android Open Source Project28527d22009-03-03 19:31:44 -08001045 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1046 return false;
1047 }
1048 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001049
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001050 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1051 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001052 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001053 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001054 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001055 }
1056 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001057 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001058 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001059 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001060 LinkProperties lp = tracker.getLinkProperties();
1061 return addRoute(lp, RouteInfo.makeHostRoute(addr));
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001062 } catch (UnknownHostException e) {}
1063 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001064 }
1065
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001066 private boolean addRoute(LinkProperties p, RouteInfo r) {
1067 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001068 }
1069
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001070 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1071 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1072 }
1073
1074 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1075 boolean doAdd) {
1076 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1077
1078 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1079 loge("Error adding route - too much recursion");
1080 return false;
1081 }
1082
1083 if (r.isHostRoute() == false) {
1084 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1085 if (bestRoute != null) {
1086 if (bestRoute.getGateway().equals(r.getGateway()) == false) {
1087 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
1088 } else {
1089 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
1090 }
1091 if (!modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd)) return false;
1092 }
1093 }
1094 if (doAdd) {
1095 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1096 mAddedRoutes.add(r);
1097 try {
1098 mNetd.addRoute(ifaceName, r);
1099 } catch (Exception e) {
1100 // never crash - catch them all
1101 loge("Exception trying to add a route: " + e);
1102 return false;
1103 }
1104 } else {
1105 // if we remove this one and there are no more like it, then refcount==0 and
1106 // we can remove it from the table
1107 mAddedRoutes.remove(r);
1108 if (mAddedRoutes.contains(r) == false) {
1109 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1110 try {
1111 mNetd.removeRoute(ifaceName, r);
1112 } catch (Exception e) {
1113 // never crash - catch them all
1114 loge("Exception trying to remove a route: " + e);
1115 return false;
1116 }
1117 } else {
1118 if (DBG) log("not removing " + r + " as it's still in use");
1119 }
1120 }
1121 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001122 }
1123
1124 /**
1125 * @see ConnectivityManager#getBackgroundDataSetting()
1126 */
1127 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001128 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001129 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001130
The Android Open Source Project28527d22009-03-03 19:31:44 -08001131 /**
1132 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1133 */
1134 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1135 mContext.enforceCallingOrSelfPermission(
1136 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1137 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001138
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001139 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1140
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001141 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1142 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1143 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001144
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001145 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001146 Settings.Secure.putInt(mContext.getContentResolver(),
1147 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1148 Intent broadcast = new Intent(
1149 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1150 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001151 }
1152
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001153 /**
1154 * @see ConnectivityManager#getMobileDataEnabled()
1155 */
1156 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001157 // TODO: This detail should probably be in DataConnectionTracker's
1158 // which is where we store the value and maybe make this
1159 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001160 enforceAccessPermission();
1161 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1162 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001163 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001164 return retVal;
1165 }
1166
Robert Greenwalt34848c02011-03-25 13:09:25 -07001167 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001168 enforceConnectivityInternalPermission();
1169
Robert Greenwalt34848c02011-03-25 13:09:25 -07001170 if (DBG) {
1171 log("setDataDependency(" + networkType + ", " + met + ")");
1172 }
1173 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1174 (met ? ENABLED : DISABLED), networkType));
1175 }
1176
1177 private void handleSetDependencyMet(int networkType, boolean met) {
1178 if (mNetTrackers[networkType] != null) {
1179 if (DBG) {
1180 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1181 }
1182 mNetTrackers[networkType].setDependencyMet(met);
1183 }
1184 }
1185
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001186 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1187 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001188 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001189 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001190 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001191
1192 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001193 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001194 }
1195
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001196 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001197 // skip update when we've already applied rules
1198 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1199 if (oldRules == uidRules) return;
1200
1201 mUidRules.put(uid, uidRules);
1202 }
1203
1204 // TODO: dispatch into NMS to push rules towards kernel module
1205 // TODO: notify UID when it has requested targeted updates
1206 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001207
1208 @Override
1209 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1210 // only someone like NPMS should only be calling us
1211 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1212
1213 if (LOGD_RULES) {
1214 Slog.d(TAG,
1215 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1216 }
1217
1218 synchronized (mRulesLock) {
1219 mMeteredIfaces.clear();
1220 for (String iface : meteredIfaces) {
1221 mMeteredIfaces.add(iface);
1222 }
1223 }
1224 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001225 };
1226
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001227 /**
1228 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1229 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001230 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001231 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001232 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001233
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001234 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001235 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001236 }
1237
1238 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001239 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1240 if (DBG) {
1241 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001242 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001243 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001244 }
1245 }
1246
The Android Open Source Project28527d22009-03-03 19:31:44 -08001247 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001248 mContext.enforceCallingOrSelfPermission(
1249 android.Manifest.permission.ACCESS_NETWORK_STATE,
1250 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001251 }
1252
1253 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001254 mContext.enforceCallingOrSelfPermission(
1255 android.Manifest.permission.CHANGE_NETWORK_STATE,
1256 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001257 }
1258
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001259 // TODO Make this a special check when it goes public
1260 private void enforceTetherChangePermission() {
1261 mContext.enforceCallingOrSelfPermission(
1262 android.Manifest.permission.CHANGE_NETWORK_STATE,
1263 "ConnectivityService");
1264 }
1265
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001266 private void enforceTetherAccessPermission() {
1267 mContext.enforceCallingOrSelfPermission(
1268 android.Manifest.permission.ACCESS_NETWORK_STATE,
1269 "ConnectivityService");
1270 }
1271
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001272 private void enforceConnectivityInternalPermission() {
1273 mContext.enforceCallingOrSelfPermission(
1274 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1275 "ConnectivityService");
1276 }
1277
The Android Open Source Project28527d22009-03-03 19:31:44 -08001278 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001279 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1280 * network, we ignore it. If it is for the active network, we send out a
1281 * broadcast. But first, we check whether it might be possible to connect
1282 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001283 * @param info the {@code NetworkInfo} for the network
1284 */
1285 private void handleDisconnect(NetworkInfo info) {
1286
Robert Greenwalt2034b912009-08-12 16:08:25 -07001287 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001288
Robert Greenwalt2034b912009-08-12 16:08:25 -07001289 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001290 /*
1291 * If the disconnected network is not the active one, then don't report
1292 * this as a loss of connectivity. What probably happened is that we're
1293 * getting the disconnect for a network that we explicitly disabled
1294 * in accordance with network preference policies.
1295 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001296 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001297 List pids = mNetRequestersPids[prevNetType];
1298 for (int i = 0; i<pids.size(); i++) {
1299 Integer pid = (Integer)pids.get(i);
1300 // will remove them because the net's no longer connected
1301 // need to do this now as only now do we know the pids and
1302 // can properly null things that are no longer referenced.
1303 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001304 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001305 }
1306
The Android Open Source Project28527d22009-03-03 19:31:44 -08001307 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1308 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1309 if (info.isFailover()) {
1310 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1311 info.setFailover(false);
1312 }
1313 if (info.getReason() != null) {
1314 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1315 }
1316 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001317 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1318 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001319 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001320
Robert Greenwalt34848c02011-03-25 13:09:25 -07001321 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001322 tryFailover(prevNetType);
1323 if (mActiveDefaultNetwork != -1) {
1324 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001325 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1326 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001327 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001328 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1329 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001330 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001331 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001332
1333 // Reset interface if no other connections are using the same interface
1334 boolean doReset = true;
1335 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1336 if (linkProperties != null) {
1337 String oldIface = linkProperties.getInterfaceName();
1338 if (TextUtils.isEmpty(oldIface) == false) {
1339 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1340 if (networkStateTracker == null) continue;
1341 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1342 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1343 LinkProperties l = networkStateTracker.getLinkProperties();
1344 if (l == null) continue;
1345 if (oldIface.equals(l.getInterfaceName())) {
1346 doReset = false;
1347 break;
1348 }
1349 }
1350 }
1351 }
1352 }
1353
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001354 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001355 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001356
1357 sendStickyBroadcast(intent);
1358 /*
1359 * If the failover network is already connected, then immediately send
1360 * out a followup broadcast indicating successful failover
1361 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001362 if (mActiveDefaultNetwork != -1) {
1363 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001364 }
1365 }
1366
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001367 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001368 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001369 * If this is a default network, check if other defaults are available.
1370 * Try to reconnect on all available and let them hash it out when
1371 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001372 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001373 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001374 if (mActiveDefaultNetwork == prevNetType) {
1375 mActiveDefaultNetwork = -1;
1376 }
1377
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001378 // don't signal a reconnect for anything lower or equal priority than our
1379 // current connected default
1380 // TODO - don't filter by priority now - nice optimization but risky
1381// int currentPriority = -1;
1382// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001383// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001384// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001385 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001386 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001387 if (mNetConfigs[checkType] == null) continue;
1388 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001389
1390// Enabling the isAvailable() optimization caused mobile to not get
1391// selected if it was in the middle of error handling. Specifically
1392// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1393// would not be available and we wouldn't get connected to anything.
1394// So removing the isAvailable() optimization below for now. TODO: This
1395// optimization should work and we need to investigate why it doesn't work.
1396// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1397// complete before it is really complete.
1398// if (!mNetTrackers[checkType].isAvailable()) continue;
1399
Robert Greenwalt34848c02011-03-25 13:09:25 -07001400// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001401
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001402 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1403 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1404 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1405 checkInfo.setFailover(true);
1406 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001407 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001408 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001409 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001410 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001411 }
1412
1413 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001414 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1415 }
1416
1417 private void sendInetConditionBroadcast(NetworkInfo info) {
1418 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1419 }
1420
1421 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1422 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001423 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1424 if (info.isFailover()) {
1425 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1426 info.setFailover(false);
1427 }
1428 if (info.getReason() != null) {
1429 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1430 }
1431 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001432 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1433 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001434 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001435 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001436 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 }
1438
1439 /**
1440 * Called when an attempt to fail over to another network has failed.
1441 * @param info the {@link NetworkInfo} for the failed network
1442 */
1443 private void handleConnectionFailure(NetworkInfo info) {
1444 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001445
Robert Greenwalt2034b912009-08-12 16:08:25 -07001446 String reason = info.getReason();
1447 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001448
Robert Greenwalte981bc52010-10-08 16:35:52 -07001449 String reasonText;
1450 if (reason == null) {
1451 reasonText = ".";
1452 } else {
1453 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001454 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001455 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001456
1457 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1458 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1459 if (getActiveNetworkInfo() == null) {
1460 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1461 }
1462 if (reason != null) {
1463 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1464 }
1465 if (extraInfo != null) {
1466 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1467 }
1468 if (info.isFailover()) {
1469 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1470 info.setFailover(false);
1471 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001472
Robert Greenwalt34848c02011-03-25 13:09:25 -07001473 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001474 tryFailover(info.getType());
1475 if (mActiveDefaultNetwork != -1) {
1476 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001477 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1478 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001479 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001480 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1481 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001482 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001483
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001484 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001485 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001486 /*
1487 * If the failover network is already connected, then immediately send
1488 * out a followup broadcast indicating successful failover
1489 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001490 if (mActiveDefaultNetwork != -1) {
1491 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001492 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001493 }
1494
1495 private void sendStickyBroadcast(Intent intent) {
1496 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001497 if (!mSystemReady) {
1498 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001499 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001500 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1501 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001502 }
1503 }
1504
1505 void systemReady() {
1506 synchronized(this) {
1507 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001508 if (mInitialBroadcast != null) {
1509 mContext.sendStickyBroadcast(mInitialBroadcast);
1510 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001511 }
1512 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001513 // load the global proxy at startup
1514 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001515 }
1516
1517 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001518 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001519
1520 // snapshot isFailover, because sendConnectedBroadcast() resets it
1521 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001522 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001523
Robert Greenwalt2034b912009-08-12 16:08:25 -07001524 // if this is a default net and other default is running
1525 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001526 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001527 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1528 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001529 mNetConfigs[mActiveDefaultNetwork].priority >
1530 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001531 mNetworkPreference == mActiveDefaultNetwork) {
1532 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001533 if (DBG) {
1534 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001535 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001536 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001537 teardown(thisNet);
1538 return;
1539 } else {
1540 // tear down the other
1541 NetworkStateTracker otherNet =
1542 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001543 if (DBG) {
1544 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001545 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001546 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001547 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001548 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001549 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001550 return;
1551 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001552 }
1553 }
1554 synchronized (ConnectivityService.this) {
1555 // have a new default network, release the transition wakelock in a second
1556 // if it's held. The second pause is to allow apps to reconnect over the
1557 // new network
1558 if (mNetTransitionWakeLock.isHeld()) {
1559 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001560 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001561 mNetTransitionWakeLockSerialNumber, 0),
1562 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001563 }
1564 }
1565 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001566 // this will cause us to come up initially as unconnected and switching
1567 // to connected after our normal pause unless somebody reports us as reall
1568 // disconnected
1569 mDefaultInetConditionPublished = 0;
1570 mDefaultConnectionSequence++;
1571 mInetConditionChangeInFlight = false;
1572 // Don't do this - if we never sign in stay, grey
1573 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001574 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001575 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001576 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001577 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001578 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001579 }
1580
The Android Open Source Project28527d22009-03-03 19:31:44 -08001581 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001582 * After a change in the connectivity state of a network. We're mainly
1583 * concerned with making sure that the list of DNS servers is set up
1584 * according to which networks are connected, and ensuring that the
1585 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001586 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001587 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001588 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1589
The Android Open Source Project28527d22009-03-03 19:31:44 -08001590 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001591 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001592 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001593 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001594 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001595
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001596 LinkProperties curLp = mCurrentLinkProperties[netType];
1597 LinkProperties newLp = null;
1598
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001599 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001600 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001601 if (VDBG) {
1602 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1603 " doReset=" + doReset + " resetMask=" + resetMask +
1604 "\n curLp=" + curLp +
1605 "\n newLp=" + newLp);
1606 }
1607
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001608 if (curLp != null) {
1609 if (curLp.isIdenticalInterfaceName(newLp)) {
1610 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1611 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1612 for (LinkAddress linkAddr : car.removed) {
1613 if (linkAddr.getAddress() instanceof Inet4Address) {
1614 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1615 }
1616 if (linkAddr.getAddress() instanceof Inet6Address) {
1617 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1618 }
Wink Saville051a6642011-07-13 13:44:13 -07001619 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001620 if (DBG) {
1621 log("handleConnectivityChange: addresses changed" +
1622 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1623 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001624 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001625 } else {
1626 if (DBG) {
1627 log("handleConnectivityChange: address are the same reset per doReset" +
1628 " linkProperty[" + netType + "]:" +
1629 " resetMask=" + resetMask);
1630 }
Wink Saville051a6642011-07-13 13:44:13 -07001631 }
1632 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001633 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1634 log("handleConnectivityChange: interface not not equivalent reset both" +
1635 " linkProperty[" + netType + "]:" +
1636 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001637 }
Wink Saville051a6642011-07-13 13:44:13 -07001638 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001639 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001640 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001641 }
1642 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001643 if (VDBG) {
1644 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1645 " doReset=" + doReset + " resetMask=" + resetMask +
1646 "\n curLp=" + curLp +
1647 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001648 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001649 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001650 mCurrentLinkProperties[netType] = newLp;
1651 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001652
Wink Saville051a6642011-07-13 13:44:13 -07001653 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001654 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1655 if (linkProperties != null) {
1656 String iface = linkProperties.getInterfaceName();
1657 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001658 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1659 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001660 }
1661 }
1662 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001663
1664 // TODO: Temporary notifying upstread change to Tethering.
1665 // @see bug/4455071
1666 /** Notify TetheringService if interface name has been changed. */
1667 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1668 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1669 if (isTetheringSupported()) {
1670 mTethering.handleTetherIfaceChange();
1671 }
1672 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001673 }
1674
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001675 /**
1676 * Add and remove routes using the old properties (null if not previously connected),
1677 * new properties (null if becoming disconnected). May even be double null, which
1678 * is a noop.
1679 * Uses isLinkDefault to determine if default routes should be set or conversely if
1680 * host routes should be set to the dns servers
1681 */
1682 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1683 Collection<RouteInfo> routesToAdd = null;
1684 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001685
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001686 if (curLp != null) {
1687 // check for the delta between the current set and the new
1688 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1689 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001690
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001691 for (RouteInfo r : routeDiff.removed) {
1692 if (isLinkDefault || ! r.isDefaultRoute()) {
1693 removeRoute(curLp, r);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001694 }
1695 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001696 routesToAdd = routeDiff.added;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001697 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001698
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001699 if (newLp != null) {
1700 // if we didn't get a diff from cur -> new, then just use the new
1701 if (routesToAdd == null) {
1702 routesToAdd = newLp.getRoutes();
1703 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001704
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001705 for (RouteInfo r : routesToAdd) {
1706 if (isLinkDefault || ! r.isDefaultRoute()) {
1707 addRoute(newLp, r);
1708 }
1709 }
1710 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001711
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001712 if (!isLinkDefault) {
1713 // handle DNS routes
1714 Collection<InetAddress> dnsToAdd = null;
1715 if (dnsDiff != null) {
1716 dnsToAdd = dnsDiff.added;
1717 for (InetAddress dnsAddress : dnsDiff.removed) {
1718 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1719 }
1720 }
1721 if (newLp != null) {
1722 if (dnsToAdd == null) {
1723 dnsToAdd = newLp.getDnses();
1724 }
1725 for(InetAddress dnsAddress : dnsToAdd) {
1726 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001727 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001728 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001729 }
1730 }
1731
1732
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001733 /**
1734 * Reads the network specific TCP buffer sizes from SystemProperties
1735 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1736 * wide use
1737 */
1738 public void updateNetworkSettings(NetworkStateTracker nt) {
1739 String key = nt.getTcpBufferSizesPropName();
1740 String bufferSizes = SystemProperties.get(key);
1741
1742 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001743 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001744
1745 // Setting to default values so we won't be stuck to previous values
1746 key = "net.tcp.buffersize.default";
1747 bufferSizes = SystemProperties.get(key);
1748 }
1749
1750 // Set values in kernel
1751 if (bufferSizes.length() != 0) {
1752 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001753 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001754 + "] which comes from [" + key + "]");
1755 }
1756 setBufferSize(bufferSizes);
1757 }
1758 }
1759
1760 /**
1761 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1762 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1763 *
1764 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1765 * writeMin, writeInitial, writeMax"
1766 */
1767 private void setBufferSize(String bufferSizes) {
1768 try {
1769 String[] values = bufferSizes.split(",");
1770
1771 if (values.length == 6) {
1772 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001773 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1774 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1775 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1776 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1777 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1778 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001779 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001780 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001781 }
1782 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001783 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001784 }
1785 }
1786
Robert Greenwalt2034b912009-08-12 16:08:25 -07001787 /**
1788 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1789 * on the highest priority active net which this process requested.
1790 * If there aren't any, clear it out
1791 */
1792 private void reassessPidDns(int myPid, boolean doBump)
1793 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001794 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001795 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001796 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001797 continue;
1798 }
1799 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001800 if (nt.getNetworkInfo().isConnected() &&
1801 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001802 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001803 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001804 List pids = mNetRequestersPids[i];
1805 for (int j=0; j<pids.size(); j++) {
1806 Integer pid = (Integer)pids.get(j);
1807 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001808 Collection<InetAddress> dnses = p.getDnses();
1809 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001810 if (doBump) {
1811 bumpDns();
1812 }
1813 return;
1814 }
1815 }
1816 }
1817 }
1818 // nothing found - delete
1819 for (int i = 1; ; i++) {
1820 String prop = "net.dns" + i + "." + myPid;
1821 if (SystemProperties.get(prop).length() == 0) {
1822 if (doBump) {
1823 bumpDns();
1824 }
1825 return;
1826 }
1827 SystemProperties.set(prop, "");
1828 }
1829 }
1830
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001831 // return true if results in a change
1832 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001833 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001834 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001835 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001836 String dnsString = dns.getHostAddress();
1837 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1838 changed = true;
1839 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1840 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001841 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001842 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001843 }
1844
1845 private void bumpDns() {
1846 /*
1847 * Bump the property that tells the name resolver library to reread
1848 * the DNS server list from the properties.
1849 */
1850 String propVal = SystemProperties.get("net.dnschange");
1851 int n = 0;
1852 if (propVal.length() != 0) {
1853 try {
1854 n = Integer.parseInt(propVal);
1855 } catch (NumberFormatException e) {}
1856 }
1857 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001858 /*
1859 * Tell the VMs to toss their DNS caches
1860 */
1861 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1862 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001863 /*
1864 * Connectivity events can happen before boot has completed ...
1865 */
1866 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001867 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001868 }
1869
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001870 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001871 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001872 NetworkStateTracker nt = mNetTrackers[netType];
1873 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001874 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001875 if (p == null) return;
1876 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001877 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001878 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001879 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001880 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001881 String dnsString = mDefaultDns.getHostAddress();
1882 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1883 if (DBG) {
1884 log("no dns provided - using " + dnsString);
1885 }
1886 changed = true;
1887 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001888 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001889 j++;
1890 } else {
1891 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001892 String dnsString = dns.getHostAddress();
1893 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1894 j++;
1895 continue;
1896 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001897 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001898 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001899 nt.getNetworkInfo().getTypeName());
1900 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001901 changed = true;
1902 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001903 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001904 }
1905 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001906 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1907 if (DBG) log("erasing net.dns" + k);
1908 changed = true;
1909 SystemProperties.set("net.dns" + k, "");
1910 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001911 }
1912 mNumDnsEntries = j;
1913 } else {
1914 // set per-pid dns for attached secondary nets
1915 List pids = mNetRequestersPids[netType];
1916 for (int y=0; y< pids.size(); y++) {
1917 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001918 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001919 }
1920 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001921 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001923 }
1924
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001925 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001926 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1927 NETWORK_RESTORE_DELAY_PROP_NAME);
1928 if(restoreDefaultNetworkDelayStr != null &&
1929 restoreDefaultNetworkDelayStr.length() != 0) {
1930 try {
1931 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1932 } catch (NumberFormatException e) {
1933 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001934 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001935 // if the system property isn't set, use the value for the apn type
1936 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1937
1938 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1939 (mNetConfigs[networkType] != null)) {
1940 ret = mNetConfigs[networkType].restoreTime;
1941 }
1942 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001943 }
1944
1945 @Override
1946 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001947 if (mContext.checkCallingOrSelfPermission(
1948 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001949 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001950 pw.println("Permission Denial: can't dump ConnectivityService " +
1951 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1952 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001953 return;
1954 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001955 pw.println();
1956 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001957 if (nst != null) {
1958 if (nst.getNetworkInfo().isConnected()) {
1959 pw.println("Active network: " + nst.getNetworkInfo().
1960 getTypeName());
1961 }
1962 pw.println(nst.getNetworkInfo());
1963 pw.println(nst);
1964 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001965 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001966 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001967
1968 pw.println("Network Requester Pids:");
1969 for (int net : mPriorityList) {
1970 String pidString = net + ": ";
1971 for (Object pid : mNetRequestersPids[net]) {
1972 pidString = pidString + pid.toString() + ", ";
1973 }
1974 pw.println(pidString);
1975 }
1976 pw.println();
1977
1978 pw.println("FeatureUsers:");
1979 for (Object requester : mFeatureUsers) {
1980 pw.println(requester.toString());
1981 }
1982 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001983
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001984 synchronized (this) {
1985 pw.println("NetworkTranstionWakeLock is currently " +
1986 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1987 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1988 }
1989 pw.println();
1990
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001991 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001992
1993 if (mInetLog != null) {
1994 pw.println();
1995 pw.println("Inet condition reports:");
1996 for(int i = 0; i < mInetLog.size(); i++) {
1997 pw.println(mInetLog.get(i));
1998 }
1999 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 }
2001
Robert Greenwalt2034b912009-08-12 16:08:25 -07002002 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002003 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002004 public MyHandler(Looper looper) {
2005 super(looper);
2006 }
2007
The Android Open Source Project28527d22009-03-03 19:31:44 -08002008 @Override
2009 public void handleMessage(Message msg) {
2010 NetworkInfo info;
2011 switch (msg.what) {
2012 case NetworkStateTracker.EVENT_STATE_CHANGED:
2013 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002014 int type = info.getType();
2015 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002016
Wink Savillee70c6f52010-12-03 12:01:38 -08002017 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002018 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002019 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002020
2021 // Connectivity state changed:
2022 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002023 // [12-9] Network subtype (for mobile network, as defined
2024 // by TelephonyManager)
2025 // [8-3] Detailed state ordinal (as defined by
2026 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002027 // [2-0] Network type (as defined by ConnectivityManager)
2028 int eventLogParam = (info.getType() & 0x7) |
2029 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2030 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002031 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002032 eventLogParam);
2033
2034 if (info.getDetailedState() ==
2035 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002036 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002037 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002038 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002039 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002041 // the logic here is, handle SUSPENDED the same as
2042 // DISCONNECTED. The only difference being we are
2043 // broadcasting an intent with NetworkInfo that's
2044 // suspended. This allows the applications an
2045 // opportunity to handle DISCONNECTED and SUSPENDED
2046 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002047 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002048 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002049 handleConnect(info);
2050 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002051 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002052 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002053 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002054 // TODO: Temporary allowing network configuration
2055 // change not resetting sockets.
2056 // @see bug/4455071
2057 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002058 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002059 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002060 String causedBy = null;
2061 synchronized (ConnectivityService.this) {
2062 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2063 mNetTransitionWakeLock.isHeld()) {
2064 mNetTransitionWakeLock.release();
2065 causedBy = mNetTransitionWakeLockCausedBy;
2066 }
2067 }
2068 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002069 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002070 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002071 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002072 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002073 FeatureUser u = (FeatureUser)msg.obj;
2074 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002075 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002076 case EVENT_INET_CONDITION_CHANGE:
2077 {
2078 int netType = msg.arg1;
2079 int condition = msg.arg2;
2080 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002081 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002082 }
2083 case EVENT_INET_CONDITION_HOLD_END:
2084 {
2085 int netType = msg.arg1;
2086 int sequence = msg.arg2;
2087 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002088 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002089 }
2090 case EVENT_SET_NETWORK_PREFERENCE:
2091 {
2092 int preference = msg.arg1;
2093 handleSetNetworkPreference(preference);
2094 break;
2095 }
2096 case EVENT_SET_BACKGROUND_DATA:
2097 {
2098 boolean enabled = (msg.arg1 == ENABLED);
2099 handleSetBackgroundData(enabled);
2100 break;
2101 }
2102 case EVENT_SET_MOBILE_DATA:
2103 {
2104 boolean enabled = (msg.arg1 == ENABLED);
2105 handleSetMobileData(enabled);
2106 break;
2107 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002108 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2109 {
2110 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002111 break;
2112 }
2113 case EVENT_SET_DEPENDENCY_MET:
2114 {
2115 boolean met = (msg.arg1 == ENABLED);
2116 handleSetDependencyMet(msg.arg2, met);
2117 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002118 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002119 }
2120 }
2121 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002122
2123 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002124 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002125 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002126
2127 if (isTetheringSupported()) {
2128 return mTethering.tether(iface);
2129 } else {
2130 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2131 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002132 }
2133
2134 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002135 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002136 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002137
2138 if (isTetheringSupported()) {
2139 return mTethering.untether(iface);
2140 } else {
2141 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2142 }
2143 }
2144
2145 // javadoc from interface
2146 public int getLastTetherError(String iface) {
2147 enforceTetherAccessPermission();
2148
2149 if (isTetheringSupported()) {
2150 return mTethering.getLastTetherError(iface);
2151 } else {
2152 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2153 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002154 }
2155
2156 // TODO - proper iface API for selection by property, inspection, etc
2157 public String[] getTetherableUsbRegexs() {
2158 enforceTetherAccessPermission();
2159 if (isTetheringSupported()) {
2160 return mTethering.getTetherableUsbRegexs();
2161 } else {
2162 return new String[0];
2163 }
2164 }
2165
2166 public String[] getTetherableWifiRegexs() {
2167 enforceTetherAccessPermission();
2168 if (isTetheringSupported()) {
2169 return mTethering.getTetherableWifiRegexs();
2170 } else {
2171 return new String[0];
2172 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002173 }
2174
Danica Chang96567052010-08-11 14:54:43 -07002175 public String[] getTetherableBluetoothRegexs() {
2176 enforceTetherAccessPermission();
2177 if (isTetheringSupported()) {
2178 return mTethering.getTetherableBluetoothRegexs();
2179 } else {
2180 return new String[0];
2181 }
2182 }
2183
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002184 // TODO - move iface listing, queries, etc to new module
2185 // javadoc from interface
2186 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002187 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002188 return mTethering.getTetherableIfaces();
2189 }
2190
2191 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002192 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002193 return mTethering.getTetheredIfaces();
2194 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002195
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002196 public String[] getTetheringErroredIfaces() {
2197 enforceTetherAccessPermission();
2198 return mTethering.getErroredIfaces();
2199 }
2200
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002201 // if ro.tether.denied = true we default to no tethering
2202 // gservices could set the secure setting to 1 though to enable it on a build where it
2203 // had previously been turned off.
2204 public boolean isTetheringSupported() {
2205 enforceTetherAccessPermission();
2206 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002207 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2208 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2209 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002210 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002211
2212 // An API NetworkStateTrackers can call when they lose their network.
2213 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2214 // whichever happens first. The timer is started by the first caller and not
2215 // restarted by subsequent callers.
2216 public void requestNetworkTransitionWakelock(String forWhom) {
2217 enforceConnectivityInternalPermission();
2218 synchronized (this) {
2219 if (mNetTransitionWakeLock.isHeld()) return;
2220 mNetTransitionWakeLockSerialNumber++;
2221 mNetTransitionWakeLock.acquire();
2222 mNetTransitionWakeLockCausedBy = forWhom;
2223 }
2224 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002225 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002226 mNetTransitionWakeLockSerialNumber, 0),
2227 mNetTransitionWakeLockTimeout);
2228 return;
2229 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002230
Robert Greenwalt986c7412010-09-08 15:24:47 -07002231 // 100 percent is full good, 0 is full bad.
2232 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002233 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002234 mContext.enforceCallingOrSelfPermission(
2235 android.Manifest.permission.STATUS_BAR,
2236 "ConnectivityService");
2237
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002238 if (DBG) {
2239 int pid = getCallingPid();
2240 int uid = getCallingUid();
2241 String s = pid + "(" + uid + ") reports inet is " +
2242 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2243 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2244 mInetLog.add(s);
2245 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2246 mInetLog.remove(0);
2247 }
2248 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002249 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002250 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2251 }
2252
2253 private void handleInetConditionChange(int netType, int condition) {
2254 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002255 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002256 netType + ", condition=" + condition +
2257 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2258 }
2259 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002260 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002261 return;
2262 }
2263 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002264 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002265 return;
2266 }
2267 mDefaultInetCondition = condition;
2268 int delay;
2269 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002270 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002271 // setup a new hold to debounce this
2272 if (mDefaultInetCondition > 50) {
2273 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2274 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2275 } else {
2276 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2277 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2278 }
2279 mInetConditionChangeInFlight = true;
2280 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2281 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2282 } else {
2283 // we've set the new condition, when this hold ends that will get
2284 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002285 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002286 }
2287 }
2288
2289 private void handleInetConditionHoldEnd(int netType, int sequence) {
2290 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002291 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002292 ", condition =" + mDefaultInetCondition +
2293 ", published condition =" + mDefaultInetConditionPublished);
2294 }
2295 mInetConditionChangeInFlight = false;
2296
2297 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002298 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002299 return;
2300 }
2301 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002302 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002303 return;
2304 }
2305 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002306 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002307 return;
2308 }
2309 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2310 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002311 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002312 return;
2313 }
2314 mDefaultInetConditionPublished = mDefaultInetCondition;
2315 sendInetConditionBroadcast(networkInfo);
2316 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002317 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002318
2319 public synchronized ProxyProperties getProxy() {
2320 if (mGlobalProxy != null) return mGlobalProxy;
2321 if (mDefaultProxy != null) return mDefaultProxy;
2322 return null;
2323 }
2324
2325 public void setGlobalProxy(ProxyProperties proxyProperties) {
2326 enforceChangePermission();
2327 synchronized (mGlobalProxyLock) {
2328 if (proxyProperties == mGlobalProxy) return;
2329 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2330 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2331
2332 String host = "";
2333 int port = 0;
2334 String exclList = "";
2335 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2336 mGlobalProxy = new ProxyProperties(proxyProperties);
2337 host = mGlobalProxy.getHost();
2338 port = mGlobalProxy.getPort();
2339 exclList = mGlobalProxy.getExclusionList();
2340 } else {
2341 mGlobalProxy = null;
2342 }
2343 ContentResolver res = mContext.getContentResolver();
2344 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2345 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002346 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002347 exclList);
2348 }
2349
2350 if (mGlobalProxy == null) {
2351 proxyProperties = mDefaultProxy;
2352 }
2353 sendProxyBroadcast(proxyProperties);
2354 }
2355
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002356 private void loadGlobalProxy() {
2357 ContentResolver res = mContext.getContentResolver();
2358 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2359 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2360 String exclList = Settings.Secure.getString(res,
2361 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2362 if (!TextUtils.isEmpty(host)) {
2363 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2364 synchronized (mGlobalProxyLock) {
2365 mGlobalProxy = proxyProperties;
2366 }
2367 }
2368 }
2369
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002370 public ProxyProperties getGlobalProxy() {
2371 synchronized (mGlobalProxyLock) {
2372 return mGlobalProxy;
2373 }
2374 }
2375
2376 private void handleApplyDefaultProxy(int type) {
2377 // check if new default - push it out to all VM if so
2378 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2379 synchronized (this) {
2380 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2381 if (mDefaultProxy == proxy) return;
2382 if (!TextUtils.isEmpty(proxy.getHost())) {
2383 mDefaultProxy = proxy;
2384 } else {
2385 mDefaultProxy = null;
2386 }
2387 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002388 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002389 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2390 if (mGlobalProxy != null) return;
2391 sendProxyBroadcast(proxy);
2392 }
2393
2394 private void handleDeprecatedGlobalHttpProxy() {
2395 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2396 Settings.Secure.HTTP_PROXY);
2397 if (!TextUtils.isEmpty(proxy)) {
2398 String data[] = proxy.split(":");
2399 String proxyHost = data[0];
2400 int proxyPort = 8080;
2401 if (data.length > 1) {
2402 try {
2403 proxyPort = Integer.parseInt(data[1]);
2404 } catch (NumberFormatException e) {
2405 return;
2406 }
2407 }
2408 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2409 setGlobalProxy(p);
2410 }
2411 }
2412
2413 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002414 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002415 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002416 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002417 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2418 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002419 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002420 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002421 }
2422
2423 private static class SettingsObserver extends ContentObserver {
2424 private int mWhat;
2425 private Handler mHandler;
2426 SettingsObserver(Handler handler, int what) {
2427 super(handler);
2428 mHandler = handler;
2429 mWhat = what;
2430 }
2431
2432 void observe(Context context) {
2433 ContentResolver resolver = context.getContentResolver();
2434 resolver.registerContentObserver(Settings.Secure.getUriFor(
2435 Settings.Secure.HTTP_PROXY), false, this);
2436 }
2437
2438 @Override
2439 public void onChange(boolean selfChange) {
2440 mHandler.obtainMessage(mWhat).sendToTarget();
2441 }
2442 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002443
2444 private void log(String s) {
2445 Slog.d(TAG, s);
2446 }
2447
2448 private void loge(String s) {
2449 Slog.e(TAG, s);
2450 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002451
Wink Savillef6b76692011-02-24 17:58:51 -08002452 int convertFeatureToNetworkType(String feature){
2453 int networkType = -1;
2454 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2455 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2456 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2457 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2458 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2459 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2460 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2461 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2462 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2463 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2464 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2465 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2466 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2467 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2468 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2469 }
2470 return networkType;
2471 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002472
2473 private static <T> T checkNotNull(T value, String message) {
2474 if (value == null) {
2475 throw new NullPointerException(message);
2476 }
2477 return value;
2478 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002479
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002480 /**
2481 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002482 * VpnBuilder and not available in ConnectivityManager. Permissions
2483 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002484 * @hide
2485 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002486 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002487 public boolean protectVpn(ParcelFileDescriptor socket) {
2488 try {
2489 int type = mActiveDefaultNetwork;
2490 if (ConnectivityManager.isNetworkTypeValid(type)) {
2491 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2492 return true;
2493 }
2494 } catch (Exception e) {
2495 // ignore
2496 } finally {
2497 try {
2498 socket.close();
2499 } catch (Exception e) {
2500 // ignore
2501 }
2502 }
2503 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002504 }
2505
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002506 /**
2507 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002508 * and not available in ConnectivityManager. Permissions are checked
2509 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002510 * @hide
2511 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002512 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002513 public boolean prepareVpn(String oldPackage, String newPackage) {
2514 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002515 }
2516
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002517 /**
2518 * Configure a TUN interface and return its file descriptor. Parameters
2519 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002520 * and not available in ConnectivityManager. Permissions are checked in
2521 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002522 * @hide
2523 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002524 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002525 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002526 return mVpn.establish(config);
2527 }
2528
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002529 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002530 * Start legacy VPN and return an intent to VpnDialogs. This method is
2531 * used by VpnSettings and not available in ConnectivityManager.
2532 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002533 * @hide
2534 */
2535 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002536 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2537 mVpn.startLegacyVpn(config, racoon, mtpd);
2538 }
2539
2540 /**
2541 * Return the information of the ongoing legacy VPN. This method is used
2542 * by VpnSettings and not available in ConnectivityManager. Permissions
2543 * are checked in Vpn class.
2544 * @hide
2545 */
2546 @Override
2547 public LegacyVpnInfo getLegacyVpnInfo() {
2548 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002549 }
2550
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002551 /**
2552 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2553 * through NetworkStateTracker since it works differently. For example, it
2554 * needs to override DNS servers but never takes the default routes. It
2555 * relies on another data network, and it could keep existing connections
2556 * alive after reconnecting, switching between networks, or even resuming
2557 * from deep sleep. Calls from applications should be done synchronously
2558 * to avoid race conditions. As these are all hidden APIs, refactoring can
2559 * be done whenever a better abstraction is developed.
2560 */
2561 public class VpnCallback {
2562
2563 private VpnCallback() {
2564 }
2565
Chia-chi Yehd050d1c2011-07-01 01:09:42 -07002566 public synchronized void override(List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002567 // TODO: override DNS servers and http proxy.
2568 }
2569
2570 public synchronized void restore() {
2571 // TODO: restore VPN changes.
2572 }
2573 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002574}