blob: a5066367e2cb03698246b697e4ac10dc29a0771c [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
Wink Saville7e4333c2011-08-05 11:40:22 -0700257 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700258 * used internally to send a sticky broadcast delayed.
259 */
260 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville7e4333c2011-08-05 11:40:22 -0700261 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700262
Robert Greenwalt2034b912009-08-12 16:08:25 -0700263 private Handler mHandler;
264
265 // list of DeathRecipients used to make sure features are turned off when
266 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500267 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700268
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400269 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800270 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400271
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700272 private PowerManager.WakeLock mNetTransitionWakeLock;
273 private String mNetTransitionWakeLockCausedBy = "";
274 private int mNetTransitionWakeLockSerialNumber;
275 private int mNetTransitionWakeLockTimeout;
276
Robert Greenwalt94daa182010-09-01 11:34:05 -0700277 private InetAddress mDefaultDns;
278
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700279 // this collection is used to refcount the added routes - if there are none left
280 // it's time to remove the route from the route table
281 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
282
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700283 // used in DBG mode to track inet condition reports
284 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
285 private ArrayList mInetLog;
286
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700287 // track the current default http proxy - tell the world if we get a new one (real change)
288 private ProxyProperties mDefaultProxy = null;
289 // track the global proxy.
290 private ProxyProperties mGlobalProxy = null;
291 private final Object mGlobalProxyLock = new Object();
292
293 private SettingsObserver mSettingsObserver;
294
Robert Greenwalt34848c02011-03-25 13:09:25 -0700295 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700296 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700297
Robert Greenwalt12c44552009-12-07 11:33:18 -0800298 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700299 public int mSimultaneity;
300 public int mType;
301 public RadioAttributes(String init) {
302 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700303 mType = Integer.parseInt(fragments[0]);
304 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700305 }
306 }
307 RadioAttributes[] mRadioAttributes;
308
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700309 // the set of network types that can only be enabled by system/sig apps
310 List mProtectedNetworks;
311
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700312 public ConnectivityService(
313 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800314 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800315
Wink Saville775aad62010-09-02 19:23:52 -0700316 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
317 handlerThread.start();
318 mHandler = new MyHandler(handlerThread.getLooper());
319
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800320 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
321 Settings.Secure.BACKGROUND_DATA, 1) == 1);
322
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800323 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800324 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
325 String id = Settings.Secure.getString(context.getContentResolver(),
326 Settings.Secure.ANDROID_ID);
327 if (id != null && id.length() > 0) {
328 String name = new String("android_").concat(id);
329 SystemProperties.set("net.hostname", name);
330 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800331 }
332
Robert Greenwalt94daa182010-09-01 11:34:05 -0700333 // read our default dns server ip
334 String dns = Settings.Secure.getString(context.getContentResolver(),
335 Settings.Secure.DEFAULT_DNS_SERVER);
336 if (dns == null || dns.length() == 0) {
337 dns = context.getResources().getString(
338 com.android.internal.R.string.config_default_dns_server);
339 }
340 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800341 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
342 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800343 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700344 }
345
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700346 mContext = checkNotNull(context, "missing Context");
347 mNetd = checkNotNull(netd, "missing INetworkManagementService");
348 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700349
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700350 try {
351 mPolicyManager.registerListener(mPolicyListener);
352 } catch (RemoteException e) {
353 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700354 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700355 }
356
357 final PowerManager powerManager = (PowerManager) context.getSystemService(
358 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700359 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
360 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
361 com.android.internal.R.integer.config_networkTransitionTimeout);
362
Robert Greenwalt2034b912009-08-12 16:08:25 -0700363 mNetTrackers = new NetworkStateTracker[
364 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700365 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700366
The Android Open Source Project28527d22009-03-03 19:31:44 -0800367 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700368
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700369 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700370 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700371
Robert Greenwalt2034b912009-08-12 16:08:25 -0700372 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700373 String[] raStrings = context.getResources().getStringArray(
374 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700375 for (String raString : raStrings) {
376 RadioAttributes r = new RadioAttributes(raString);
377 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800378 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700379 continue;
380 }
381 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800382 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700383 r.mType);
384 continue;
385 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700386 mRadioAttributes[r.mType] = r;
387 }
388
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700389 String[] naStrings = context.getResources().getStringArray(
390 com.android.internal.R.array.networkAttributes);
391 for (String naString : naStrings) {
392 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700393 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700394 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800395 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700396 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700397 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700398 }
Wink Savillef2a62832011-04-07 14:23:45 -0700399 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800400 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700401 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700402 continue;
403 }
Wink Savillef2a62832011-04-07 14:23:45 -0700404 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800405 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700406 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700407 continue;
408 }
Wink Savillef2a62832011-04-07 14:23:45 -0700409 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700410 mNetworksDefined++;
411 } catch(Exception e) {
412 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700413 }
414 }
415
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700416 mProtectedNetworks = new ArrayList<Integer>();
417 int[] protectedNetworks = context.getResources().getIntArray(
418 com.android.internal.R.array.config_protectedNetworks);
419 for (int p : protectedNetworks) {
420 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
421 mProtectedNetworks.add(p);
422 } else {
423 if (DBG) loge("Ignoring protectedNetwork " + p);
424 }
425 }
426
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700427 // high priority first
428 mPriorityList = new int[mNetworksDefined];
429 {
430 int insertionPoint = mNetworksDefined-1;
431 int currentLowest = 0;
432 int nextLowest = 0;
433 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700434 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700435 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700436 if (na.priority < currentLowest) continue;
437 if (na.priority > currentLowest) {
438 if (na.priority < nextLowest || nextLowest == 0) {
439 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700440 }
441 continue;
442 }
Wink Savillef2a62832011-04-07 14:23:45 -0700443 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700444 }
445 currentLowest = nextLowest;
446 nextLowest = 0;
447 }
448 }
449
450 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
451 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700452 mNetRequestersPids[i] = new ArrayList();
453 }
454
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500455 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700456
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700457 mNumDnsEntries = 0;
458
459 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
460 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800461 /*
462 * Create the network state trackers for Wi-Fi and mobile
463 * data. Maybe this could be done with a factory class,
464 * but it's not clear that it's worth it, given that
465 * the number of different network types is not going
466 * to change very often.
467 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700468 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700469 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700470 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800471 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700472 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700473 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700474 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700475 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700476 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700477 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700478 break;
479 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700480 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700481 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700482 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700483 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800484 case ConnectivityManager.TYPE_DUMMY:
485 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700486 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800487 mNetTrackers[netType].startMonitoring(context, mHandler);
488 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800489 case ConnectivityManager.TYPE_BLUETOOTH:
490 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
491 mNetTrackers[netType].startMonitoring(context, mHandler);
492 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800493 case ConnectivityManager.TYPE_ETHERNET:
494 mNetTrackers[netType] = EthernetDataTracker.getInstance();
495 mNetTrackers[netType].startMonitoring(context, mHandler);
496 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700497 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800498 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700499 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700500 continue;
501 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700502 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700503 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700504 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800505
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700506 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
507 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
508
509 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700510 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700511 mTethering.getTetherableWifiRegexs().length != 0 ||
512 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700513 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800514
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700515 mVpn = new Vpn(mContext, new VpnCallback());
516
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700517 try {
518 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700519 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700520 } catch (RemoteException e) {
521 loge("Error registering observer :" + e);
522 }
523
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700524 if (DBG) {
525 mInetLog = new ArrayList();
526 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700527
528 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
529 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800530
531 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800532 }
533
534 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700535 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800536 * @param preference the new preference
537 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700538 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800539 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700540
541 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800542 }
543
544 public int getNetworkPreference() {
545 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700546 int preference;
547 synchronized(this) {
548 preference = mNetworkPreference;
549 }
550 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800551 }
552
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700553 private void handleSetNetworkPreference(int preference) {
554 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700555 mNetConfigs[preference] != null &&
556 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700557 if (mNetworkPreference != preference) {
558 final ContentResolver cr = mContext.getContentResolver();
559 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
560 synchronized(this) {
561 mNetworkPreference = preference;
562 }
563 enforcePreference();
564 }
565 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800566 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700567
Wink Saville4f0de1e2011-08-04 15:01:58 -0700568 private int getConnectivityChangeDelay() {
569 final ContentResolver cr = mContext.getContentResolver();
570
571 /** Check system properties for the default value then use secure settings value, if any. */
572 int defaultDelay = SystemProperties.getInt(
573 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
574 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
575 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
576 defaultDelay);
577 }
578
The Android Open Source Project28527d22009-03-03 19:31:44 -0800579 private int getPersistedNetworkPreference() {
580 final ContentResolver cr = mContext.getContentResolver();
581
582 final int networkPrefSetting = Settings.Secure
583 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
584 if (networkPrefSetting != -1) {
585 return networkPrefSetting;
586 }
587
588 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
589 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700590
The Android Open Source Project28527d22009-03-03 19:31:44 -0800591 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700592 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800593 * In this method, we only tear down a non-preferred network. Establishing
594 * a connection to the preferred network is taken care of when we handle
595 * the disconnect event from the non-preferred network
596 * (see {@link #handleDisconnect(NetworkInfo)}).
597 */
598 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800600 return;
601
Robert Greenwalt2034b912009-08-12 16:08:25 -0700602 if (!mNetTrackers[mNetworkPreference].isAvailable())
603 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800604
Robert Greenwalt2034b912009-08-12 16:08:25 -0700605 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700606 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700607 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700608 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800609 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700610 " in enforcePreference");
611 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700612 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800613 }
614 }
615 }
616
617 private boolean teardown(NetworkStateTracker netTracker) {
618 if (netTracker.teardown()) {
619 netTracker.setTeardownRequested(true);
620 return true;
621 } else {
622 return false;
623 }
624 }
625
626 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700627 * Check if UID should be blocked from using the network represented by the
628 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700629 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700630 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
631 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700632
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700633 final boolean networkCostly;
634 final int uidRules;
635 synchronized (mRulesLock) {
636 networkCostly = mMeteredIfaces.contains(iface);
637 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700638 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700639
640 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
641 return true;
642 }
643
644 // no restrictive rules; network is visible
645 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700646 }
647
648 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700649 * Return a filtered {@link NetworkInfo}, potentially marked
650 * {@link DetailedState#BLOCKED} based on
651 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700652 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700653 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
654 NetworkInfo info = tracker.getNetworkInfo();
655 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700656 // network is blocked; clone and override state
657 info = new NetworkInfo(info);
658 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700659 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700660 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700661 }
662
663 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800664 * Return NetworkInfo for the active (i.e., connected) network interface.
665 * It is assumed that at most one network is active at a time. If more
666 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700667 * @return the info for the active network, or {@code null} if none is
668 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800669 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700670 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800671 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700672 enforceAccessPermission();
673 final int uid = Binder.getCallingUid();
674 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800675 }
676
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700677 @Override
678 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
679 enforceConnectivityInternalPermission();
680 return getNetworkInfo(mActiveDefaultNetwork, uid);
681 }
682
683 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800684 public NetworkInfo getNetworkInfo(int networkType) {
685 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700686 final int uid = Binder.getCallingUid();
687 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800688 }
689
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700690 private NetworkInfo getNetworkInfo(int networkType, int uid) {
691 NetworkInfo info = null;
692 if (isNetworkTypeValid(networkType)) {
693 final NetworkStateTracker tracker = mNetTrackers[networkType];
694 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700695 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700696 }
697 }
698 return info;
699 }
700
701 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800702 public NetworkInfo[] getAllNetworkInfo() {
703 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700704 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700705 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700706 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700707 for (NetworkStateTracker tracker : mNetTrackers) {
708 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700709 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700710 }
711 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800712 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700713 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800714 }
715
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700716 /**
717 * Return LinkProperties for the active (i.e., connected) default
718 * network interface. It is assumed that at most one default network
719 * is active at a time. If more than one is active, it is indeterminate
720 * which will be returned.
721 * @return the ip properties for the active network, or {@code null} if
722 * none is active
723 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700724 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700725 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700726 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700727 }
728
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700729 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700730 public LinkProperties getLinkProperties(int networkType) {
731 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700732 if (isNetworkTypeValid(networkType)) {
733 final NetworkStateTracker tracker = mNetTrackers[networkType];
734 if (tracker != null) {
735 return tracker.getLinkProperties();
736 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700737 }
738 return null;
739 }
740
Jeff Sharkey21062e72011-05-28 20:56:34 -0700741 @Override
742 public NetworkState[] getAllNetworkState() {
743 enforceAccessPermission();
744 final int uid = Binder.getCallingUid();
745 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700746 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700747 for (NetworkStateTracker tracker : mNetTrackers) {
748 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700749 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700750 result.add(new NetworkState(
751 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
752 }
753 }
754 }
755 return result.toArray(new NetworkState[result.size()]);
756 }
757
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700758 private NetworkState getNetworkStateUnchecked(int networkType) {
759 if (isNetworkTypeValid(networkType)) {
760 final NetworkStateTracker tracker = mNetTrackers[networkType];
761 if (tracker != null) {
762 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
763 tracker.getLinkCapabilities());
764 }
765 }
766 return null;
767 }
768
769 @Override
770 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
771 enforceAccessPermission();
772 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
773 if (state != null) {
774 try {
775 return mPolicyManager.getNetworkQuotaInfo(state);
776 } catch (RemoteException e) {
777 }
778 }
779 return null;
780 }
781
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782 public boolean setRadios(boolean turnOn) {
783 boolean result = true;
784 enforceChangePermission();
785 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700786 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800787 }
788 return result;
789 }
790
791 public boolean setRadio(int netType, boolean turnOn) {
792 enforceChangePermission();
793 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
794 return false;
795 }
796 NetworkStateTracker tracker = mNetTrackers[netType];
797 return tracker != null && tracker.setRadio(turnOn);
798 }
799
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700800 /**
801 * Used to notice when the calling process dies so we can self-expire
802 *
803 * Also used to know if the process has cleaned up after itself when
804 * our auto-expire timer goes off. The timer has a link to an object.
805 *
806 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 private class FeatureUser implements IBinder.DeathRecipient {
808 int mNetworkType;
809 String mFeature;
810 IBinder mBinder;
811 int mPid;
812 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800813 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814
815 FeatureUser(int type, String feature, IBinder binder) {
816 super();
817 mNetworkType = type;
818 mFeature = feature;
819 mBinder = binder;
820 mPid = getCallingPid();
821 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800822 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700823
Robert Greenwalt2034b912009-08-12 16:08:25 -0700824 try {
825 mBinder.linkToDeath(this, 0);
826 } catch (RemoteException e) {
827 binderDied();
828 }
829 }
830
831 void unlinkDeathRecipient() {
832 mBinder.unlinkToDeath(this, 0);
833 }
834
835 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800836 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800837 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
838 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700839 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700840 }
841
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700842 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700843 if (VDBG) {
844 log("ConnectivityService FeatureUser expire(" +
845 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
846 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
847 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700848 stopUsingNetworkFeature(this, false);
849 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800850
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500851 public boolean isSameUser(FeatureUser u) {
852 if (u == null) return false;
853
854 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
855 }
856
857 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
858 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
859 TextUtils.equals(mFeature, feature)) {
860 return true;
861 }
862 return false;
863 }
864
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800865 public String toString() {
866 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
867 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
868 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700869 }
870
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700871 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700872 public int startUsingNetworkFeature(int networkType, String feature,
873 IBinder binder) {
874 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800875 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700876 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700878 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700879 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700880 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700883 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700884
885 // TODO - move this into the MobileDataStateTracker
886 int usedNetworkType = networkType;
887 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800888 usedNetworkType = convertFeatureToNetworkType(feature);
889 if (usedNetworkType < 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700890 loge("Can't match any netTracker!");
Wink Savillef6b76692011-02-24 17:58:51 -0800891 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 }
893 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700894
895 if (mProtectedNetworks.contains(usedNetworkType)) {
896 enforceConnectivityInternalPermission();
897 }
898
Robert Greenwalt2034b912009-08-12 16:08:25 -0700899 NetworkStateTracker network = mNetTrackers[usedNetworkType];
900 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800901 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700902 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700903 NetworkStateTracker radio = mNetTrackers[networkType];
904 NetworkInfo ni = network.getNetworkInfo();
905
906 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800907 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800908 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
909 return Phone.APN_TYPE_NOT_AVAILABLE;
910 } else {
911 // else make the attempt anyway - probably giving REQUEST_STARTED below
912 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700913 }
914
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500915 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
916
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700917 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500918 boolean addToList = true;
919 if (restoreTimer < 0) {
920 // In case there is no timer is specified for the feature,
921 // make sure we don't add duplicate entry with the same request.
922 for (FeatureUser u : mFeatureUsers) {
923 if (u.isSameUser(f)) {
924 // Duplicate user is found. Do not add.
925 addToList = false;
926 break;
927 }
928 }
929 }
930
931 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700932 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
933 // this gets used for per-pid dns when connected
934 mNetRequestersPids[usedNetworkType].add(currentPid);
935 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700936 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700937
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700938 if (restoreTimer >= 0) {
939 mHandler.sendMessageDelayed(
940 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
941 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700942
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700943 if ((ni.isConnectedOrConnecting() == true) &&
944 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700945 if (ni.isConnected() == true) {
946 // add the pid-specific dns
repo sync3035f652011-08-02 13:39:06 -0700947 handleDnsConfigurationChange(usedNetworkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800948 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700949 return Phone.APN_ALREADY_ACTIVE;
950 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800951 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700952 return Phone.APN_REQUEST_STARTED;
953 }
954
955 // check if the radio in play can make another contact
956 // assume if cannot for now
957
Wink Savillee70c6f52010-12-03 12:01:38 -0800958 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700959 network.reconnect();
960 return Phone.APN_REQUEST_STARTED;
961 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800962 // need to remember this unsupported request so we respond appropriately on stop
963 synchronized(this) {
964 mFeatureUsers.add(f);
965 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
966 // this gets used for per-pid dns when connected
967 mNetRequestersPids[usedNetworkType].add(currentPid);
968 }
969 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700970 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700971 }
972 }
973 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800974 }
975
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700976 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800977 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700978 enforceChangePermission();
979
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700980 int pid = getCallingPid();
981 int uid = getCallingUid();
982
983 FeatureUser u = null;
984 boolean found = false;
985
986 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500987 for (FeatureUser x : mFeatureUsers) {
988 if (x.isSameUser(pid, uid, networkType, feature)) {
989 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700990 found = true;
991 break;
992 }
993 }
994 }
995 if (found && u != null) {
996 // stop regardless of how many other time this proc had called start
997 return stopUsingNetworkFeature(u, true);
998 } else {
999 // none found!
Robert Greenwalt78f28112011-08-02 17:18:41 -07001000 if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001001 return 1;
1002 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001003 }
1004
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001005 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1006 int networkType = u.mNetworkType;
1007 String feature = u.mFeature;
1008 int pid = u.mPid;
1009 int uid = u.mUid;
1010
1011 NetworkStateTracker tracker = null;
1012 boolean callTeardown = false; // used to carry our decision outside of sync block
1013
Robert Greenwalt2034b912009-08-12 16:08:25 -07001014 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001015 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001016 ": " + feature);
1017 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001018
The Android Open Source Project28527d22009-03-03 19:31:44 -08001019 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1020 return -1;
1021 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001022
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001023 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1024 // sync block
1025 synchronized(this) {
1026 // check if this process still has an outstanding start request
1027 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001028 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001029 return 1;
1030 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001031 u.unlinkDeathRecipient();
1032 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1033 // If we care about duplicate requests, check for that here.
1034 //
1035 // This is done to support the extension of a request - the app
1036 // can request we start the network feature again and renew the
1037 // auto-shutoff delay. Normal "stop" calls from the app though
1038 // do not pay attention to duplicate requests - in effect the
1039 // API does not refcount and a single stop will counter multiple starts.
1040 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001041 for (FeatureUser x : mFeatureUsers) {
1042 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001043 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001044 return 1;
1045 }
1046 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001047 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001048
1049 // TODO - move to MobileDataStateTracker
1050 int usedNetworkType = networkType;
1051 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -08001052 usedNetworkType = convertFeatureToNetworkType(feature);
1053 if (usedNetworkType < 0) {
1054 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001055 }
1056 }
1057 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001058 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001059 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001060 return -1;
1061 }
1062 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001063 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001064 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001065 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001066 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001067 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001068 "others still using it");
1069 return 1;
1070 }
1071 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001072 } else {
1073 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001074 }
1075 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001076 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001077 if (callTeardown) {
1078 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001079 return 1;
1080 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001081 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001082 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001083 }
1084
1085 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001086 * @deprecated use requestRouteToHostAddress instead
1087 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001088 * Ensure that a network route exists to deliver traffic to the specified
1089 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001090 * @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
The Android Open Source Project28527d22009-03-03 19:31:44 -08001094 * @return {@code true} on success, {@code false} on failure
1095 */
1096 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001097 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1098
1099 if (inetAddress == null) {
1100 return false;
1101 }
1102
1103 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1104 }
1105
1106 /**
1107 * Ensure that a network route exists to deliver traffic to the specified
1108 * host via the specified network interface.
1109 * @param networkType the type of the network over which traffic to the
1110 * specified host is to be routed
1111 * @param hostAddress the IP address of the host to which the route is
1112 * desired
1113 * @return {@code true} on success, {@code false} on failure
1114 */
1115 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001116 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001117 if (mProtectedNetworks.contains(networkType)) {
1118 enforceConnectivityInternalPermission();
1119 }
1120
The Android Open Source Project28527d22009-03-03 19:31:44 -08001121 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1122 return false;
1123 }
1124 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001125
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001126 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1127 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001128 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001129 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001130 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001131 }
1132 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001133 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001134 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001135 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001136 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001137 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001138 } catch (UnknownHostException e) {}
1139 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001140 }
1141
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001142 private boolean addRoute(LinkProperties p, RouteInfo r) {
1143 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001144 }
1145
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001146 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1147 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1148 }
1149
Robert Greenwalt98107422011-07-22 11:55:33 -07001150 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1151 return modifyRouteToAddress(lp, addr, true);
1152 }
1153
1154 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1155 return modifyRouteToAddress(lp, addr, false);
1156 }
1157
1158 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1159 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1160 if (bestRoute == null) {
1161 bestRoute = RouteInfo.makeHostRoute(addr);
1162 } else {
1163 if (bestRoute.getGateway().equals(addr)) {
1164 // if there is no better route, add the implied hostroute for our gateway
1165 bestRoute = RouteInfo.makeHostRoute(addr);
1166 } else {
1167 // if we will connect to this through another route, add a direct route
1168 // to it's gateway
1169 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1170 }
1171 }
1172 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1173 }
1174
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001175 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1176 boolean doAdd) {
1177 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1178
1179 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1180 loge("Error adding route - too much recursion");
1181 return false;
1182 }
1183
1184 if (r.isHostRoute() == false) {
1185 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1186 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001187 if (bestRoute.getGateway().equals(r.getGateway())) {
1188 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001189 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001190 } else {
1191 // if we will connect to our gateway through another route, add a direct
1192 // route to it's gateway
1193 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001194 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001195 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001196 }
1197 }
1198 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001199 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001200 mAddedRoutes.add(r);
1201 try {
1202 mNetd.addRoute(ifaceName, r);
1203 } catch (Exception e) {
1204 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001205 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001206 return false;
1207 }
1208 } else {
1209 // if we remove this one and there are no more like it, then refcount==0 and
1210 // we can remove it from the table
1211 mAddedRoutes.remove(r);
1212 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001213 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001214 try {
1215 mNetd.removeRoute(ifaceName, r);
1216 } catch (Exception e) {
1217 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001218 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001219 return false;
1220 }
1221 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001222 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001223 }
1224 }
1225 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001226 }
1227
1228 /**
1229 * @see ConnectivityManager#getBackgroundDataSetting()
1230 */
1231 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001232 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001233 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001234
The Android Open Source Project28527d22009-03-03 19:31:44 -08001235 /**
1236 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1237 */
1238 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1239 mContext.enforceCallingOrSelfPermission(
1240 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1241 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001242
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001243 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1244
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001245 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1246 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1247 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001248
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001249 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001250 Settings.Secure.putInt(mContext.getContentResolver(),
1251 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1252 Intent broadcast = new Intent(
1253 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1254 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001255 }
1256
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001257 /**
1258 * @see ConnectivityManager#getMobileDataEnabled()
1259 */
1260 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001261 // TODO: This detail should probably be in DataConnectionTracker's
1262 // which is where we store the value and maybe make this
1263 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001264 enforceAccessPermission();
1265 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1266 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001267 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001268 return retVal;
1269 }
1270
Robert Greenwalt34848c02011-03-25 13:09:25 -07001271 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001272 enforceConnectivityInternalPermission();
1273
Robert Greenwalt34848c02011-03-25 13:09:25 -07001274 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1275 (met ? ENABLED : DISABLED), networkType));
1276 }
1277
1278 private void handleSetDependencyMet(int networkType, boolean met) {
1279 if (mNetTrackers[networkType] != null) {
1280 if (DBG) {
1281 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1282 }
1283 mNetTrackers[networkType].setDependencyMet(met);
1284 }
1285 }
1286
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001287 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1288 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001289 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001290 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001291 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001292
1293 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001294 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001295 }
1296
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001297 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001298 // skip update when we've already applied rules
1299 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1300 if (oldRules == uidRules) return;
1301
1302 mUidRules.put(uid, uidRules);
1303 }
1304
1305 // TODO: dispatch into NMS to push rules towards kernel module
1306 // TODO: notify UID when it has requested targeted updates
1307 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001308
1309 @Override
1310 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1311 // only someone like NPMS should only be calling us
1312 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1313
1314 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001315 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001316 }
1317
1318 synchronized (mRulesLock) {
1319 mMeteredIfaces.clear();
1320 for (String iface : meteredIfaces) {
1321 mMeteredIfaces.add(iface);
1322 }
1323 }
1324 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001325 };
1326
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001327 /**
1328 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1329 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001330 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001331 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001332 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001333
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001334 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001335 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001336 }
1337
1338 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001339 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001340 if (VDBG) {
1341 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001342 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001343 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001344 }
1345 }
1346
The Android Open Source Project28527d22009-03-03 19:31:44 -08001347 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001348 mContext.enforceCallingOrSelfPermission(
1349 android.Manifest.permission.ACCESS_NETWORK_STATE,
1350 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001351 }
1352
1353 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001354 mContext.enforceCallingOrSelfPermission(
1355 android.Manifest.permission.CHANGE_NETWORK_STATE,
1356 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001357 }
1358
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001359 // TODO Make this a special check when it goes public
1360 private void enforceTetherChangePermission() {
1361 mContext.enforceCallingOrSelfPermission(
1362 android.Manifest.permission.CHANGE_NETWORK_STATE,
1363 "ConnectivityService");
1364 }
1365
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001366 private void enforceTetherAccessPermission() {
1367 mContext.enforceCallingOrSelfPermission(
1368 android.Manifest.permission.ACCESS_NETWORK_STATE,
1369 "ConnectivityService");
1370 }
1371
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001372 private void enforceConnectivityInternalPermission() {
1373 mContext.enforceCallingOrSelfPermission(
1374 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1375 "ConnectivityService");
1376 }
1377
The Android Open Source Project28527d22009-03-03 19:31:44 -08001378 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001379 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1380 * network, we ignore it. If it is for the active network, we send out a
1381 * broadcast. But first, we check whether it might be possible to connect
1382 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001383 * @param info the {@code NetworkInfo} for the network
1384 */
1385 private void handleDisconnect(NetworkInfo info) {
1386
Robert Greenwalt2034b912009-08-12 16:08:25 -07001387 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001388
Robert Greenwalt2034b912009-08-12 16:08:25 -07001389 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001390 /*
1391 * If the disconnected network is not the active one, then don't report
1392 * this as a loss of connectivity. What probably happened is that we're
1393 * getting the disconnect for a network that we explicitly disabled
1394 * in accordance with network preference policies.
1395 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001396 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001397 List pids = mNetRequestersPids[prevNetType];
1398 for (int i = 0; i<pids.size(); i++) {
1399 Integer pid = (Integer)pids.get(i);
1400 // will remove them because the net's no longer connected
1401 // need to do this now as only now do we know the pids and
1402 // can properly null things that are no longer referenced.
1403 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001405 }
1406
The Android Open Source Project28527d22009-03-03 19:31:44 -08001407 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1408 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1409 if (info.isFailover()) {
1410 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1411 info.setFailover(false);
1412 }
1413 if (info.getReason() != null) {
1414 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1415 }
1416 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001417 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1418 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001419 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001420
Robert Greenwalt34848c02011-03-25 13:09:25 -07001421 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001422 tryFailover(prevNetType);
1423 if (mActiveDefaultNetwork != -1) {
1424 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001425 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1426 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001427 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001428 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1429 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001430 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001431 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001432
1433 // Reset interface if no other connections are using the same interface
1434 boolean doReset = true;
1435 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1436 if (linkProperties != null) {
1437 String oldIface = linkProperties.getInterfaceName();
1438 if (TextUtils.isEmpty(oldIface) == false) {
1439 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1440 if (networkStateTracker == null) continue;
1441 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1442 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1443 LinkProperties l = networkStateTracker.getLinkProperties();
1444 if (l == null) continue;
1445 if (oldIface.equals(l.getInterfaceName())) {
1446 doReset = false;
1447 break;
1448 }
1449 }
1450 }
1451 }
1452 }
1453
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001454 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001455 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001456
Wink Saville4f0de1e2011-08-04 15:01:58 -07001457 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001458 /*
1459 * If the failover network is already connected, then immediately send
1460 * out a followup broadcast indicating successful failover
1461 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001462 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001463 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1464 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001465 }
1466 }
1467
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001468 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001469 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001470 * If this is a default network, check if other defaults are available.
1471 * Try to reconnect on all available and let them hash it out when
1472 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001473 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001474 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001475 if (mActiveDefaultNetwork == prevNetType) {
1476 mActiveDefaultNetwork = -1;
1477 }
1478
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001479 // don't signal a reconnect for anything lower or equal priority than our
1480 // current connected default
1481 // TODO - don't filter by priority now - nice optimization but risky
1482// int currentPriority = -1;
1483// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001484// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001485// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001486 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001487 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001488 if (mNetConfigs[checkType] == null) continue;
1489 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001490
1491// Enabling the isAvailable() optimization caused mobile to not get
1492// selected if it was in the middle of error handling. Specifically
1493// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1494// would not be available and we wouldn't get connected to anything.
1495// So removing the isAvailable() optimization below for now. TODO: This
1496// optimization should work and we need to investigate why it doesn't work.
1497// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1498// complete before it is really complete.
1499// if (!mNetTrackers[checkType].isAvailable()) continue;
1500
Robert Greenwalt34848c02011-03-25 13:09:25 -07001501// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001502
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001503 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1504 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1505 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1506 checkInfo.setFailover(true);
1507 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001508 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001509 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001510 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001512 }
1513
1514 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001515 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1516 }
1517
Wink Saville4f0de1e2011-08-04 15:01:58 -07001518 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1519 sendGeneralBroadcastDelayed(info, ConnectivityManager.CONNECTIVITY_ACTION, delayMs);
1520 }
1521
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001522 private void sendInetConditionBroadcast(NetworkInfo info) {
1523 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1524 }
1525
Wink Saville4f0de1e2011-08-04 15:01:58 -07001526 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001527 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001528 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1529 if (info.isFailover()) {
1530 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1531 info.setFailover(false);
1532 }
1533 if (info.getReason() != null) {
1534 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1535 }
1536 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001537 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1538 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001539 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001540 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001541 return intent;
1542 }
1543
1544 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1545 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1546 }
1547
1548 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1549 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001550 }
1551
1552 /**
1553 * Called when an attempt to fail over to another network has failed.
1554 * @param info the {@link NetworkInfo} for the failed network
1555 */
1556 private void handleConnectionFailure(NetworkInfo info) {
1557 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001558
Robert Greenwalt2034b912009-08-12 16:08:25 -07001559 String reason = info.getReason();
1560 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001561
Robert Greenwalte981bc52010-10-08 16:35:52 -07001562 String reasonText;
1563 if (reason == null) {
1564 reasonText = ".";
1565 } else {
1566 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001568 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001569
1570 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1571 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1572 if (getActiveNetworkInfo() == null) {
1573 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1574 }
1575 if (reason != null) {
1576 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1577 }
1578 if (extraInfo != null) {
1579 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1580 }
1581 if (info.isFailover()) {
1582 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1583 info.setFailover(false);
1584 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001585
Robert Greenwalt34848c02011-03-25 13:09:25 -07001586 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001587 tryFailover(info.getType());
1588 if (mActiveDefaultNetwork != -1) {
1589 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001590 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1591 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001592 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001593 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1594 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001595 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001596
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001597 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001598 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001599 /*
1600 * If the failover network is already connected, then immediately send
1601 * out a followup broadcast indicating successful failover
1602 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001603 if (mActiveDefaultNetwork != -1) {
1604 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001605 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001606 }
1607
1608 private void sendStickyBroadcast(Intent intent) {
1609 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001610 if (!mSystemReady) {
1611 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001612 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001613 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001614 if (DBG) {
1615 log("sendStickyBroadcast: NetworkInfo=" +
1616 intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
1617 }
1618
Dianne Hackborna417ff82009-12-08 19:45:14 -08001619 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001620 }
1621 }
1622
Wink Saville4f0de1e2011-08-04 15:01:58 -07001623 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1624 if (delayMs <= 0) {
1625 sendStickyBroadcast(intent);
1626 } else {
1627 if (DBG) log("sendStickyBroadcastDelayed: delayMs=" + delayMs + " intent=" + intent);
1628 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1629 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1630 }
1631 }
1632
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001633 void systemReady() {
1634 synchronized(this) {
1635 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001636 if (mInitialBroadcast != null) {
1637 mContext.sendStickyBroadcast(mInitialBroadcast);
1638 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001639 }
1640 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001641 // load the global proxy at startup
1642 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001643 }
1644
1645 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001646 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001647
1648 // snapshot isFailover, because sendConnectedBroadcast() resets it
1649 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001650 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001651
Robert Greenwalt2034b912009-08-12 16:08:25 -07001652 // if this is a default net and other default is running
1653 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001654 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001655 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1656 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001657 mNetConfigs[mActiveDefaultNetwork].priority >
1658 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001659 mNetworkPreference == mActiveDefaultNetwork) {
1660 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001661 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001662 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001663 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001664 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001665 teardown(thisNet);
1666 return;
1667 } else {
1668 // tear down the other
1669 NetworkStateTracker otherNet =
1670 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001671 if (DBG) {
1672 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001673 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001674 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001675 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001676 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001677 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001678 return;
1679 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001680 }
1681 }
1682 synchronized (ConnectivityService.this) {
1683 // have a new default network, release the transition wakelock in a second
1684 // if it's held. The second pause is to allow apps to reconnect over the
1685 // new network
1686 if (mNetTransitionWakeLock.isHeld()) {
1687 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001688 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001689 mNetTransitionWakeLockSerialNumber, 0),
1690 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001691 }
1692 }
1693 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001694 // this will cause us to come up initially as unconnected and switching
1695 // to connected after our normal pause unless somebody reports us as reall
1696 // disconnected
1697 mDefaultInetConditionPublished = 0;
1698 mDefaultConnectionSequence++;
1699 mInetConditionChangeInFlight = false;
1700 // Don't do this - if we never sign in stay, grey
1701 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001702 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001703 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001704 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001705 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001706 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001707 }
1708
The Android Open Source Project28527d22009-03-03 19:31:44 -08001709 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001710 * After a change in the connectivity state of a network. We're mainly
1711 * concerned with making sure that the list of DNS servers is set up
1712 * according to which networks are connected, and ensuring that the
1713 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001714 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001715 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001716 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1717
The Android Open Source Project28527d22009-03-03 19:31:44 -08001718 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001719 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001720 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001721 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001722 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001723
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001724 LinkProperties curLp = mCurrentLinkProperties[netType];
1725 LinkProperties newLp = null;
1726
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001727 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001728 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001729 if (VDBG) {
1730 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1731 " doReset=" + doReset + " resetMask=" + resetMask +
1732 "\n curLp=" + curLp +
1733 "\n newLp=" + newLp);
1734 }
1735
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001736 if (curLp != null) {
1737 if (curLp.isIdenticalInterfaceName(newLp)) {
1738 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1739 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1740 for (LinkAddress linkAddr : car.removed) {
1741 if (linkAddr.getAddress() instanceof Inet4Address) {
1742 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1743 }
1744 if (linkAddr.getAddress() instanceof Inet6Address) {
1745 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1746 }
Wink Saville051a6642011-07-13 13:44:13 -07001747 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001748 if (DBG) {
1749 log("handleConnectivityChange: addresses changed" +
1750 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1751 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001752 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001753 } else {
1754 if (DBG) {
1755 log("handleConnectivityChange: address are the same reset per doReset" +
1756 " linkProperty[" + netType + "]:" +
1757 " resetMask=" + resetMask);
1758 }
Wink Saville051a6642011-07-13 13:44:13 -07001759 }
1760 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001761 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001762 if (DBG) {
1763 log("handleConnectivityChange: interface not not equivalent reset both" +
1764 " linkProperty[" + netType + "]:" +
1765 " resetMask=" + resetMask);
1766 }
Wink Saville051a6642011-07-13 13:44:13 -07001767 }
Wink Saville051a6642011-07-13 13:44:13 -07001768 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001769 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001770 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001771 }
1772 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001773 if (VDBG) {
1774 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1775 " doReset=" + doReset + " resetMask=" + resetMask +
1776 "\n curLp=" + curLp +
1777 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001778 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001779 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001780 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001781 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001782
Robert Greenwalt8d777252011-08-15 12:31:55 -07001783 if (doReset || resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001784 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1785 if (linkProperties != null) {
1786 String iface = linkProperties.getInterfaceName();
1787 if (TextUtils.isEmpty(iface) == false) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001788 if (doReset || resetMask != 0) {
1789 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1790 NetworkUtils.resetConnections(iface, resetMask);
1791 }
1792 if (resetDns) {
1793 if (DBG) log("resetting DNS cache for " + iface);
1794 try {
1795 mNetd.flushInterfaceDnsCache(iface);
1796 } catch (Exception e) {
1797 // never crash - catch them all
1798 loge("Exception resetting dns cache: " + e);
1799 }
1800 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001801 }
1802 }
1803 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001804
1805 // TODO: Temporary notifying upstread change to Tethering.
1806 // @see bug/4455071
1807 /** Notify TetheringService if interface name has been changed. */
1808 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1809 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1810 if (isTetheringSupported()) {
1811 mTethering.handleTetherIfaceChange();
1812 }
1813 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001814 }
1815
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001816 /**
1817 * Add and remove routes using the old properties (null if not previously connected),
1818 * new properties (null if becoming disconnected). May even be double null, which
1819 * is a noop.
1820 * Uses isLinkDefault to determine if default routes should be set or conversely if
1821 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001822 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001823 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07001824 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1825 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001826 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001827 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1828 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001829 if (curLp != null) {
1830 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001831 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001832 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001833 } else if (newLp != null) {
1834 routeDiff.added = newLp.getRoutes();
1835 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001836 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001837
Robert Greenwalt8d777252011-08-15 12:31:55 -07001838 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1839
Robert Greenwalt98107422011-07-22 11:55:33 -07001840 for (RouteInfo r : routeDiff.removed) {
1841 if (isLinkDefault || ! r.isDefaultRoute()) {
1842 removeRoute(curLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001843 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001844 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001845
Robert Greenwalt98107422011-07-22 11:55:33 -07001846 for (RouteInfo r : routeDiff.added) {
1847 if (isLinkDefault || ! r.isDefaultRoute()) {
1848 addRoute(newLp, r);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001849 } else {
1850 // many radios add a default route even when we don't want one.
1851 // remove the default route unless somebody else has asked for it
1852 String ifaceName = newLp.getInterfaceName();
1853 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
1854 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1855 try {
1856 mNetd.removeRoute(ifaceName, r);
1857 } catch (Exception e) {
1858 // never crash - catch them all
1859 loge("Exception trying to remove a route: " + e);
1860 }
1861 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001862 }
1863 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001864
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001865 if (!isLinkDefault) {
1866 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07001867 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001868 // routes changed - remove all old dns entries and add new
1869 if (curLp != null) {
1870 for (InetAddress oldDns : curLp.getDnses()) {
1871 removeRouteToAddress(curLp, oldDns);
1872 }
1873 }
1874 if (newLp != null) {
1875 for (InetAddress newDns : newLp.getDnses()) {
1876 addRouteToAddress(newLp, newDns);
1877 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001878 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001879 } else {
1880 // no change in routes, check for change in dns themselves
1881 for (InetAddress oldDns : dnsDiff.removed) {
1882 removeRouteToAddress(curLp, oldDns);
1883 }
1884 for (InetAddress newDns : dnsDiff.added) {
1885 addRouteToAddress(newLp, newDns);
1886 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001887 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001888 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001889 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001890 }
1891
1892
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001893 /**
1894 * Reads the network specific TCP buffer sizes from SystemProperties
1895 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1896 * wide use
1897 */
1898 public void updateNetworkSettings(NetworkStateTracker nt) {
1899 String key = nt.getTcpBufferSizesPropName();
1900 String bufferSizes = SystemProperties.get(key);
1901
1902 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001903 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001904
1905 // Setting to default values so we won't be stuck to previous values
1906 key = "net.tcp.buffersize.default";
1907 bufferSizes = SystemProperties.get(key);
1908 }
1909
1910 // Set values in kernel
1911 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001912 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001913 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001914 + "] which comes from [" + key + "]");
1915 }
1916 setBufferSize(bufferSizes);
1917 }
1918 }
1919
1920 /**
1921 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1922 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1923 *
1924 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1925 * writeMin, writeInitial, writeMax"
1926 */
1927 private void setBufferSize(String bufferSizes) {
1928 try {
1929 String[] values = bufferSizes.split(",");
1930
1931 if (values.length == 6) {
1932 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001933 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1934 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1935 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1936 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1937 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1938 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001939 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001940 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001941 }
1942 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001943 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001944 }
1945 }
1946
Robert Greenwalt2034b912009-08-12 16:08:25 -07001947 /**
1948 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1949 * on the highest priority active net which this process requested.
1950 * If there aren't any, clear it out
1951 */
1952 private void reassessPidDns(int myPid, boolean doBump)
1953 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001954 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001955 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001956 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001957 continue;
1958 }
1959 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001960 if (nt.getNetworkInfo().isConnected() &&
1961 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001962 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001963 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001964 List pids = mNetRequestersPids[i];
1965 for (int j=0; j<pids.size(); j++) {
1966 Integer pid = (Integer)pids.get(j);
1967 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001968 Collection<InetAddress> dnses = p.getDnses();
1969 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001970 if (doBump) {
1971 bumpDns();
1972 }
1973 return;
1974 }
1975 }
1976 }
1977 }
1978 // nothing found - delete
1979 for (int i = 1; ; i++) {
1980 String prop = "net.dns" + i + "." + myPid;
1981 if (SystemProperties.get(prop).length() == 0) {
1982 if (doBump) {
1983 bumpDns();
1984 }
1985 return;
1986 }
1987 SystemProperties.set(prop, "");
1988 }
1989 }
1990
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001991 // return true if results in a change
1992 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001993 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001994 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001995 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001996 String dnsString = dns.getHostAddress();
1997 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1998 changed = true;
1999 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2000 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002001 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002002 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002003 }
2004
2005 private void bumpDns() {
2006 /*
2007 * Bump the property that tells the name resolver library to reread
2008 * the DNS server list from the properties.
2009 */
2010 String propVal = SystemProperties.get("net.dnschange");
2011 int n = 0;
2012 if (propVal.length() != 0) {
2013 try {
2014 n = Integer.parseInt(propVal);
2015 } catch (NumberFormatException e) {}
2016 }
2017 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002018 /*
2019 * Tell the VMs to toss their DNS caches
2020 */
2021 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2022 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002023 /*
2024 * Connectivity events can happen before boot has completed ...
2025 */
2026 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002027 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002028 }
2029
Chia-chi Yehcc844502011-07-14 18:01:57 -07002030 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002031 private boolean updateDns(String network, String iface,
2032 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002033 boolean changed = false;
2034 int last = 0;
2035 if (dnses.size() == 0 && mDefaultDns != null) {
2036 ++last;
2037 String value = mDefaultDns.getHostAddress();
2038 if (!value.equals(SystemProperties.get("net.dns1"))) {
2039 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002040 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002041 }
2042 changed = true;
2043 SystemProperties.set("net.dns1", value);
2044 }
2045 } else {
2046 for (InetAddress dns : dnses) {
2047 ++last;
2048 String key = "net.dns" + last;
2049 String value = dns.getHostAddress();
2050 if (!changed && value.equals(SystemProperties.get(key))) {
2051 continue;
2052 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002053 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002054 log("adding dns " + value + " for " + network);
2055 }
2056 changed = true;
2057 SystemProperties.set(key, value);
2058 }
2059 }
2060 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2061 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002062 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002063 changed = true;
2064 SystemProperties.set(key, "");
2065 }
2066 mNumDnsEntries = last;
2067
Robert Greenwaltfce71862011-07-25 16:06:25 -07002068 if (changed) {
2069 try {
2070 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2071 mNetd.setDefaultInterfaceForDns(iface);
2072 } catch (Exception e) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002073 loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002074 }
2075 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002076 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2077 SystemProperties.set("net.dns.search", domains);
2078 changed = true;
2079 }
2080 return changed;
2081 }
2082
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002083 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002084 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002085 NetworkStateTracker nt = mNetTrackers[netType];
2086 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002087 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002088 if (p == null) return;
2089 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002090 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002091 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002092 String network = nt.getNetworkInfo().getTypeName();
2093 synchronized (mDnsLock) {
2094 if (!mDnsOverridden) {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002095 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002096 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002097 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002098 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002099 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002100 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002101 NetworkUtils.makeStrings(dnses));
2102 } catch (Exception e) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002103 loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002104 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002105 // set per-pid dns for attached secondary nets
2106 List pids = mNetRequestersPids[netType];
2107 for (int y=0; y< pids.size(); y++) {
2108 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002109 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002110 }
2111 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002112 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002113 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002114 }
2115
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002116 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002117 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2118 NETWORK_RESTORE_DELAY_PROP_NAME);
2119 if(restoreDefaultNetworkDelayStr != null &&
2120 restoreDefaultNetworkDelayStr.length() != 0) {
2121 try {
2122 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2123 } catch (NumberFormatException e) {
2124 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002125 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002126 // if the system property isn't set, use the value for the apn type
2127 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2128
2129 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2130 (mNetConfigs[networkType] != null)) {
2131 ret = mNetConfigs[networkType].restoreTime;
2132 }
2133 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 }
2135
2136 @Override
2137 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002138 if (mContext.checkCallingOrSelfPermission(
2139 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002140 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002141 pw.println("Permission Denial: can't dump ConnectivityService " +
2142 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2143 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002144 return;
2145 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 pw.println();
2147 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002148 if (nst != null) {
2149 if (nst.getNetworkInfo().isConnected()) {
2150 pw.println("Active network: " + nst.getNetworkInfo().
2151 getTypeName());
2152 }
2153 pw.println(nst.getNetworkInfo());
2154 pw.println(nst);
2155 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002156 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002157 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002158
2159 pw.println("Network Requester Pids:");
2160 for (int net : mPriorityList) {
2161 String pidString = net + ": ";
2162 for (Object pid : mNetRequestersPids[net]) {
2163 pidString = pidString + pid.toString() + ", ";
2164 }
2165 pw.println(pidString);
2166 }
2167 pw.println();
2168
2169 pw.println("FeatureUsers:");
2170 for (Object requester : mFeatureUsers) {
2171 pw.println(requester.toString());
2172 }
2173 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002174
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002175 synchronized (this) {
2176 pw.println("NetworkTranstionWakeLock is currently " +
2177 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2178 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2179 }
2180 pw.println();
2181
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002182 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002183
2184 if (mInetLog != null) {
2185 pw.println();
2186 pw.println("Inet condition reports:");
2187 for(int i = 0; i < mInetLog.size(); i++) {
2188 pw.println(mInetLog.get(i));
2189 }
2190 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002191 }
2192
Robert Greenwalt2034b912009-08-12 16:08:25 -07002193 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002194 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002195 public MyHandler(Looper looper) {
2196 super(looper);
2197 }
2198
The Android Open Source Project28527d22009-03-03 19:31:44 -08002199 @Override
2200 public void handleMessage(Message msg) {
2201 NetworkInfo info;
2202 switch (msg.what) {
2203 case NetworkStateTracker.EVENT_STATE_CHANGED:
2204 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002205 int type = info.getType();
2206 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002207
Wink Savillee70c6f52010-12-03 12:01:38 -08002208 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002209 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002210 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002211
2212 // Connectivity state changed:
2213 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002214 // [12-9] Network subtype (for mobile network, as defined
2215 // by TelephonyManager)
2216 // [8-3] Detailed state ordinal (as defined by
2217 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002218 // [2-0] Network type (as defined by ConnectivityManager)
2219 int eventLogParam = (info.getType() & 0x7) |
2220 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2221 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002222 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002223 eventLogParam);
2224
2225 if (info.getDetailedState() ==
2226 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002227 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002228 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002229 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002230 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002231 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002232 // the logic here is, handle SUSPENDED the same as
2233 // DISCONNECTED. The only difference being we are
2234 // broadcasting an intent with NetworkInfo that's
2235 // suspended. This allows the applications an
2236 // opportunity to handle DISCONNECTED and SUSPENDED
2237 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002238 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002239 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002240 handleConnect(info);
2241 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002243 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002244 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002245 // TODO: Temporary allowing network configuration
2246 // change not resetting sockets.
2247 // @see bug/4455071
2248 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002250 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002251 String causedBy = null;
2252 synchronized (ConnectivityService.this) {
2253 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2254 mNetTransitionWakeLock.isHeld()) {
2255 mNetTransitionWakeLock.release();
2256 causedBy = mNetTransitionWakeLockCausedBy;
2257 }
2258 }
2259 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002260 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002261 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002262 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002263 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002264 FeatureUser u = (FeatureUser)msg.obj;
2265 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002266 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002267 case EVENT_INET_CONDITION_CHANGE:
2268 {
2269 int netType = msg.arg1;
2270 int condition = msg.arg2;
2271 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002272 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002273 }
2274 case EVENT_INET_CONDITION_HOLD_END:
2275 {
2276 int netType = msg.arg1;
2277 int sequence = msg.arg2;
2278 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002279 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002280 }
2281 case EVENT_SET_NETWORK_PREFERENCE:
2282 {
2283 int preference = msg.arg1;
2284 handleSetNetworkPreference(preference);
2285 break;
2286 }
2287 case EVENT_SET_BACKGROUND_DATA:
2288 {
2289 boolean enabled = (msg.arg1 == ENABLED);
2290 handleSetBackgroundData(enabled);
2291 break;
2292 }
2293 case EVENT_SET_MOBILE_DATA:
2294 {
2295 boolean enabled = (msg.arg1 == ENABLED);
2296 handleSetMobileData(enabled);
2297 break;
2298 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002299 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2300 {
2301 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002302 break;
2303 }
2304 case EVENT_SET_DEPENDENCY_MET:
2305 {
2306 boolean met = (msg.arg1 == ENABLED);
2307 handleSetDependencyMet(msg.arg2, met);
2308 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002309 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002310 case EVENT_RESTORE_DNS:
2311 {
2312 if (mActiveDefaultNetwork != -1) {
2313 handleDnsConfigurationChange(mActiveDefaultNetwork);
2314 }
2315 break;
2316 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002317 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2318 {
2319 Intent intent = (Intent)msg.obj;
2320 log("EVENT_SEND_STICKY_BROADCAST_INTENT: sendStickyBroadcast intent=" + intent);
2321 sendStickyBroadcast(intent);
2322 break;
2323 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002324 }
2325 }
2326 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002327
2328 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002329 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002330 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002331
2332 if (isTetheringSupported()) {
2333 return mTethering.tether(iface);
2334 } else {
2335 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2336 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002337 }
2338
2339 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002340 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002341 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002342
2343 if (isTetheringSupported()) {
2344 return mTethering.untether(iface);
2345 } else {
2346 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2347 }
2348 }
2349
2350 // javadoc from interface
2351 public int getLastTetherError(String iface) {
2352 enforceTetherAccessPermission();
2353
2354 if (isTetheringSupported()) {
2355 return mTethering.getLastTetherError(iface);
2356 } else {
2357 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2358 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002359 }
2360
2361 // TODO - proper iface API for selection by property, inspection, etc
2362 public String[] getTetherableUsbRegexs() {
2363 enforceTetherAccessPermission();
2364 if (isTetheringSupported()) {
2365 return mTethering.getTetherableUsbRegexs();
2366 } else {
2367 return new String[0];
2368 }
2369 }
2370
2371 public String[] getTetherableWifiRegexs() {
2372 enforceTetherAccessPermission();
2373 if (isTetheringSupported()) {
2374 return mTethering.getTetherableWifiRegexs();
2375 } else {
2376 return new String[0];
2377 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002378 }
2379
Danica Chang96567052010-08-11 14:54:43 -07002380 public String[] getTetherableBluetoothRegexs() {
2381 enforceTetherAccessPermission();
2382 if (isTetheringSupported()) {
2383 return mTethering.getTetherableBluetoothRegexs();
2384 } else {
2385 return new String[0];
2386 }
2387 }
2388
Mike Lockwooded4a1742011-07-19 13:04:47 -07002389 public int setUsbTethering(boolean enable) {
2390 enforceTetherAccessPermission();
2391 if (isTetheringSupported()) {
2392 return mTethering.setUsbTethering(enable);
2393 } else {
2394 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2395 }
2396 }
2397
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002398 // TODO - move iface listing, queries, etc to new module
2399 // javadoc from interface
2400 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002401 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002402 return mTethering.getTetherableIfaces();
2403 }
2404
2405 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002406 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002407 return mTethering.getTetheredIfaces();
2408 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002409
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002410 public String[] getTetheringErroredIfaces() {
2411 enforceTetherAccessPermission();
2412 return mTethering.getErroredIfaces();
2413 }
2414
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002415 // if ro.tether.denied = true we default to no tethering
2416 // gservices could set the secure setting to 1 though to enable it on a build where it
2417 // had previously been turned off.
2418 public boolean isTetheringSupported() {
2419 enforceTetherAccessPermission();
2420 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002421 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2422 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2423 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002424 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002425
2426 // An API NetworkStateTrackers can call when they lose their network.
2427 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2428 // whichever happens first. The timer is started by the first caller and not
2429 // restarted by subsequent callers.
2430 public void requestNetworkTransitionWakelock(String forWhom) {
2431 enforceConnectivityInternalPermission();
2432 synchronized (this) {
2433 if (mNetTransitionWakeLock.isHeld()) return;
2434 mNetTransitionWakeLockSerialNumber++;
2435 mNetTransitionWakeLock.acquire();
2436 mNetTransitionWakeLockCausedBy = forWhom;
2437 }
2438 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002439 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002440 mNetTransitionWakeLockSerialNumber, 0),
2441 mNetTransitionWakeLockTimeout);
2442 return;
2443 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002444
Robert Greenwalt986c7412010-09-08 15:24:47 -07002445 // 100 percent is full good, 0 is full bad.
2446 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002447 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002448 mContext.enforceCallingOrSelfPermission(
2449 android.Manifest.permission.STATUS_BAR,
2450 "ConnectivityService");
2451
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002452 if (DBG) {
2453 int pid = getCallingPid();
2454 int uid = getCallingUid();
2455 String s = pid + "(" + uid + ") reports inet is " +
2456 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2457 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2458 mInetLog.add(s);
2459 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2460 mInetLog.remove(0);
2461 }
2462 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002463 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002464 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2465 }
2466
2467 private void handleInetConditionChange(int netType, int condition) {
2468 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002469 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002470 netType + ", condition=" + condition +
2471 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2472 }
2473 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002474 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002475 return;
2476 }
2477 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002478 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002479 return;
2480 }
2481 mDefaultInetCondition = condition;
2482 int delay;
2483 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002484 if (VDBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002485 // setup a new hold to debounce this
2486 if (mDefaultInetCondition > 50) {
2487 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2488 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2489 } else {
2490 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2491 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2492 }
2493 mInetConditionChangeInFlight = true;
2494 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2495 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2496 } else {
2497 // we've set the new condition, when this hold ends that will get
2498 // picked up
Robert Greenwalt78f28112011-08-02 17:18:41 -07002499 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002500 }
2501 }
2502
2503 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002504 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002505 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002506 ", condition =" + mDefaultInetCondition +
2507 ", published condition =" + mDefaultInetConditionPublished);
2508 }
2509 mInetConditionChangeInFlight = false;
2510
2511 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002512 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002513 return;
2514 }
2515 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002516 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002517 return;
2518 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002519 // TODO: Figure out why this optimization sometimes causes a
2520 // change in mDefaultInetCondition to be missed and the
2521 // UI to not be updated.
2522 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2523 // if (DBG) log("no change in condition - aborting");
2524 // return;
2525 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002526 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2527 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002528 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002529 return;
2530 }
2531 mDefaultInetConditionPublished = mDefaultInetCondition;
2532 sendInetConditionBroadcast(networkInfo);
2533 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002534 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002535
2536 public synchronized ProxyProperties getProxy() {
2537 if (mGlobalProxy != null) return mGlobalProxy;
2538 if (mDefaultProxy != null) return mDefaultProxy;
2539 return null;
2540 }
2541
2542 public void setGlobalProxy(ProxyProperties proxyProperties) {
2543 enforceChangePermission();
2544 synchronized (mGlobalProxyLock) {
2545 if (proxyProperties == mGlobalProxy) return;
2546 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2547 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2548
2549 String host = "";
2550 int port = 0;
2551 String exclList = "";
2552 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2553 mGlobalProxy = new ProxyProperties(proxyProperties);
2554 host = mGlobalProxy.getHost();
2555 port = mGlobalProxy.getPort();
2556 exclList = mGlobalProxy.getExclusionList();
2557 } else {
2558 mGlobalProxy = null;
2559 }
2560 ContentResolver res = mContext.getContentResolver();
2561 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2562 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002563 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002564 exclList);
2565 }
2566
2567 if (mGlobalProxy == null) {
2568 proxyProperties = mDefaultProxy;
2569 }
2570 sendProxyBroadcast(proxyProperties);
2571 }
2572
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002573 private void loadGlobalProxy() {
2574 ContentResolver res = mContext.getContentResolver();
2575 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2576 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2577 String exclList = Settings.Secure.getString(res,
2578 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2579 if (!TextUtils.isEmpty(host)) {
2580 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2581 synchronized (mGlobalProxyLock) {
2582 mGlobalProxy = proxyProperties;
2583 }
2584 }
2585 }
2586
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002587 public ProxyProperties getGlobalProxy() {
2588 synchronized (mGlobalProxyLock) {
2589 return mGlobalProxy;
2590 }
2591 }
2592
2593 private void handleApplyDefaultProxy(int type) {
2594 // check if new default - push it out to all VM if so
2595 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2596 synchronized (this) {
2597 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2598 if (mDefaultProxy == proxy) return;
Robert Greenwalt027f5052011-07-29 10:03:37 -07002599 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002600 mDefaultProxy = proxy;
2601 } else {
2602 mDefaultProxy = null;
2603 }
2604 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002605 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002606 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2607 if (mGlobalProxy != null) return;
2608 sendProxyBroadcast(proxy);
2609 }
2610
2611 private void handleDeprecatedGlobalHttpProxy() {
2612 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2613 Settings.Secure.HTTP_PROXY);
2614 if (!TextUtils.isEmpty(proxy)) {
2615 String data[] = proxy.split(":");
2616 String proxyHost = data[0];
2617 int proxyPort = 8080;
2618 if (data.length > 1) {
2619 try {
2620 proxyPort = Integer.parseInt(data[1]);
2621 } catch (NumberFormatException e) {
2622 return;
2623 }
2624 }
2625 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2626 setGlobalProxy(p);
2627 }
2628 }
2629
2630 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002631 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002632 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002633 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002634 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2635 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002636 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002637 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002638 }
2639
2640 private static class SettingsObserver extends ContentObserver {
2641 private int mWhat;
2642 private Handler mHandler;
2643 SettingsObserver(Handler handler, int what) {
2644 super(handler);
2645 mHandler = handler;
2646 mWhat = what;
2647 }
2648
2649 void observe(Context context) {
2650 ContentResolver resolver = context.getContentResolver();
2651 resolver.registerContentObserver(Settings.Secure.getUriFor(
2652 Settings.Secure.HTTP_PROXY), false, this);
2653 }
2654
2655 @Override
2656 public void onChange(boolean selfChange) {
2657 mHandler.obtainMessage(mWhat).sendToTarget();
2658 }
2659 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002660
2661 private void log(String s) {
2662 Slog.d(TAG, s);
2663 }
2664
2665 private void loge(String s) {
2666 Slog.e(TAG, s);
2667 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002668
Wink Savillef6b76692011-02-24 17:58:51 -08002669 int convertFeatureToNetworkType(String feature){
2670 int networkType = -1;
2671 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2672 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2673 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2674 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2675 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2676 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2677 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2678 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2679 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2680 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2681 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2682 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2683 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2684 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2685 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2686 }
2687 return networkType;
2688 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002689
2690 private static <T> T checkNotNull(T value, String message) {
2691 if (value == null) {
2692 throw new NullPointerException(message);
2693 }
2694 return value;
2695 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002696
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002697 /**
2698 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002699 * VpnBuilder and not available in ConnectivityManager. Permissions
2700 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002701 * @hide
2702 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002703 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002704 public boolean protectVpn(ParcelFileDescriptor socket) {
2705 try {
2706 int type = mActiveDefaultNetwork;
2707 if (ConnectivityManager.isNetworkTypeValid(type)) {
2708 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2709 return true;
2710 }
2711 } catch (Exception e) {
2712 // ignore
2713 } finally {
2714 try {
2715 socket.close();
2716 } catch (Exception e) {
2717 // ignore
2718 }
2719 }
2720 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002721 }
2722
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002723 /**
2724 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002725 * and not available in ConnectivityManager. Permissions are checked
2726 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002727 * @hide
2728 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002729 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002730 public boolean prepareVpn(String oldPackage, String newPackage) {
2731 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002732 }
2733
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002734 /**
2735 * Configure a TUN interface and return its file descriptor. Parameters
2736 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002737 * and not available in ConnectivityManager. Permissions are checked in
2738 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002739 * @hide
2740 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002741 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002742 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002743 return mVpn.establish(config);
2744 }
2745
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002746 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002747 * Start legacy VPN and return an intent to VpnDialogs. This method is
2748 * used by VpnSettings and not available in ConnectivityManager.
2749 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002750 * @hide
2751 */
2752 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002753 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2754 mVpn.startLegacyVpn(config, racoon, mtpd);
2755 }
2756
2757 /**
2758 * Return the information of the ongoing legacy VPN. This method is used
2759 * by VpnSettings and not available in ConnectivityManager. Permissions
2760 * are checked in Vpn class.
2761 * @hide
2762 */
2763 @Override
2764 public LegacyVpnInfo getLegacyVpnInfo() {
2765 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002766 }
2767
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002768 /**
2769 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2770 * through NetworkStateTracker since it works differently. For example, it
2771 * needs to override DNS servers but never takes the default routes. It
2772 * relies on another data network, and it could keep existing connections
2773 * alive after reconnecting, switching between networks, or even resuming
2774 * from deep sleep. Calls from applications should be done synchronously
2775 * to avoid race conditions. As these are all hidden APIs, refactoring can
2776 * be done whenever a better abstraction is developed.
2777 */
2778 public class VpnCallback {
2779
2780 private VpnCallback() {
2781 }
2782
Chia-chi Yehcc844502011-07-14 18:01:57 -07002783 public void override(List<String> dnsServers, List<String> searchDomains) {
2784 if (dnsServers == null) {
2785 restore();
2786 return;
2787 }
2788
2789 // Convert DNS servers into addresses.
2790 List<InetAddress> addresses = new ArrayList<InetAddress>();
2791 for (String address : dnsServers) {
2792 // Double check the addresses and remove invalid ones.
2793 try {
2794 addresses.add(InetAddress.parseNumericAddress(address));
2795 } catch (Exception e) {
2796 // ignore
2797 }
2798 }
2799 if (addresses.isEmpty()) {
2800 restore();
2801 return;
2802 }
2803
2804 // Concatenate search domains into a string.
2805 StringBuilder buffer = new StringBuilder();
2806 if (searchDomains != null) {
2807 for (String domain : searchDomains) {
2808 buffer.append(domain).append(' ');
2809 }
2810 }
2811 String domains = buffer.toString().trim();
2812
2813 // Apply DNS changes.
2814 boolean changed = false;
2815 synchronized (mDnsLock) {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002816 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002817 mDnsOverridden = true;
2818 }
2819 if (changed) {
2820 bumpDns();
2821 }
2822
2823 // TODO: temporarily remove http proxy?
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002824 }
2825
Chia-chi Yehcc844502011-07-14 18:01:57 -07002826 public void restore() {
2827 synchronized (mDnsLock) {
2828 if (!mDnsOverridden) {
2829 return;
2830 }
2831 mDnsOverridden = false;
2832 }
2833 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002834 }
2835 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002836}