blob: c1d1f750307081250386a599a86860511d9e8b12 [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 Sharkey66fa9682011-08-02 17:22:34 -070043import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070044import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080045import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070046import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070047import android.net.Proxy;
48import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070049import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080050import android.net.wifi.WifiStateTracker;
51import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040052import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080053import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070054import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070055import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070056import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.os.Looper;
58import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070059import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070060import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070061import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.os.ServiceManager;
63import android.os.SystemProperties;
64import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070065import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080066import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080067import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070068import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070072import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080073import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070074import com.android.server.connectivity.Vpn;
75
Jeff Sharkey21062e72011-05-28 20:56:34 -070076import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070077import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080078
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070080import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070082import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070083import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070084import java.net.InetAddress;
85import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070086import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070087import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070088import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070089import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070090import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070092import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093
94/**
95 * @hide
96 */
97public class ConnectivityService extends IConnectivityManager.Stub {
98
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070099 private static final boolean DBG = true;
Wink Saville051a6642011-07-13 13:44:13 -0700100 private static final boolean VDBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101 private static final String TAG = "ConnectivityService";
102
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700103 private static final boolean LOGD_RULES = false;
104
Robert Greenwalt2034b912009-08-12 16:08:25 -0700105 // how long to wait before switching back to a radio's default network
106 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
107 // system property that can override the above value
108 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
109 "android.telephony.apn-restore";
110
Robert Greenwaltbd492212011-05-06 17:10:53 -0700111 // used in recursive route setting to add gateways for the host for which
112 // a host route was requested.
113 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
114
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800115 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800116 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800117
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700118 private Vpn mVpn;
119
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700120 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
121 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700122 /** Currently active network rules by UID. */
123 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700124 /** Set of ifaces that are costly. */
125 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700126
The Android Open Source Project28527d22009-03-03 19:31:44 -0800127 /**
128 * Sometimes we want to refer to the individual network state
129 * trackers separately, and sometimes we just want to treat them
130 * abstractly.
131 */
132 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700133
134 /**
Wink Saville051a6642011-07-13 13:44:13 -0700135 * The link properties that define the current links
136 */
137 private LinkProperties mCurrentLinkProperties[];
138
139 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700140 * A per Net list of the PID's that requested access to the net
141 * used both as a refcount and for per-PID DNS selection
142 */
143 private List mNetRequestersPids[];
144
Robert Greenwalt2034b912009-08-12 16:08:25 -0700145 // priority order of the nettrackers
146 // (excluding dynamically set mNetworkPreference)
147 // TODO - move mNetworkTypePreference into this
148 private int[] mPriorityList;
149
The Android Open Source Project28527d22009-03-03 19:31:44 -0800150 private Context mContext;
151 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700152 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700153 // 0 is full bad, 100 is full good
154 private int mDefaultInetCondition = 0;
155 private int mDefaultInetConditionPublished = 0;
156 private boolean mInetConditionChangeInFlight = false;
157 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158
Chia-chi Yehcc844502011-07-14 18:01:57 -0700159 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700161 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
163 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700164 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800165
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800166 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
167
Robert Greenwalt355205c2011-05-10 15:05:02 -0700168 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700169 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700170
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700171 private static final int ENABLED = 1;
172 private static final int DISABLED = 0;
173
174 // Share the event space with NetworkStateTracker (which can't see this
175 // internal class but sends us events). If you change these, change
176 // NetworkStateTracker.java too.
177 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
178 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
179
180 /**
181 * used internally as a delayed event to make us switch back to the
182 * default network
183 */
184 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
185 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
186
187 /**
188 * used internally to change our mobile data enabled flag
189 */
190 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
191 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
192
193 /**
194 * used internally to change our network preference setting
195 * arg1 = networkType to prefer
196 */
197 private static final int EVENT_SET_NETWORK_PREFERENCE =
198 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
199
200 /**
201 * used internally to synchronize inet condition reports
202 * arg1 = networkType
203 * arg2 = condition (0 bad, 100 good)
204 */
205 private static final int EVENT_INET_CONDITION_CHANGE =
206 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
207
208 /**
209 * used internally to mark the end of inet condition hold periods
210 * arg1 = networkType
211 */
212 private static final int EVENT_INET_CONDITION_HOLD_END =
213 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
214
215 /**
216 * used internally to set the background data preference
217 * arg1 = TRUE for enabled, FALSE for disabled
218 */
219 private static final int EVENT_SET_BACKGROUND_DATA =
220 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
221
222 /**
223 * used internally to set enable/disable cellular data
224 * arg1 = ENBALED or DISABLED
225 */
226 private static final int EVENT_SET_MOBILE_DATA =
227 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
228
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700229 /**
230 * used internally to clear a wakelock when transitioning
231 * from one net to another
232 */
233 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
234 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
235
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700236 /**
237 * used internally to reload global proxy settings
238 */
239 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
240 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
241
Robert Greenwalt34848c02011-03-25 13:09:25 -0700242 /**
243 * used internally to set external dependency met/unmet
244 * arg1 = ENABLED (met) or DISABLED (unmet)
245 * arg2 = NetworkType
246 */
247 private static final int EVENT_SET_DEPENDENCY_MET =
248 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
249
Chia-chi Yehcc844502011-07-14 18:01:57 -0700250 /**
251 * used internally to restore DNS properties back to the
252 * default network
253 */
254 private static final int EVENT_RESTORE_DNS =
255 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
256
Robert Greenwalt2034b912009-08-12 16:08:25 -0700257 private Handler mHandler;
258
259 // list of DeathRecipients used to make sure features are turned off when
260 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500261 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700262
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400263 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800264 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400265
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700266 private PowerManager.WakeLock mNetTransitionWakeLock;
267 private String mNetTransitionWakeLockCausedBy = "";
268 private int mNetTransitionWakeLockSerialNumber;
269 private int mNetTransitionWakeLockTimeout;
270
Robert Greenwalt94daa182010-09-01 11:34:05 -0700271 private InetAddress mDefaultDns;
272
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700273 // this collection is used to refcount the added routes - if there are none left
274 // it's time to remove the route from the route table
275 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
276
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700277 // used in DBG mode to track inet condition reports
278 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
279 private ArrayList mInetLog;
280
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700281 // track the current default http proxy - tell the world if we get a new one (real change)
282 private ProxyProperties mDefaultProxy = null;
283 // track the global proxy.
284 private ProxyProperties mGlobalProxy = null;
285 private final Object mGlobalProxyLock = new Object();
286
287 private SettingsObserver mSettingsObserver;
288
Robert Greenwalt34848c02011-03-25 13:09:25 -0700289 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700290 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700291
Robert Greenwalt12c44552009-12-07 11:33:18 -0800292 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700293 public int mSimultaneity;
294 public int mType;
295 public RadioAttributes(String init) {
296 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700297 mType = Integer.parseInt(fragments[0]);
298 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700299 }
300 }
301 RadioAttributes[] mRadioAttributes;
302
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700303 // the set of network types that can only be enabled by system/sig apps
304 List mProtectedNetworks;
305
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700306 public ConnectivityService(
307 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800308 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800309
Wink Saville775aad62010-09-02 19:23:52 -0700310 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
311 handlerThread.start();
312 mHandler = new MyHandler(handlerThread.getLooper());
313
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800314 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
315 Settings.Secure.BACKGROUND_DATA, 1) == 1);
316
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800317 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800318 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
319 String id = Settings.Secure.getString(context.getContentResolver(),
320 Settings.Secure.ANDROID_ID);
321 if (id != null && id.length() > 0) {
322 String name = new String("android_").concat(id);
323 SystemProperties.set("net.hostname", name);
324 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800325 }
326
Robert Greenwalt94daa182010-09-01 11:34:05 -0700327 // read our default dns server ip
328 String dns = Settings.Secure.getString(context.getContentResolver(),
329 Settings.Secure.DEFAULT_DNS_SERVER);
330 if (dns == null || dns.length() == 0) {
331 dns = context.getResources().getString(
332 com.android.internal.R.string.config_default_dns_server);
333 }
334 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800335 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
336 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800337 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700338 }
339
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700340 mContext = checkNotNull(context, "missing Context");
341 mNetd = checkNotNull(netd, "missing INetworkManagementService");
342 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700343
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700344 try {
345 mPolicyManager.registerListener(mPolicyListener);
346 } catch (RemoteException e) {
347 // ouch, no rules updates means some processes may never get network
348 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
349 }
350
351 final PowerManager powerManager = (PowerManager) context.getSystemService(
352 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700353 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
354 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
355 com.android.internal.R.integer.config_networkTransitionTimeout);
356
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 mNetTrackers = new NetworkStateTracker[
358 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700359 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700360
The Android Open Source Project28527d22009-03-03 19:31:44 -0800361 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700362
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700364 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700365
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367 String[] raStrings = context.getResources().getStringArray(
368 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700369 for (String raString : raStrings) {
370 RadioAttributes r = new RadioAttributes(raString);
371 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800372 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 continue;
374 }
375 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800376 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700377 r.mType);
378 continue;
379 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700380 mRadioAttributes[r.mType] = r;
381 }
382
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700383 String[] naStrings = context.getResources().getStringArray(
384 com.android.internal.R.array.networkAttributes);
385 for (String naString : naStrings) {
386 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700387 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700388 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700390 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700392 }
Wink Savillef2a62832011-04-07 14:23:45 -0700393 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800394 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700395 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700396 continue;
397 }
Wink Savillef2a62832011-04-07 14:23:45 -0700398 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800399 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700400 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700401 continue;
402 }
Wink Savillef2a62832011-04-07 14:23:45 -0700403 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700404 mNetworksDefined++;
405 } catch(Exception e) {
406 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700407 }
408 }
409
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700410 mProtectedNetworks = new ArrayList<Integer>();
411 int[] protectedNetworks = context.getResources().getIntArray(
412 com.android.internal.R.array.config_protectedNetworks);
413 for (int p : protectedNetworks) {
414 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
415 mProtectedNetworks.add(p);
416 } else {
417 if (DBG) loge("Ignoring protectedNetwork " + p);
418 }
419 }
420
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700421 // high priority first
422 mPriorityList = new int[mNetworksDefined];
423 {
424 int insertionPoint = mNetworksDefined-1;
425 int currentLowest = 0;
426 int nextLowest = 0;
427 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700428 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700429 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700430 if (na.priority < currentLowest) continue;
431 if (na.priority > currentLowest) {
432 if (na.priority < nextLowest || nextLowest == 0) {
433 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700434 }
435 continue;
436 }
Wink Savillef2a62832011-04-07 14:23:45 -0700437 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700438 }
439 currentLowest = nextLowest;
440 nextLowest = 0;
441 }
442 }
443
444 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
445 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700446 mNetRequestersPids[i] = new ArrayList();
447 }
448
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500449 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700450
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700451 mNumDnsEntries = 0;
452
453 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
454 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800455 /*
456 * Create the network state trackers for Wi-Fi and mobile
457 * data. Maybe this could be done with a factory class,
458 * but it's not clear that it's worth it, given that
459 * the number of different network types is not going
460 * to change very often.
461 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700463 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700464 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800465 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700466 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700467 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700468 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700469 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700470 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700471 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700472 break;
473 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700474 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700475 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700476 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700477 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800478 case ConnectivityManager.TYPE_DUMMY:
479 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700480 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800481 mNetTrackers[netType].startMonitoring(context, mHandler);
482 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800483 case ConnectivityManager.TYPE_BLUETOOTH:
484 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800487 case ConnectivityManager.TYPE_ETHERNET:
488 mNetTrackers[netType] = EthernetDataTracker.getInstance();
489 mNetTrackers[netType].startMonitoring(context, mHandler);
490 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700491 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800492 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700493 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700494 continue;
495 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700496 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700497 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700498 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800499
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700500 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
501 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
502
503 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700504 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700505 mTethering.getTetherableWifiRegexs().length != 0 ||
506 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700507 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800508
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700509 mVpn = new Vpn(mContext, new VpnCallback());
510
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700511 try {
512 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700513 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700514 } catch (RemoteException e) {
515 loge("Error registering observer :" + e);
516 }
517
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700518 if (DBG) {
519 mInetLog = new ArrayList();
520 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700521
522 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
523 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800524
525 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800526 }
527
528 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700529 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800530 * @param preference the new preference
531 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700532 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800533 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700534
535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800536 }
537
538 public int getNetworkPreference() {
539 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700540 int preference;
541 synchronized(this) {
542 preference = mNetworkPreference;
543 }
544 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800545 }
546
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700547 private void handleSetNetworkPreference(int preference) {
548 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700549 mNetConfigs[preference] != null &&
550 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700551 if (mNetworkPreference != preference) {
552 final ContentResolver cr = mContext.getContentResolver();
553 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
554 synchronized(this) {
555 mNetworkPreference = preference;
556 }
557 enforcePreference();
558 }
559 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800560 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700561
The Android Open Source Project28527d22009-03-03 19:31:44 -0800562 private int getPersistedNetworkPreference() {
563 final ContentResolver cr = mContext.getContentResolver();
564
565 final int networkPrefSetting = Settings.Secure
566 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
567 if (networkPrefSetting != -1) {
568 return networkPrefSetting;
569 }
570
571 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
572 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700573
The Android Open Source Project28527d22009-03-03 19:31:44 -0800574 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700575 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800576 * In this method, we only tear down a non-preferred network. Establishing
577 * a connection to the preferred network is taken care of when we handle
578 * the disconnect event from the non-preferred network
579 * (see {@link #handleDisconnect(NetworkInfo)}).
580 */
581 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700582 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800583 return;
584
Robert Greenwalt2034b912009-08-12 16:08:25 -0700585 if (!mNetTrackers[mNetworkPreference].isAvailable())
586 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800587
Robert Greenwalt2034b912009-08-12 16:08:25 -0700588 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700589 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700590 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700591 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800592 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700593 " in enforcePreference");
594 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700595 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800596 }
597 }
598 }
599
600 private boolean teardown(NetworkStateTracker netTracker) {
601 if (netTracker.teardown()) {
602 netTracker.setTeardownRequested(true);
603 return true;
604 } else {
605 return false;
606 }
607 }
608
609 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700610 * Check if UID should be blocked from using the network represented by the
611 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700612 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700613 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
614 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700615
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700616 final boolean networkCostly;
617 final int uidRules;
618 synchronized (mRulesLock) {
619 networkCostly = mMeteredIfaces.contains(iface);
620 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700621 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700622
623 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
624 return true;
625 }
626
627 // no restrictive rules; network is visible
628 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700629 }
630
631 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700632 * Return a filtered {@link NetworkInfo}, potentially marked
633 * {@link DetailedState#BLOCKED} based on
634 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700635 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700636 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
637 NetworkInfo info = tracker.getNetworkInfo();
638 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700639 // network is blocked; clone and override state
640 info = new NetworkInfo(info);
641 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700642 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700643 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700644 }
645
646 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800647 * Return NetworkInfo for the active (i.e., connected) network interface.
648 * It is assumed that at most one network is active at a time. If more
649 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700650 * @return the info for the active network, or {@code null} if none is
651 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800652 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700653 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800654 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700655 enforceAccessPermission();
656 final int uid = Binder.getCallingUid();
657 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800658 }
659
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700660 @Override
661 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
662 enforceConnectivityInternalPermission();
663 return getNetworkInfo(mActiveDefaultNetwork, uid);
664 }
665
666 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800667 public NetworkInfo getNetworkInfo(int networkType) {
668 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700669 final int uid = Binder.getCallingUid();
670 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800671 }
672
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700673 private NetworkInfo getNetworkInfo(int networkType, int uid) {
674 NetworkInfo info = null;
675 if (isNetworkTypeValid(networkType)) {
676 final NetworkStateTracker tracker = mNetTrackers[networkType];
677 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700678 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700679 }
680 }
681 return info;
682 }
683
684 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800685 public NetworkInfo[] getAllNetworkInfo() {
686 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700687 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700688 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700689 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700690 for (NetworkStateTracker tracker : mNetTrackers) {
691 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700692 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700693 }
694 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800695 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700696 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800697 }
698
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700699 /**
700 * Return LinkProperties for the active (i.e., connected) default
701 * network interface. It is assumed that at most one default network
702 * is active at a time. If more than one is active, it is indeterminate
703 * which will be returned.
704 * @return the ip properties for the active network, or {@code null} if
705 * none is active
706 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700707 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700708 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700709 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700710 }
711
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700712 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700713 public LinkProperties getLinkProperties(int networkType) {
714 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700715 if (isNetworkTypeValid(networkType)) {
716 final NetworkStateTracker tracker = mNetTrackers[networkType];
717 if (tracker != null) {
718 return tracker.getLinkProperties();
719 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700720 }
721 return null;
722 }
723
Jeff Sharkey21062e72011-05-28 20:56:34 -0700724 @Override
725 public NetworkState[] getAllNetworkState() {
726 enforceAccessPermission();
727 final int uid = Binder.getCallingUid();
728 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700729 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700730 for (NetworkStateTracker tracker : mNetTrackers) {
731 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700732 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700733 result.add(new NetworkState(
734 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
735 }
736 }
737 }
738 return result.toArray(new NetworkState[result.size()]);
739 }
740
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700741 private NetworkState getNetworkStateUnchecked(int networkType) {
742 if (isNetworkTypeValid(networkType)) {
743 final NetworkStateTracker tracker = mNetTrackers[networkType];
744 if (tracker != null) {
745 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
746 tracker.getLinkCapabilities());
747 }
748 }
749 return null;
750 }
751
752 @Override
753 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
754 enforceAccessPermission();
755 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
756 if (state != null) {
757 try {
758 return mPolicyManager.getNetworkQuotaInfo(state);
759 } catch (RemoteException e) {
760 }
761 }
762 return null;
763 }
764
The Android Open Source Project28527d22009-03-03 19:31:44 -0800765 public boolean setRadios(boolean turnOn) {
766 boolean result = true;
767 enforceChangePermission();
768 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700769 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800770 }
771 return result;
772 }
773
774 public boolean setRadio(int netType, boolean turnOn) {
775 enforceChangePermission();
776 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
777 return false;
778 }
779 NetworkStateTracker tracker = mNetTrackers[netType];
780 return tracker != null && tracker.setRadio(turnOn);
781 }
782
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700783 /**
784 * Used to notice when the calling process dies so we can self-expire
785 *
786 * Also used to know if the process has cleaned up after itself when
787 * our auto-expire timer goes off. The timer has a link to an object.
788 *
789 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700790 private class FeatureUser implements IBinder.DeathRecipient {
791 int mNetworkType;
792 String mFeature;
793 IBinder mBinder;
794 int mPid;
795 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800796 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797
798 FeatureUser(int type, String feature, IBinder binder) {
799 super();
800 mNetworkType = type;
801 mFeature = feature;
802 mBinder = binder;
803 mPid = getCallingPid();
804 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800805 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700806
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 try {
808 mBinder.linkToDeath(this, 0);
809 } catch (RemoteException e) {
810 binderDied();
811 }
812 }
813
814 void unlinkDeathRecipient() {
815 mBinder.unlinkToDeath(this, 0);
816 }
817
818 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800819 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800820 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
821 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700822 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700823 }
824
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700825 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800826 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800827 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
828 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700829 stopUsingNetworkFeature(this, false);
830 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800831
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500832 public boolean isSameUser(FeatureUser u) {
833 if (u == null) return false;
834
835 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
836 }
837
838 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
839 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
840 TextUtils.equals(mFeature, feature)) {
841 return true;
842 }
843 return false;
844 }
845
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800846 public String toString() {
847 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
848 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
849 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700850 }
851
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700852 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700853 public int startUsingNetworkFeature(int networkType, String feature,
854 IBinder binder) {
855 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800856 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700857 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800858 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700859 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700860 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700861 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800862 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700863
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700864 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700865
866 // TODO - move this into the MobileDataStateTracker
867 int usedNetworkType = networkType;
868 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800869 usedNetworkType = convertFeatureToNetworkType(feature);
870 if (usedNetworkType < 0) {
871 Slog.e(TAG, "Can't match any netTracker!");
872 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700873 }
874 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700875
876 if (mProtectedNetworks.contains(usedNetworkType)) {
877 enforceConnectivityInternalPermission();
878 }
879
Robert Greenwalt2034b912009-08-12 16:08:25 -0700880 NetworkStateTracker network = mNetTrackers[usedNetworkType];
881 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800882 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700883 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700884 NetworkStateTracker radio = mNetTrackers[networkType];
885 NetworkInfo ni = network.getNetworkInfo();
886
887 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800888 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800889 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
890 return Phone.APN_TYPE_NOT_AVAILABLE;
891 } else {
892 // else make the attempt anyway - probably giving REQUEST_STARTED below
893 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700894 }
895
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500896 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
897
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700898 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500899 boolean addToList = true;
900 if (restoreTimer < 0) {
901 // In case there is no timer is specified for the feature,
902 // make sure we don't add duplicate entry with the same request.
903 for (FeatureUser u : mFeatureUsers) {
904 if (u.isSameUser(f)) {
905 // Duplicate user is found. Do not add.
906 addToList = false;
907 break;
908 }
909 }
910 }
911
912 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700913 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
914 // this gets used for per-pid dns when connected
915 mNetRequestersPids[usedNetworkType].add(currentPid);
916 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700917 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700918
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700919 if (restoreTimer >= 0) {
920 mHandler.sendMessageDelayed(
921 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
922 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700923
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700924 if ((ni.isConnectedOrConnecting() == true) &&
925 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700926 if (ni.isConnected() == true) {
927 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700928 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800929 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700930 return Phone.APN_ALREADY_ACTIVE;
931 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800932 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700933 return Phone.APN_REQUEST_STARTED;
934 }
935
936 // check if the radio in play can make another contact
937 // assume if cannot for now
938
Wink Savillee70c6f52010-12-03 12:01:38 -0800939 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700940 network.reconnect();
941 return Phone.APN_REQUEST_STARTED;
942 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800943 // need to remember this unsupported request so we respond appropriately on stop
944 synchronized(this) {
945 mFeatureUsers.add(f);
946 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
947 // this gets used for per-pid dns when connected
948 mNetRequestersPids[usedNetworkType].add(currentPid);
949 }
950 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700951 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700952 }
953 }
954 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800955 }
956
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700957 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800958 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700959 enforceChangePermission();
960
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700961 int pid = getCallingPid();
962 int uid = getCallingUid();
963
964 FeatureUser u = null;
965 boolean found = false;
966
967 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500968 for (FeatureUser x : mFeatureUsers) {
969 if (x.isSameUser(pid, uid, networkType, feature)) {
970 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700971 found = true;
972 break;
973 }
974 }
975 }
976 if (found && u != null) {
977 // stop regardless of how many other time this proc had called start
978 return stopUsingNetworkFeature(u, true);
979 } else {
980 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800981 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700982 return 1;
983 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700984 }
985
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700986 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
987 int networkType = u.mNetworkType;
988 String feature = u.mFeature;
989 int pid = u.mPid;
990 int uid = u.mUid;
991
992 NetworkStateTracker tracker = null;
993 boolean callTeardown = false; // used to carry our decision outside of sync block
994
Robert Greenwalt2034b912009-08-12 16:08:25 -0700995 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800996 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700997 ": " + feature);
998 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700999
The Android Open Source Project28527d22009-03-03 19:31:44 -08001000 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1001 return -1;
1002 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001003
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001004 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1005 // sync block
1006 synchronized(this) {
1007 // check if this process still has an outstanding start request
1008 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001009 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001010 return 1;
1011 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001012 u.unlinkDeathRecipient();
1013 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1014 // If we care about duplicate requests, check for that here.
1015 //
1016 // This is done to support the extension of a request - the app
1017 // can request we start the network feature again and renew the
1018 // auto-shutoff delay. Normal "stop" calls from the app though
1019 // do not pay attention to duplicate requests - in effect the
1020 // API does not refcount and a single stop will counter multiple starts.
1021 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001022 for (FeatureUser x : mFeatureUsers) {
1023 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001024 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001025 return 1;
1026 }
1027 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001028 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001029
1030 // TODO - move to MobileDataStateTracker
1031 int usedNetworkType = networkType;
1032 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -08001033 usedNetworkType = convertFeatureToNetworkType(feature);
1034 if (usedNetworkType < 0) {
1035 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001036 }
1037 }
1038 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001039 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001040 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001041 return -1;
1042 }
1043 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001044 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001045 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001046 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001047 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001048 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001049 "others still using it");
1050 return 1;
1051 }
1052 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001053 } else {
1054 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001055 }
1056 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001057 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001058 if (callTeardown) {
1059 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001060 return 1;
1061 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001062 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001063 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001064 }
1065
1066 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001067 * @deprecated use requestRouteToHostAddress instead
1068 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001069 * Ensure that a network route exists to deliver traffic to the specified
1070 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001071 * @param networkType the type of the network over which traffic to the
1072 * specified host is to be routed
1073 * @param hostAddress the IP address of the host to which the route is
1074 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001075 * @return {@code true} on success, {@code false} on failure
1076 */
1077 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001078 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1079
1080 if (inetAddress == null) {
1081 return false;
1082 }
1083
1084 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1085 }
1086
1087 /**
1088 * Ensure that a network route exists to deliver traffic to the specified
1089 * host via the specified network interface.
1090 * @param networkType the type of the network over which traffic to the
1091 * specified host is to be routed
1092 * @param hostAddress the IP address of the host to which the route is
1093 * desired
1094 * @return {@code true} on success, {@code false} on failure
1095 */
1096 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001097 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001098 if (mProtectedNetworks.contains(networkType)) {
1099 enforceConnectivityInternalPermission();
1100 }
1101
The Android Open Source Project28527d22009-03-03 19:31:44 -08001102 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1103 return false;
1104 }
1105 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001106
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001107 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1108 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001109 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001110 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001111 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001112 }
1113 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001114 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001115 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001116 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001117 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001118 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001119 } catch (UnknownHostException e) {}
1120 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001121 }
1122
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001123 private boolean addRoute(LinkProperties p, RouteInfo r) {
1124 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001125 }
1126
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001127 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1128 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1129 }
1130
Robert Greenwalt98107422011-07-22 11:55:33 -07001131 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1132 return modifyRouteToAddress(lp, addr, true);
1133 }
1134
1135 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1136 return modifyRouteToAddress(lp, addr, false);
1137 }
1138
1139 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1140 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1141 if (bestRoute == null) {
1142 bestRoute = RouteInfo.makeHostRoute(addr);
1143 } else {
1144 if (bestRoute.getGateway().equals(addr)) {
1145 // if there is no better route, add the implied hostroute for our gateway
1146 bestRoute = RouteInfo.makeHostRoute(addr);
1147 } else {
1148 // if we will connect to this through another route, add a direct route
1149 // to it's gateway
1150 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1151 }
1152 }
1153 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1154 }
1155
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001156 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1157 boolean doAdd) {
1158 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1159
1160 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1161 loge("Error adding route - too much recursion");
1162 return false;
1163 }
1164
1165 if (r.isHostRoute() == false) {
1166 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1167 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001168 if (bestRoute.getGateway().equals(r.getGateway())) {
1169 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001170 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001171 } else {
1172 // if we will connect to our gateway through another route, add a direct
1173 // route to it's gateway
1174 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001175 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001176 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001177 }
1178 }
1179 if (doAdd) {
1180 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1181 mAddedRoutes.add(r);
1182 try {
1183 mNetd.addRoute(ifaceName, r);
1184 } catch (Exception e) {
1185 // never crash - catch them all
1186 loge("Exception trying to add a route: " + e);
1187 return false;
1188 }
1189 } else {
1190 // if we remove this one and there are no more like it, then refcount==0 and
1191 // we can remove it from the table
1192 mAddedRoutes.remove(r);
1193 if (mAddedRoutes.contains(r) == false) {
1194 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1195 try {
1196 mNetd.removeRoute(ifaceName, r);
1197 } catch (Exception e) {
1198 // never crash - catch them all
1199 loge("Exception trying to remove a route: " + e);
1200 return false;
1201 }
1202 } else {
1203 if (DBG) log("not removing " + r + " as it's still in use");
1204 }
1205 }
1206 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001207 }
1208
1209 /**
1210 * @see ConnectivityManager#getBackgroundDataSetting()
1211 */
1212 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001213 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001214 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001215
The Android Open Source Project28527d22009-03-03 19:31:44 -08001216 /**
1217 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1218 */
1219 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1220 mContext.enforceCallingOrSelfPermission(
1221 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1222 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001223
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001224 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1225
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001226 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1227 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1228 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001229
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001230 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001231 Settings.Secure.putInt(mContext.getContentResolver(),
1232 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1233 Intent broadcast = new Intent(
1234 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1235 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001236 }
1237
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001238 /**
1239 * @see ConnectivityManager#getMobileDataEnabled()
1240 */
1241 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001242 // TODO: This detail should probably be in DataConnectionTracker's
1243 // which is where we store the value and maybe make this
1244 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001245 enforceAccessPermission();
1246 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1247 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001248 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001249 return retVal;
1250 }
1251
Robert Greenwalt34848c02011-03-25 13:09:25 -07001252 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001253 enforceConnectivityInternalPermission();
1254
Robert Greenwalt34848c02011-03-25 13:09:25 -07001255 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1256 (met ? ENABLED : DISABLED), networkType));
1257 }
1258
1259 private void handleSetDependencyMet(int networkType, boolean met) {
1260 if (mNetTrackers[networkType] != null) {
1261 if (DBG) {
1262 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1263 }
1264 mNetTrackers[networkType].setDependencyMet(met);
1265 }
1266 }
1267
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001268 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1269 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001270 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001271 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001272 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001273
1274 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001275 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001276 }
1277
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001278 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001279 // skip update when we've already applied rules
1280 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1281 if (oldRules == uidRules) return;
1282
1283 mUidRules.put(uid, uidRules);
1284 }
1285
1286 // TODO: dispatch into NMS to push rules towards kernel module
1287 // TODO: notify UID when it has requested targeted updates
1288 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001289
1290 @Override
1291 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1292 // only someone like NPMS should only be calling us
1293 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1294
1295 if (LOGD_RULES) {
1296 Slog.d(TAG,
1297 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1298 }
1299
1300 synchronized (mRulesLock) {
1301 mMeteredIfaces.clear();
1302 for (String iface : meteredIfaces) {
1303 mMeteredIfaces.add(iface);
1304 }
1305 }
1306 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001307 };
1308
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001309 /**
1310 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1311 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001312 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001313 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001314 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001315
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001316 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001317 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001318 }
1319
1320 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001321 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1322 if (DBG) {
1323 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001324 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001325 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001326 }
1327 }
1328
The Android Open Source Project28527d22009-03-03 19:31:44 -08001329 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001330 mContext.enforceCallingOrSelfPermission(
1331 android.Manifest.permission.ACCESS_NETWORK_STATE,
1332 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001333 }
1334
1335 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001336 mContext.enforceCallingOrSelfPermission(
1337 android.Manifest.permission.CHANGE_NETWORK_STATE,
1338 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001339 }
1340
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001341 // TODO Make this a special check when it goes public
1342 private void enforceTetherChangePermission() {
1343 mContext.enforceCallingOrSelfPermission(
1344 android.Manifest.permission.CHANGE_NETWORK_STATE,
1345 "ConnectivityService");
1346 }
1347
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001348 private void enforceTetherAccessPermission() {
1349 mContext.enforceCallingOrSelfPermission(
1350 android.Manifest.permission.ACCESS_NETWORK_STATE,
1351 "ConnectivityService");
1352 }
1353
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001354 private void enforceConnectivityInternalPermission() {
1355 mContext.enforceCallingOrSelfPermission(
1356 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1357 "ConnectivityService");
1358 }
1359
The Android Open Source Project28527d22009-03-03 19:31:44 -08001360 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001361 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1362 * network, we ignore it. If it is for the active network, we send out a
1363 * broadcast. But first, we check whether it might be possible to connect
1364 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001365 * @param info the {@code NetworkInfo} for the network
1366 */
1367 private void handleDisconnect(NetworkInfo info) {
1368
Robert Greenwalt2034b912009-08-12 16:08:25 -07001369 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001370
Robert Greenwalt2034b912009-08-12 16:08:25 -07001371 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001372 /*
1373 * If the disconnected network is not the active one, then don't report
1374 * this as a loss of connectivity. What probably happened is that we're
1375 * getting the disconnect for a network that we explicitly disabled
1376 * in accordance with network preference policies.
1377 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001378 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001379 List pids = mNetRequestersPids[prevNetType];
1380 for (int i = 0; i<pids.size(); i++) {
1381 Integer pid = (Integer)pids.get(i);
1382 // will remove them because the net's no longer connected
1383 // need to do this now as only now do we know the pids and
1384 // can properly null things that are no longer referenced.
1385 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001386 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001387 }
1388
The Android Open Source Project28527d22009-03-03 19:31:44 -08001389 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1390 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1391 if (info.isFailover()) {
1392 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1393 info.setFailover(false);
1394 }
1395 if (info.getReason() != null) {
1396 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1397 }
1398 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001399 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1400 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001401 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001402
Robert Greenwalt34848c02011-03-25 13:09:25 -07001403 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001404 tryFailover(prevNetType);
1405 if (mActiveDefaultNetwork != -1) {
1406 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001407 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1408 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001409 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001410 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1411 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001412 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001413 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001414
1415 // Reset interface if no other connections are using the same interface
1416 boolean doReset = true;
1417 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1418 if (linkProperties != null) {
1419 String oldIface = linkProperties.getInterfaceName();
1420 if (TextUtils.isEmpty(oldIface) == false) {
1421 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1422 if (networkStateTracker == null) continue;
1423 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1424 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1425 LinkProperties l = networkStateTracker.getLinkProperties();
1426 if (l == null) continue;
1427 if (oldIface.equals(l.getInterfaceName())) {
1428 doReset = false;
1429 break;
1430 }
1431 }
1432 }
1433 }
1434 }
1435
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001436 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001437 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001438
1439 sendStickyBroadcast(intent);
1440 /*
1441 * If the failover network is already connected, then immediately send
1442 * out a followup broadcast indicating successful failover
1443 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001444 if (mActiveDefaultNetwork != -1) {
1445 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001446 }
1447 }
1448
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001449 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001450 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001451 * If this is a default network, check if other defaults are available.
1452 * Try to reconnect on all available and let them hash it out when
1453 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001454 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001455 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001456 if (mActiveDefaultNetwork == prevNetType) {
1457 mActiveDefaultNetwork = -1;
1458 }
1459
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001460 // don't signal a reconnect for anything lower or equal priority than our
1461 // current connected default
1462 // TODO - don't filter by priority now - nice optimization but risky
1463// int currentPriority = -1;
1464// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001465// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001466// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001467 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001468 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001469 if (mNetConfigs[checkType] == null) continue;
1470 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001471
1472// Enabling the isAvailable() optimization caused mobile to not get
1473// selected if it was in the middle of error handling. Specifically
1474// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1475// would not be available and we wouldn't get connected to anything.
1476// So removing the isAvailable() optimization below for now. TODO: This
1477// optimization should work and we need to investigate why it doesn't work.
1478// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1479// complete before it is really complete.
1480// if (!mNetTrackers[checkType].isAvailable()) continue;
1481
Robert Greenwalt34848c02011-03-25 13:09:25 -07001482// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001483
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001484 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1485 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1486 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1487 checkInfo.setFailover(true);
1488 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001489 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001490 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001491 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001492 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001493 }
1494
1495 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001496 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1497 }
1498
1499 private void sendInetConditionBroadcast(NetworkInfo info) {
1500 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1501 }
1502
1503 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1504 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001505 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1506 if (info.isFailover()) {
1507 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1508 info.setFailover(false);
1509 }
1510 if (info.getReason() != null) {
1511 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1512 }
1513 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001514 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1515 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001516 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001517 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001518 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001519 }
1520
1521 /**
1522 * Called when an attempt to fail over to another network has failed.
1523 * @param info the {@link NetworkInfo} for the failed network
1524 */
1525 private void handleConnectionFailure(NetworkInfo info) {
1526 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527
Robert Greenwalt2034b912009-08-12 16:08:25 -07001528 String reason = info.getReason();
1529 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001530
Robert Greenwalte981bc52010-10-08 16:35:52 -07001531 String reasonText;
1532 if (reason == null) {
1533 reasonText = ".";
1534 } else {
1535 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001536 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001537 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001538
1539 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1540 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1541 if (getActiveNetworkInfo() == null) {
1542 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1543 }
1544 if (reason != null) {
1545 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1546 }
1547 if (extraInfo != null) {
1548 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1549 }
1550 if (info.isFailover()) {
1551 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1552 info.setFailover(false);
1553 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001554
Robert Greenwalt34848c02011-03-25 13:09:25 -07001555 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001556 tryFailover(info.getType());
1557 if (mActiveDefaultNetwork != -1) {
1558 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001559 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1560 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001561 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001562 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1563 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001564 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001565
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001566 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001567 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001568 /*
1569 * If the failover network is already connected, then immediately send
1570 * out a followup broadcast indicating successful failover
1571 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001572 if (mActiveDefaultNetwork != -1) {
1573 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001574 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001575 }
1576
1577 private void sendStickyBroadcast(Intent intent) {
1578 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001579 if (!mSystemReady) {
1580 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001581 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001582 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1583 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001584 }
1585 }
1586
1587 void systemReady() {
1588 synchronized(this) {
1589 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001590 if (mInitialBroadcast != null) {
1591 mContext.sendStickyBroadcast(mInitialBroadcast);
1592 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001593 }
1594 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001595 // load the global proxy at startup
1596 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001597 }
1598
1599 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001600 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001601
1602 // snapshot isFailover, because sendConnectedBroadcast() resets it
1603 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001604 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001605
Robert Greenwalt2034b912009-08-12 16:08:25 -07001606 // if this is a default net and other default is running
1607 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001608 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001609 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1610 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001611 mNetConfigs[mActiveDefaultNetwork].priority >
1612 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001613 mNetworkPreference == mActiveDefaultNetwork) {
1614 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001615 if (DBG) {
1616 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001617 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001618 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001619 teardown(thisNet);
1620 return;
1621 } else {
1622 // tear down the other
1623 NetworkStateTracker otherNet =
1624 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001625 if (DBG) {
1626 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001627 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001628 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001629 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001630 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001631 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001632 return;
1633 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001634 }
1635 }
1636 synchronized (ConnectivityService.this) {
1637 // have a new default network, release the transition wakelock in a second
1638 // if it's held. The second pause is to allow apps to reconnect over the
1639 // new network
1640 if (mNetTransitionWakeLock.isHeld()) {
1641 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001642 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001643 mNetTransitionWakeLockSerialNumber, 0),
1644 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001645 }
1646 }
1647 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001648 // this will cause us to come up initially as unconnected and switching
1649 // to connected after our normal pause unless somebody reports us as reall
1650 // disconnected
1651 mDefaultInetConditionPublished = 0;
1652 mDefaultConnectionSequence++;
1653 mInetConditionChangeInFlight = false;
1654 // Don't do this - if we never sign in stay, grey
1655 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001656 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001657 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001658 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001659 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001660 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001661 }
1662
The Android Open Source Project28527d22009-03-03 19:31:44 -08001663 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001664 * After a change in the connectivity state of a network. We're mainly
1665 * concerned with making sure that the list of DNS servers is set up
1666 * according to which networks are connected, and ensuring that the
1667 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001668 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001669 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001670 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1671
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001673 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001674 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001675 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001676 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001677
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001678 LinkProperties curLp = mCurrentLinkProperties[netType];
1679 LinkProperties newLp = null;
1680
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001681 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001682 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001683 if (VDBG) {
1684 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1685 " doReset=" + doReset + " resetMask=" + resetMask +
1686 "\n curLp=" + curLp +
1687 "\n newLp=" + newLp);
1688 }
1689
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001690 if (curLp != null) {
1691 if (curLp.isIdenticalInterfaceName(newLp)) {
1692 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1693 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1694 for (LinkAddress linkAddr : car.removed) {
1695 if (linkAddr.getAddress() instanceof Inet4Address) {
1696 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1697 }
1698 if (linkAddr.getAddress() instanceof Inet6Address) {
1699 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1700 }
Wink Saville051a6642011-07-13 13:44:13 -07001701 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001702 if (DBG) {
1703 log("handleConnectivityChange: addresses changed" +
1704 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1705 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001706 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001707 } else {
1708 if (DBG) {
1709 log("handleConnectivityChange: address are the same reset per doReset" +
1710 " linkProperty[" + netType + "]:" +
1711 " resetMask=" + resetMask);
1712 }
Wink Saville051a6642011-07-13 13:44:13 -07001713 }
1714 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001715 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1716 log("handleConnectivityChange: interface not not equivalent reset both" +
1717 " linkProperty[" + netType + "]:" +
1718 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001719 }
Wink Saville051a6642011-07-13 13:44:13 -07001720 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001721 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001722 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001723 }
1724 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001725 if (VDBG) {
1726 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1727 " doReset=" + doReset + " resetMask=" + resetMask +
1728 "\n curLp=" + curLp +
1729 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001730 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001731 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001732 mCurrentLinkProperties[netType] = newLp;
1733 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001734
Wink Saville051a6642011-07-13 13:44:13 -07001735 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001736 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1737 if (linkProperties != null) {
1738 String iface = linkProperties.getInterfaceName();
1739 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001740 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1741 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001742 }
1743 }
1744 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001745
1746 // TODO: Temporary notifying upstread change to Tethering.
1747 // @see bug/4455071
1748 /** Notify TetheringService if interface name has been changed. */
1749 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1750 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1751 if (isTetheringSupported()) {
1752 mTethering.handleTetherIfaceChange();
1753 }
1754 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001755 }
1756
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001757 /**
1758 * Add and remove routes using the old properties (null if not previously connected),
1759 * new properties (null if becoming disconnected). May even be double null, which
1760 * is a noop.
1761 * Uses isLinkDefault to determine if default routes should be set or conversely if
1762 * host routes should be set to the dns servers
1763 */
1764 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1765 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001766 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1767 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001768 if (curLp != null) {
1769 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001770 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001771 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001772 } else if (newLp != null) {
1773 routeDiff.added = newLp.getRoutes();
1774 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001775 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001776
Robert Greenwalt98107422011-07-22 11:55:33 -07001777 for (RouteInfo r : routeDiff.removed) {
1778 if (isLinkDefault || ! r.isDefaultRoute()) {
1779 removeRoute(curLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001780 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001781 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001782
Robert Greenwalt98107422011-07-22 11:55:33 -07001783 for (RouteInfo r : routeDiff.added) {
1784 if (isLinkDefault || ! r.isDefaultRoute()) {
1785 addRoute(newLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001786 }
1787 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001788
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001789 if (!isLinkDefault) {
1790 // handle DNS routes
Robert Greenwalt98107422011-07-22 11:55:33 -07001791 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1792 // no change in routes, check for change in dns themselves
1793 for (InetAddress oldDns : dnsDiff.removed) {
1794 removeRouteToAddress(curLp, oldDns);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001795 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001796 for (InetAddress newDns : dnsDiff.added) {
1797 addRouteToAddress(newLp, newDns);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001798 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001799 } else {
1800 // routes changed - remove all old dns entries and add new
1801 if (curLp != null) {
1802 for (InetAddress oldDns : curLp.getDnses()) {
1803 removeRouteToAddress(curLp, oldDns);
1804 }
1805 }
1806 if (newLp != null) {
1807 for (InetAddress newDns : newLp.getDnses()) {
1808 addRouteToAddress(newLp, newDns);
1809 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001810 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001811 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001812 }
1813 }
1814
1815
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001816 /**
1817 * Reads the network specific TCP buffer sizes from SystemProperties
1818 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1819 * wide use
1820 */
1821 public void updateNetworkSettings(NetworkStateTracker nt) {
1822 String key = nt.getTcpBufferSizesPropName();
1823 String bufferSizes = SystemProperties.get(key);
1824
1825 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001826 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001827
1828 // Setting to default values so we won't be stuck to previous values
1829 key = "net.tcp.buffersize.default";
1830 bufferSizes = SystemProperties.get(key);
1831 }
1832
1833 // Set values in kernel
1834 if (bufferSizes.length() != 0) {
1835 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001836 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001837 + "] which comes from [" + key + "]");
1838 }
1839 setBufferSize(bufferSizes);
1840 }
1841 }
1842
1843 /**
1844 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1845 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1846 *
1847 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1848 * writeMin, writeInitial, writeMax"
1849 */
1850 private void setBufferSize(String bufferSizes) {
1851 try {
1852 String[] values = bufferSizes.split(",");
1853
1854 if (values.length == 6) {
1855 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001856 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1857 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1858 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1859 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1860 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1861 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001862 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001863 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001864 }
1865 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001866 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001867 }
1868 }
1869
Robert Greenwalt2034b912009-08-12 16:08:25 -07001870 /**
1871 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1872 * on the highest priority active net which this process requested.
1873 * If there aren't any, clear it out
1874 */
1875 private void reassessPidDns(int myPid, boolean doBump)
1876 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001877 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001878 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001879 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001880 continue;
1881 }
1882 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001883 if (nt.getNetworkInfo().isConnected() &&
1884 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001885 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001886 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001887 List pids = mNetRequestersPids[i];
1888 for (int j=0; j<pids.size(); j++) {
1889 Integer pid = (Integer)pids.get(j);
1890 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001891 Collection<InetAddress> dnses = p.getDnses();
1892 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001893 if (doBump) {
1894 bumpDns();
1895 }
1896 return;
1897 }
1898 }
1899 }
1900 }
1901 // nothing found - delete
1902 for (int i = 1; ; i++) {
1903 String prop = "net.dns" + i + "." + myPid;
1904 if (SystemProperties.get(prop).length() == 0) {
1905 if (doBump) {
1906 bumpDns();
1907 }
1908 return;
1909 }
1910 SystemProperties.set(prop, "");
1911 }
1912 }
1913
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001914 // return true if results in a change
1915 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001916 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001917 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001918 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001919 String dnsString = dns.getHostAddress();
1920 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1921 changed = true;
1922 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1923 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001924 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001925 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001926 }
1927
1928 private void bumpDns() {
1929 /*
1930 * Bump the property that tells the name resolver library to reread
1931 * the DNS server list from the properties.
1932 */
1933 String propVal = SystemProperties.get("net.dnschange");
1934 int n = 0;
1935 if (propVal.length() != 0) {
1936 try {
1937 n = Integer.parseInt(propVal);
1938 } catch (NumberFormatException e) {}
1939 }
1940 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001941 /*
1942 * Tell the VMs to toss their DNS caches
1943 */
1944 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1945 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001946 /*
1947 * Connectivity events can happen before boot has completed ...
1948 */
1949 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001950 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001951 }
1952
Chia-chi Yehcc844502011-07-14 18:01:57 -07001953 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07001954 private boolean updateDns(String network, String iface,
1955 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07001956 boolean changed = false;
1957 int last = 0;
1958 if (dnses.size() == 0 && mDefaultDns != null) {
1959 ++last;
1960 String value = mDefaultDns.getHostAddress();
1961 if (!value.equals(SystemProperties.get("net.dns1"))) {
1962 if (DBG) {
1963 log("no dns provided for " + network + " - using " + value);
1964 }
1965 changed = true;
1966 SystemProperties.set("net.dns1", value);
1967 }
1968 } else {
1969 for (InetAddress dns : dnses) {
1970 ++last;
1971 String key = "net.dns" + last;
1972 String value = dns.getHostAddress();
1973 if (!changed && value.equals(SystemProperties.get(key))) {
1974 continue;
1975 }
1976 if (DBG) {
1977 log("adding dns " + value + " for " + network);
1978 }
1979 changed = true;
1980 SystemProperties.set(key, value);
1981 }
1982 }
1983 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
1984 String key = "net.dns" + i;
1985 if (DBG) log("erasing " + key);
1986 changed = true;
1987 SystemProperties.set(key, "");
1988 }
1989 mNumDnsEntries = last;
1990
Robert Greenwaltfce71862011-07-25 16:06:25 -07001991 if (changed) {
1992 try {
1993 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
1994 mNetd.setDefaultInterfaceForDns(iface);
1995 } catch (Exception e) {
1996 Slog.e(TAG, "exception setting default dns interface: " + e);
1997 }
1998 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07001999 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2000 SystemProperties.set("net.dns.search", domains);
2001 changed = true;
2002 }
2003 return changed;
2004 }
2005
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002006 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002007 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002008 NetworkStateTracker nt = mNetTrackers[netType];
2009 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002010 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002011 if (p == null) return;
2012 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002013 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002014 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002015 String network = nt.getNetworkInfo().getTypeName();
2016 synchronized (mDnsLock) {
2017 if (!mDnsOverridden) {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002018 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002019 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002020 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002021 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002022 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002023 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002024 NetworkUtils.makeStrings(dnses));
2025 } catch (Exception e) {
2026 Slog.e(TAG, "exception setting dns servers: " + e);
2027 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002028 // set per-pid dns for attached secondary nets
2029 List pids = mNetRequestersPids[netType];
2030 for (int y=0; y< pids.size(); y++) {
2031 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002032 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002033 }
2034 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002035 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002036 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002037 }
2038
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002039 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002040 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2041 NETWORK_RESTORE_DELAY_PROP_NAME);
2042 if(restoreDefaultNetworkDelayStr != null &&
2043 restoreDefaultNetworkDelayStr.length() != 0) {
2044 try {
2045 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2046 } catch (NumberFormatException e) {
2047 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002048 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002049 // if the system property isn't set, use the value for the apn type
2050 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2051
2052 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2053 (mNetConfigs[networkType] != null)) {
2054 ret = mNetConfigs[networkType].restoreTime;
2055 }
2056 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002057 }
2058
2059 @Override
2060 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002061 if (mContext.checkCallingOrSelfPermission(
2062 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002063 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002064 pw.println("Permission Denial: can't dump ConnectivityService " +
2065 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2066 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002067 return;
2068 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002069 pw.println();
2070 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002071 if (nst != null) {
2072 if (nst.getNetworkInfo().isConnected()) {
2073 pw.println("Active network: " + nst.getNetworkInfo().
2074 getTypeName());
2075 }
2076 pw.println(nst.getNetworkInfo());
2077 pw.println(nst);
2078 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002079 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002080 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002081
2082 pw.println("Network Requester Pids:");
2083 for (int net : mPriorityList) {
2084 String pidString = net + ": ";
2085 for (Object pid : mNetRequestersPids[net]) {
2086 pidString = pidString + pid.toString() + ", ";
2087 }
2088 pw.println(pidString);
2089 }
2090 pw.println();
2091
2092 pw.println("FeatureUsers:");
2093 for (Object requester : mFeatureUsers) {
2094 pw.println(requester.toString());
2095 }
2096 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002097
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002098 synchronized (this) {
2099 pw.println("NetworkTranstionWakeLock is currently " +
2100 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2101 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2102 }
2103 pw.println();
2104
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002105 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002106
2107 if (mInetLog != null) {
2108 pw.println();
2109 pw.println("Inet condition reports:");
2110 for(int i = 0; i < mInetLog.size(); i++) {
2111 pw.println(mInetLog.get(i));
2112 }
2113 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002114 }
2115
Robert Greenwalt2034b912009-08-12 16:08:25 -07002116 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002117 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002118 public MyHandler(Looper looper) {
2119 super(looper);
2120 }
2121
The Android Open Source Project28527d22009-03-03 19:31:44 -08002122 @Override
2123 public void handleMessage(Message msg) {
2124 NetworkInfo info;
2125 switch (msg.what) {
2126 case NetworkStateTracker.EVENT_STATE_CHANGED:
2127 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002128 int type = info.getType();
2129 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002130
Wink Savillee70c6f52010-12-03 12:01:38 -08002131 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002132 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002133 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134
2135 // Connectivity state changed:
2136 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002137 // [12-9] Network subtype (for mobile network, as defined
2138 // by TelephonyManager)
2139 // [8-3] Detailed state ordinal (as defined by
2140 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002141 // [2-0] Network type (as defined by ConnectivityManager)
2142 int eventLogParam = (info.getType() & 0x7) |
2143 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2144 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002145 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002146 eventLogParam);
2147
2148 if (info.getDetailedState() ==
2149 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002150 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002151 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002152 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002153 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002155 // the logic here is, handle SUSPENDED the same as
2156 // DISCONNECTED. The only difference being we are
2157 // broadcasting an intent with NetworkInfo that's
2158 // suspended. This allows the applications an
2159 // opportunity to handle DISCONNECTED and SUSPENDED
2160 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002162 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002163 handleConnect(info);
2164 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002166 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002167 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002168 // TODO: Temporary allowing network configuration
2169 // change not resetting sockets.
2170 // @see bug/4455071
2171 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002172 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002173 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002174 String causedBy = null;
2175 synchronized (ConnectivityService.this) {
2176 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2177 mNetTransitionWakeLock.isHeld()) {
2178 mNetTransitionWakeLock.release();
2179 causedBy = mNetTransitionWakeLockCausedBy;
2180 }
2181 }
2182 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002183 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002184 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002185 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002186 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002187 FeatureUser u = (FeatureUser)msg.obj;
2188 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002189 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002190 case EVENT_INET_CONDITION_CHANGE:
2191 {
2192 int netType = msg.arg1;
2193 int condition = msg.arg2;
2194 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002195 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002196 }
2197 case EVENT_INET_CONDITION_HOLD_END:
2198 {
2199 int netType = msg.arg1;
2200 int sequence = msg.arg2;
2201 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002202 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002203 }
2204 case EVENT_SET_NETWORK_PREFERENCE:
2205 {
2206 int preference = msg.arg1;
2207 handleSetNetworkPreference(preference);
2208 break;
2209 }
2210 case EVENT_SET_BACKGROUND_DATA:
2211 {
2212 boolean enabled = (msg.arg1 == ENABLED);
2213 handleSetBackgroundData(enabled);
2214 break;
2215 }
2216 case EVENT_SET_MOBILE_DATA:
2217 {
2218 boolean enabled = (msg.arg1 == ENABLED);
2219 handleSetMobileData(enabled);
2220 break;
2221 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002222 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2223 {
2224 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002225 break;
2226 }
2227 case EVENT_SET_DEPENDENCY_MET:
2228 {
2229 boolean met = (msg.arg1 == ENABLED);
2230 handleSetDependencyMet(msg.arg2, met);
2231 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002232 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002233 case EVENT_RESTORE_DNS:
2234 {
2235 if (mActiveDefaultNetwork != -1) {
2236 handleDnsConfigurationChange(mActiveDefaultNetwork);
2237 }
2238 break;
2239 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002240 }
2241 }
2242 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002243
2244 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002245 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002246 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002247
2248 if (isTetheringSupported()) {
2249 return mTethering.tether(iface);
2250 } else {
2251 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2252 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002253 }
2254
2255 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002256 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002257 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002258
2259 if (isTetheringSupported()) {
2260 return mTethering.untether(iface);
2261 } else {
2262 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2263 }
2264 }
2265
2266 // javadoc from interface
2267 public int getLastTetherError(String iface) {
2268 enforceTetherAccessPermission();
2269
2270 if (isTetheringSupported()) {
2271 return mTethering.getLastTetherError(iface);
2272 } else {
2273 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2274 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002275 }
2276
2277 // TODO - proper iface API for selection by property, inspection, etc
2278 public String[] getTetherableUsbRegexs() {
2279 enforceTetherAccessPermission();
2280 if (isTetheringSupported()) {
2281 return mTethering.getTetherableUsbRegexs();
2282 } else {
2283 return new String[0];
2284 }
2285 }
2286
2287 public String[] getTetherableWifiRegexs() {
2288 enforceTetherAccessPermission();
2289 if (isTetheringSupported()) {
2290 return mTethering.getTetherableWifiRegexs();
2291 } else {
2292 return new String[0];
2293 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002294 }
2295
Danica Chang96567052010-08-11 14:54:43 -07002296 public String[] getTetherableBluetoothRegexs() {
2297 enforceTetherAccessPermission();
2298 if (isTetheringSupported()) {
2299 return mTethering.getTetherableBluetoothRegexs();
2300 } else {
2301 return new String[0];
2302 }
2303 }
2304
Mike Lockwooded4a1742011-07-19 13:04:47 -07002305 public int setUsbTethering(boolean enable) {
2306 enforceTetherAccessPermission();
2307 if (isTetheringSupported()) {
2308 return mTethering.setUsbTethering(enable);
2309 } else {
2310 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2311 }
2312 }
2313
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002314 // TODO - move iface listing, queries, etc to new module
2315 // javadoc from interface
2316 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002317 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002318 return mTethering.getTetherableIfaces();
2319 }
2320
2321 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002322 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002323 return mTethering.getTetheredIfaces();
2324 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002325
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002326 public String[] getTetheringErroredIfaces() {
2327 enforceTetherAccessPermission();
2328 return mTethering.getErroredIfaces();
2329 }
2330
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002331 // if ro.tether.denied = true we default to no tethering
2332 // gservices could set the secure setting to 1 though to enable it on a build where it
2333 // had previously been turned off.
2334 public boolean isTetheringSupported() {
2335 enforceTetherAccessPermission();
2336 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002337 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2338 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2339 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002340 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002341
2342 // An API NetworkStateTrackers can call when they lose their network.
2343 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2344 // whichever happens first. The timer is started by the first caller and not
2345 // restarted by subsequent callers.
2346 public void requestNetworkTransitionWakelock(String forWhom) {
2347 enforceConnectivityInternalPermission();
2348 synchronized (this) {
2349 if (mNetTransitionWakeLock.isHeld()) return;
2350 mNetTransitionWakeLockSerialNumber++;
2351 mNetTransitionWakeLock.acquire();
2352 mNetTransitionWakeLockCausedBy = forWhom;
2353 }
2354 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002355 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002356 mNetTransitionWakeLockSerialNumber, 0),
2357 mNetTransitionWakeLockTimeout);
2358 return;
2359 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002360
Robert Greenwalt986c7412010-09-08 15:24:47 -07002361 // 100 percent is full good, 0 is full bad.
2362 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002363 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002364 mContext.enforceCallingOrSelfPermission(
2365 android.Manifest.permission.STATUS_BAR,
2366 "ConnectivityService");
2367
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002368 if (DBG) {
2369 int pid = getCallingPid();
2370 int uid = getCallingUid();
2371 String s = pid + "(" + uid + ") reports inet is " +
2372 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2373 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2374 mInetLog.add(s);
2375 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2376 mInetLog.remove(0);
2377 }
2378 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002379 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002380 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2381 }
2382
2383 private void handleInetConditionChange(int netType, int condition) {
2384 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002385 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002386 netType + ", condition=" + condition +
2387 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2388 }
2389 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002390 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002391 return;
2392 }
2393 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002394 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002395 return;
2396 }
2397 mDefaultInetCondition = condition;
2398 int delay;
2399 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002400 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002401 // setup a new hold to debounce this
2402 if (mDefaultInetCondition > 50) {
2403 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2404 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2405 } else {
2406 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2407 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2408 }
2409 mInetConditionChangeInFlight = true;
2410 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2411 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2412 } else {
2413 // we've set the new condition, when this hold ends that will get
2414 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002415 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002416 }
2417 }
2418
2419 private void handleInetConditionHoldEnd(int netType, int sequence) {
2420 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002421 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002422 ", condition =" + mDefaultInetCondition +
2423 ", published condition =" + mDefaultInetConditionPublished);
2424 }
2425 mInetConditionChangeInFlight = false;
2426
2427 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002428 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002429 return;
2430 }
2431 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002432 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002433 return;
2434 }
2435 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002436 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002437 return;
2438 }
2439 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2440 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002441 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002442 return;
2443 }
2444 mDefaultInetConditionPublished = mDefaultInetCondition;
2445 sendInetConditionBroadcast(networkInfo);
2446 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002447 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002448
2449 public synchronized ProxyProperties getProxy() {
2450 if (mGlobalProxy != null) return mGlobalProxy;
2451 if (mDefaultProxy != null) return mDefaultProxy;
2452 return null;
2453 }
2454
2455 public void setGlobalProxy(ProxyProperties proxyProperties) {
2456 enforceChangePermission();
2457 synchronized (mGlobalProxyLock) {
2458 if (proxyProperties == mGlobalProxy) return;
2459 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2460 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2461
2462 String host = "";
2463 int port = 0;
2464 String exclList = "";
2465 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2466 mGlobalProxy = new ProxyProperties(proxyProperties);
2467 host = mGlobalProxy.getHost();
2468 port = mGlobalProxy.getPort();
2469 exclList = mGlobalProxy.getExclusionList();
2470 } else {
2471 mGlobalProxy = null;
2472 }
2473 ContentResolver res = mContext.getContentResolver();
2474 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2475 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002476 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002477 exclList);
2478 }
2479
2480 if (mGlobalProxy == null) {
2481 proxyProperties = mDefaultProxy;
2482 }
2483 sendProxyBroadcast(proxyProperties);
2484 }
2485
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002486 private void loadGlobalProxy() {
2487 ContentResolver res = mContext.getContentResolver();
2488 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2489 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2490 String exclList = Settings.Secure.getString(res,
2491 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2492 if (!TextUtils.isEmpty(host)) {
2493 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2494 synchronized (mGlobalProxyLock) {
2495 mGlobalProxy = proxyProperties;
2496 }
2497 }
2498 }
2499
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002500 public ProxyProperties getGlobalProxy() {
2501 synchronized (mGlobalProxyLock) {
2502 return mGlobalProxy;
2503 }
2504 }
2505
2506 private void handleApplyDefaultProxy(int type) {
2507 // check if new default - push it out to all VM if so
2508 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2509 synchronized (this) {
2510 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2511 if (mDefaultProxy == proxy) return;
Robert Greenwalt027f5052011-07-29 10:03:37 -07002512 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002513 mDefaultProxy = proxy;
2514 } else {
2515 mDefaultProxy = null;
2516 }
2517 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002518 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002519 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2520 if (mGlobalProxy != null) return;
2521 sendProxyBroadcast(proxy);
2522 }
2523
2524 private void handleDeprecatedGlobalHttpProxy() {
2525 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2526 Settings.Secure.HTTP_PROXY);
2527 if (!TextUtils.isEmpty(proxy)) {
2528 String data[] = proxy.split(":");
2529 String proxyHost = data[0];
2530 int proxyPort = 8080;
2531 if (data.length > 1) {
2532 try {
2533 proxyPort = Integer.parseInt(data[1]);
2534 } catch (NumberFormatException e) {
2535 return;
2536 }
2537 }
2538 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2539 setGlobalProxy(p);
2540 }
2541 }
2542
2543 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002544 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002545 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002546 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002547 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2548 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002549 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002550 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002551 }
2552
2553 private static class SettingsObserver extends ContentObserver {
2554 private int mWhat;
2555 private Handler mHandler;
2556 SettingsObserver(Handler handler, int what) {
2557 super(handler);
2558 mHandler = handler;
2559 mWhat = what;
2560 }
2561
2562 void observe(Context context) {
2563 ContentResolver resolver = context.getContentResolver();
2564 resolver.registerContentObserver(Settings.Secure.getUriFor(
2565 Settings.Secure.HTTP_PROXY), false, this);
2566 }
2567
2568 @Override
2569 public void onChange(boolean selfChange) {
2570 mHandler.obtainMessage(mWhat).sendToTarget();
2571 }
2572 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002573
2574 private void log(String s) {
2575 Slog.d(TAG, s);
2576 }
2577
2578 private void loge(String s) {
2579 Slog.e(TAG, s);
2580 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002581
Wink Savillef6b76692011-02-24 17:58:51 -08002582 int convertFeatureToNetworkType(String feature){
2583 int networkType = -1;
2584 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2585 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2586 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2587 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2588 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2589 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2590 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2591 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2592 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2593 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2594 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2595 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2596 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2597 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2598 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2599 }
2600 return networkType;
2601 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002602
2603 private static <T> T checkNotNull(T value, String message) {
2604 if (value == null) {
2605 throw new NullPointerException(message);
2606 }
2607 return value;
2608 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002609
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002610 /**
2611 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002612 * VpnBuilder and not available in ConnectivityManager. Permissions
2613 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002614 * @hide
2615 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002616 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002617 public boolean protectVpn(ParcelFileDescriptor socket) {
2618 try {
2619 int type = mActiveDefaultNetwork;
2620 if (ConnectivityManager.isNetworkTypeValid(type)) {
2621 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2622 return true;
2623 }
2624 } catch (Exception e) {
2625 // ignore
2626 } finally {
2627 try {
2628 socket.close();
2629 } catch (Exception e) {
2630 // ignore
2631 }
2632 }
2633 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002634 }
2635
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002636 /**
2637 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002638 * and not available in ConnectivityManager. Permissions are checked
2639 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002640 * @hide
2641 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002642 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002643 public boolean prepareVpn(String oldPackage, String newPackage) {
2644 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002645 }
2646
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002647 /**
2648 * Configure a TUN interface and return its file descriptor. Parameters
2649 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002650 * and not available in ConnectivityManager. Permissions are checked in
2651 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002652 * @hide
2653 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002654 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002655 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002656 return mVpn.establish(config);
2657 }
2658
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002659 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002660 * Start legacy VPN and return an intent to VpnDialogs. This method is
2661 * used by VpnSettings and not available in ConnectivityManager.
2662 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002663 * @hide
2664 */
2665 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002666 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2667 mVpn.startLegacyVpn(config, racoon, mtpd);
2668 }
2669
2670 /**
2671 * Return the information of the ongoing legacy VPN. This method is used
2672 * by VpnSettings and not available in ConnectivityManager. Permissions
2673 * are checked in Vpn class.
2674 * @hide
2675 */
2676 @Override
2677 public LegacyVpnInfo getLegacyVpnInfo() {
2678 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002679 }
2680
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002681 /**
2682 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2683 * through NetworkStateTracker since it works differently. For example, it
2684 * needs to override DNS servers but never takes the default routes. It
2685 * relies on another data network, and it could keep existing connections
2686 * alive after reconnecting, switching between networks, or even resuming
2687 * from deep sleep. Calls from applications should be done synchronously
2688 * to avoid race conditions. As these are all hidden APIs, refactoring can
2689 * be done whenever a better abstraction is developed.
2690 */
2691 public class VpnCallback {
2692
2693 private VpnCallback() {
2694 }
2695
Chia-chi Yehcc844502011-07-14 18:01:57 -07002696 public void override(List<String> dnsServers, List<String> searchDomains) {
2697 if (dnsServers == null) {
2698 restore();
2699 return;
2700 }
2701
2702 // Convert DNS servers into addresses.
2703 List<InetAddress> addresses = new ArrayList<InetAddress>();
2704 for (String address : dnsServers) {
2705 // Double check the addresses and remove invalid ones.
2706 try {
2707 addresses.add(InetAddress.parseNumericAddress(address));
2708 } catch (Exception e) {
2709 // ignore
2710 }
2711 }
2712 if (addresses.isEmpty()) {
2713 restore();
2714 return;
2715 }
2716
2717 // Concatenate search domains into a string.
2718 StringBuilder buffer = new StringBuilder();
2719 if (searchDomains != null) {
2720 for (String domain : searchDomains) {
2721 buffer.append(domain).append(' ');
2722 }
2723 }
2724 String domains = buffer.toString().trim();
2725
2726 // Apply DNS changes.
2727 boolean changed = false;
2728 synchronized (mDnsLock) {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002729 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002730 mDnsOverridden = true;
2731 }
2732 if (changed) {
2733 bumpDns();
2734 }
2735
2736 // TODO: temporarily remove http proxy?
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002737 }
2738
Chia-chi Yehcc844502011-07-14 18:01:57 -07002739 public void restore() {
2740 synchronized (mDnsLock) {
2741 if (!mDnsOverridden) {
2742 return;
2743 }
2744 mDnsOverridden = false;
2745 }
2746 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002747 }
2748 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002749}