blob: 3ae7a3f8c4462e218da76ff3ad3dd8e0e3ed4c8b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070023
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Wink Savillec9822c52011-07-14 12:23:28 -070036import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080037import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070038import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070040import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070042import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070043import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070044import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070046import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.net.Proxy;
48import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070049import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.wifi.WifiStateTracker;
51import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040052import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070054import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070055import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070056import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Looper;
58import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070059import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070060import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070061import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.ServiceManager;
63import android.os.SystemProperties;
64import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070065import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070068import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Chia-chi Yeh2e467642011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070072import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080073import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074import com.android.server.connectivity.Vpn;
75
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070076import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070077import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070080import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -070082import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070083import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070084import java.net.InetAddress;
85import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070087import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070088import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070089import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070090import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070091import java.util.List;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94/**
95 * @hide
96 */
97public class ConnectivityService extends IConnectivityManager.Stub {
98
Robert Greenwaltba175a52010-10-05 19:12:26 -070099 private static final boolean DBG = true;
Wink Savillee8222252011-07-13 13:44:13 -0700100 private static final boolean VDBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final String TAG = "ConnectivityService";
102
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103 private static final boolean LOGD_RULES = false;
104
Robert Greenwalt42acef32009-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 Greenwaltf43396c2011-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 Greenwaltd0e18ff2010-01-26 11:40:34 -0800115 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800116 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800117
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700118 private Vpn mVpn;
119
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
121 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122 /** Currently active network rules by UID. */
123 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700124 /** Set of ifaces that are costly. */
125 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700126
The Android Open Source Project9066cfe2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700133
134 /**
Wink Savillee8222252011-07-13 13:44:13 -0700135 * The link properties that define the current links
136 */
137 private LinkProperties mCurrentLinkProperties[];
138
139 /**
Robert Greenwalt42acef32009-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 Greenwalt42acef32009-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 Project9066cfe2009-03-03 19:31:44 -0800150 private Context mContext;
151 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-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 Project9066cfe2009-03-03 19:31:44 -0800158
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700159 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700161 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700164 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800166 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
167
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700168 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700169 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700170
Robert Greenwalt8dcc28b2010-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 Greenwaltf3331232010-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 Greenwalt434203a2010-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 Greenwaltd55a6b42011-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 Yeh44bb2512011-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 Saville2b30afd2011-08-05 11:40:22 -0700257 /**
Wink Saville628b0852011-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 Saville2b30afd2011-08-05 11:40:22 -0700261 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville628b0852011-08-04 15:01:58 -0700262
Robert Greenwalt42acef32009-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 Ondo3bed4c92011-07-19 11:23:37 -0500267 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700268
Mike Lockwood0f79b542009-08-14 14:18:49 -0400269 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800270 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400271
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700272 private PowerManager.WakeLock mNetTransitionWakeLock;
273 private String mNetTransitionWakeLockCausedBy = "";
274 private int mNetTransitionWakeLockSerialNumber;
275 private int mNetTransitionWakeLockTimeout;
276
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700277 private InetAddress mDefaultDns;
278
Robert Greenwalt0a46db52011-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 Greenwalt4e8dfef2010-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 Greenwalt434203a2010-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700295 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700296 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700297
Robert Greenwalt511288a2009-12-07 11:33:18 -0800298 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700299 public int mSimultaneity;
300 public int mType;
301 public RadioAttributes(String init) {
302 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700303 mType = Integer.parseInt(fragments[0]);
304 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700305 }
306 }
307 RadioAttributes[] mRadioAttributes;
308
Robert Greenwalt50393202011-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 Sharkeyc006f1a2011-05-19 17:12:49 -0700312 public ConnectivityService(
313 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800314 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800315
Wink Savillebb08caf2010-09-02 19:23:52 -0700316 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
317 handlerThread.start();
318 mHandler = new MyHandler(handlerThread.getLooper());
319
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800320 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
321 Settings.Secure.BACKGROUND_DATA, 1) == 1);
322
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800323 // setup our unique device name
Robert Greenwalt733c6292010-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 Greenwaltde8383c2010-01-14 17:47:58 -0800331 }
332
Robert Greenwalte90aa5e2010-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 Greenwalte5903732011-02-22 16:00:42 -0800341 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
342 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800343 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700344 }
345
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700346 mContext = checkNotNull(context, "missing Context");
347 mNetd = checkNotNull(netd, "missing INetworkManagementService");
348 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700349
Jeff Sharkeyc006f1a2011-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 Greenwalt58d4c592011-08-02 17:18:41 -0700354 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700355 }
356
357 final PowerManager powerManager = (PowerManager) context.getSystemService(
358 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-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 Greenwalt42acef32009-08-12 16:08:25 -0700363 mNetTrackers = new NetworkStateTracker[
364 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700365 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700368
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700369 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700370 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700371
Robert Greenwalt42acef32009-08-12 16:08:25 -0700372 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700373 String[] raStrings = context.getResources().getStringArray(
374 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-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 Savilleed9c02b2010-12-03 12:01:38 -0800378 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700379 continue;
380 }
381 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800382 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700383 r.mType);
384 continue;
385 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700386 mRadioAttributes[r.mType] = r;
387 }
388
Robert Greenwalt5154ae762009-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700393 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700394 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800395 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700396 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398 }
Wink Saville975c8482011-04-07 14:23:45 -0700399 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800400 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700401 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700402 continue;
403 }
Wink Saville975c8482011-04-07 14:23:45 -0700404 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800405 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700406 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700407 continue;
408 }
Wink Saville975c8482011-04-07 14:23:45 -0700409 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700410 mNetworksDefined++;
411 } catch(Exception e) {
412 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700413 }
414 }
415
Robert Greenwalt50393202011-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 Greenwalt5154ae762009-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700434 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 if (na == null) continue;
Wink Saville975c8482011-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 Greenwalt5154ae762009-10-30 14:17:42 -0700440 }
441 continue;
442 }
Wink Saville975c8482011-04-07 14:23:45 -0700443 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-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 Greenwalt42acef32009-08-12 16:08:25 -0700452 mNetRequestersPids[i] = new ArrayList();
453 }
454
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500455 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700456
Robert Greenwalt5154ae762009-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 Project9066cfe2009-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 Greenwalt5154ae762009-10-30 14:17:42 -0700468 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700469 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700470 case ConnectivityManager.TYPE_WIFI:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800471 if (DBG) log("Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700472 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700473 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700474 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700475 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700476 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700477 wst.startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700478 break;
479 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700480 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700481 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700482 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700483 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800484 case ConnectivityManager.TYPE_DUMMY:
485 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700486 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800487 mNetTrackers[netType].startMonitoring(context, mHandler);
488 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800489 case ConnectivityManager.TYPE_BLUETOOTH:
490 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
491 mNetTrackers[netType].startMonitoring(context, mHandler);
492 break;
Benoit Goby19970692010-12-22 14:29:40 -0800493 case ConnectivityManager.TYPE_ETHERNET:
494 mNetTrackers[netType] = EthernetDataTracker.getInstance();
495 mNetTrackers[netType].startMonitoring(context, mHandler);
496 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700497 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800498 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700499 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700500 continue;
501 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700502 mCurrentLinkProperties[netType] = null;
Robert Greenwaltc96e6cc2011-07-15 11:16:45 -0700503 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700504 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800505
Chia-chi Yehc9338302011-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 Greenwaltccf83af12011-06-02 17:30:47 -0700510 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700511 mTethering.getTetherableWifiRegexs().length != 0 ||
512 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700513 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800514
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700515 mVpn = new Vpn(mContext, new VpnCallback());
516
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700517 try {
518 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700519 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700520 } catch (RemoteException e) {
521 loge("Error registering observer :" + e);
522 }
523
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700524 if (DBG) {
525 mInetLog = new ArrayList();
526 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700527
528 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
529 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800530
531 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 }
533
534 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700535 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 * @param preference the new preference
537 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700538 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700540
541 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 }
543
544 public int getNetworkPreference() {
545 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700546 int preference;
547 synchronized(this) {
548 preference = mNetworkPreference;
549 }
550 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 }
552
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700553 private void handleSetNetworkPreference(int preference) {
554 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700555 mNetConfigs[preference] != null &&
556 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-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 Project9066cfe2009-03-03 19:31:44 -0800566 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700567
Wink Saville628b0852011-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 Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -0700590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700592 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700599 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 return;
601
Robert Greenwalt42acef32009-08-12 16:08:25 -0700602 if (!mNetTrackers[mNetworkPreference].isAvailable())
603 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604
Robert Greenwalt42acef32009-08-12 16:08:25 -0700605 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700606 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700607 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700608 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800609 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700610 " in enforcePreference");
611 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700612 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-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 Sharkeyfdfef572011-06-16 15:07:48 -0700627 * Check if UID should be blocked from using the network represented by the
628 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700629 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700630 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
631 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700632
Jeff Sharkeyfdfef572011-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 Sharkeyc006f1a2011-05-19 17:12:49 -0700638 }
Jeff Sharkeyfdfef572011-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 Sharkeyc006f1a2011-05-19 17:12:49 -0700646 }
647
648 /**
Jeff Sharkeyfdfef572011-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 Sharkeyc006f1a2011-05-19 17:12:49 -0700652 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700653 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
654 NetworkInfo info = tracker.getNetworkInfo();
655 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-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 Sharkeyc006f1a2011-05-19 17:12:49 -0700659 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700660 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700661 }
662
663 /**
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-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 Project9066cfe2009-03-03 19:31:44 -0800669 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700670 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700672 enforceAccessPermission();
673 final int uid = Binder.getCallingUid();
674 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676
Jeff Sharkeyc006f1a2011-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 Project9066cfe2009-03-03 19:31:44 -0800684 public NetworkInfo getNetworkInfo(int networkType) {
685 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700686 final int uid = Binder.getCallingUid();
687 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
689
Jeff Sharkeyc006f1a2011-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 Sharkeyfdfef572011-06-16 15:07:48 -0700695 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700696 }
697 }
698 return info;
699 }
700
701 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 public NetworkInfo[] getAllNetworkInfo() {
703 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700704 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700705 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700706 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700707 for (NetworkStateTracker tracker : mNetTrackers) {
708 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700709 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700710 }
711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700713 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715
Robert Greenwaltd192dad2010-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 Sharkeyc006f1a2011-05-19 17:12:49 -0700724 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700725 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700726 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700727 }
728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700730 public LinkProperties getLinkProperties(int networkType) {
731 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-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 Greenwaltd192dad2010-09-14 09:18:02 -0700737 }
738 return null;
739 }
740
Jeff Sharkeyd2a45872011-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 Sharkeyfdfef572011-06-16 15:07:48 -0700746 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700747 for (NetworkStateTracker tracker : mNetTrackers) {
748 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700749 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-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 Sharkeyf0ceede2011-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 Project9066cfe2009-03-03 19:31:44 -0800782 public boolean setRadios(boolean turnOn) {
783 boolean result = true;
784 enforceChangePermission();
785 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700786 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-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 Greenwalt9c75d4a2009-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 Greenwalt42acef32009-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 Greenwaltb9285352009-12-21 18:24:07 -0800813 long mCreateTime;
Robert Greenwalt42acef32009-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 Greenwaltb9285352009-12-21 18:24:07 -0800822 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700823
Robert Greenwalt42acef32009-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 Savilleed9c02b2010-12-03 12:01:38 -0800836 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800837 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
838 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700839 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700840 }
841
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700842 public void expire() {
Robert Greenwalt58d4c592011-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 Greenwalt9c75d4a2009-09-27 17:27:04 -0700848 stopUsingNetworkFeature(this, false);
849 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800850
Kazuhiro Ondo3bed4c92011-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 Greenwaltb9285352009-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 Greenwalt42acef32009-08-12 16:08:25 -0700869 }
870
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700871 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700872 public int startUsingNetworkFeature(int networkType, String feature,
873 IBinder binder) {
874 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800875 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700878 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700879 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700880 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700882
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700883 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700884
885 // TODO - move this into the MobileDataStateTracker
886 int usedNetworkType = networkType;
887 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800888 usedNetworkType = convertFeatureToNetworkType(feature);
889 if (usedNetworkType < 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700890 loge("Can't match any netTracker!");
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800891 usedNetworkType = networkType;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 }
893 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700894
895 if (mProtectedNetworks.contains(usedNetworkType)) {
896 enforceConnectivityInternalPermission();
897 }
898
Robert Greenwalt42acef32009-08-12 16:08:25 -0700899 NetworkStateTracker network = mNetTrackers[usedNetworkType];
900 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800901 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700902 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700903 NetworkStateTracker radio = mNetTrackers[networkType];
904 NetworkInfo ni = network.getNetworkInfo();
905
906 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800907 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-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 Greenwalt42acef32009-08-12 16:08:25 -0700913 }
914
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500915 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
916
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700917 synchronized(this) {
Kazuhiro Ondo3bed4c92011-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 Greenwalt9c75d4a2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700936 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700937
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700938 if (restoreTimer >= 0) {
939 mHandler.sendMessageDelayed(
940 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
941 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700942
Robert Greenwalta64bf832009-08-19 20:19:33 -0700943 if ((ni.isConnectedOrConnecting() == true) &&
944 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700945 if (ni.isConnected() == true) {
946 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -0700947 handleDnsConfigurationChange(usedNetworkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800948 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700949 return Phone.APN_ALREADY_ACTIVE;
950 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800951 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-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 Savilleed9c02b2010-12-03 12:01:38 -0800958 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700959 network.reconnect();
960 return Phone.APN_REQUEST_STARTED;
961 } else {
Robert Greenwalt0be1e982010-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 Greenwalt02648a42010-05-18 10:52:51 -0700970 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700971 }
972 }
973 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
975
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700976 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700978 enforceChangePermission();
979
Robert Greenwalt9c75d4a2009-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 Ondo3bed4c92011-07-19 11:23:37 -0500987 for (FeatureUser x : mFeatureUsers) {
988 if (x.isSameUser(pid, uid, networkType, feature)) {
989 u = x;
Robert Greenwalt9c75d4a2009-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 Greenwalt58d4c592011-08-02 17:18:41 -07001000 if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001001 return 1;
1002 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001003 }
1004
Robert Greenwalt9c75d4a2009-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 Greenwalt42acef32009-08-12 16:08:25 -07001014 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001015 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001016 ": " + feature);
1017 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1020 return -1;
1021 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001022
Robert Greenwalt9c75d4a2009-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 Savilleed9c02b2010-12-03 12:01:38 -08001028 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001029 return 1;
1030 }
Robert Greenwalt9c75d4a2009-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 Ondo3bed4c92011-07-19 11:23:37 -05001041 for (FeatureUser x : mFeatureUsers) {
1042 if (x.isSameUser(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001043 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001044 return 1;
1045 }
1046 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001047 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001048
1049 // TODO - move to MobileDataStateTracker
1050 int usedNetworkType = networkType;
1051 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -08001052 usedNetworkType = convertFeatureToNetworkType(feature);
1053 if (usedNetworkType < 0) {
1054 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001055 }
1056 }
1057 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001058 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001059 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001060 return -1;
1061 }
1062 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001063 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001064 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001065 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001066 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001067 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001068 "others still using it");
1069 return 1;
1070 }
1071 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001072 } else {
1073 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001074 }
1075 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001076 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001077 if (callTeardown) {
1078 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001079 return 1;
1080 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001081 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 }
1084
1085 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001086 * @deprecated use requestRouteToHostAddress instead
1087 *
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-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 Project9066cfe2009-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 Greenwalt585ac0f2010-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 Project9066cfe2009-03-03 19:31:44 -08001116 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001117 if (mProtectedNetworks.contains(networkType)) {
1118 enforceConnectivityInternalPermission();
1119 }
1120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1122 return false;
1123 }
1124 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001125
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001126 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1127 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001128 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001129 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001130 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001131 }
1132 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001134 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001135 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001136 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001137 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001138 } catch (UnknownHostException e) {}
1139 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001140 }
1141
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001142 private boolean addRoute(LinkProperties p, RouteInfo r) {
1143 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001144 }
1145
Robert Greenwalt0a46db52011-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 Greenwaltad55d352011-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 Greenwalt0a46db52011-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 Greenwalt476f5522011-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 Greenwalt0a46db52011-07-14 14:28:05 -07001189 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-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 Greenwalt0a46db52011-07-14 14:28:05 -07001194 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001195 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001196 }
1197 }
1198 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001199 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-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 Greenwalt58d4c592011-08-02 17:18:41 -07001205 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-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 Greenwalt58d4c592011-08-02 17:18:41 -07001213 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001214 try {
1215 mNetd.removeRoute(ifaceName, r);
1216 } catch (Exception e) {
1217 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001218 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001219 return false;
1220 }
1221 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001222 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001223 }
1224 }
1225 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
1227
1228 /**
1229 * @see ConnectivityManager#getBackgroundDataSetting()
1230 */
1231 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001232 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001234
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -07001242
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001243 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1244
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001245 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1246 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001249 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-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 Greenwalt86e9e552009-07-16 17:21:39 -07001255 }
1256
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001257 /**
1258 * @see ConnectivityManager#getMobileDataEnabled()
1259 */
1260 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-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 Greenwaltc03fa502010-02-23 18:58:05 -08001264 enforceAccessPermission();
1265 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1266 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001267 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001268 return retVal;
1269 }
1270
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001271 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001272 enforceConnectivityInternalPermission();
1273
Robert Greenwaltd55a6b42011-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 Sharkeyc006f1a2011-05-19 17:12:49 -07001287 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1288 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001289 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001290 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001291 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001292
1293 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001294 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001295 }
1296
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001297 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-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 Sharkeyfdfef572011-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 Greenwalt58d4c592011-08-02 17:18:41 -07001315 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-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 Sharkeyc006f1a2011-05-19 17:12:49 -07001325 };
1326
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001327 /**
1328 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1329 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001330 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001331 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001332 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001333
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001334 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001335 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001336 }
1337
1338 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001339 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001340 if (VDBG) {
1341 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001342 }
Wink Savillee7982682010-12-07 10:31:02 -08001343 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001344 }
1345 }
1346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001348 mContext.enforceCallingOrSelfPermission(
1349 android.Manifest.permission.ACCESS_NETWORK_STATE,
1350 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
1352
1353 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001354 mContext.enforceCallingOrSelfPermission(
1355 android.Manifest.permission.CHANGE_NETWORK_STATE,
1356 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358
Robert Greenwaltd0e18ff2010-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 Greenwalt2a091d72010-02-11 18:18:40 -08001366 private void enforceTetherAccessPermission() {
1367 mContext.enforceCallingOrSelfPermission(
1368 android.Manifest.permission.ACCESS_NETWORK_STATE,
1369 "ConnectivityService");
1370 }
1371
Robert Greenwalt14f2ef42010-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 Project9066cfe2009-03-03 19:31:44 -08001378 /**
Robert Greenwalt86e9e552009-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 Project9066cfe2009-03-03 19:31:44 -08001383 * @param info the {@code NetworkInfo} for the network
1384 */
1385 private void handleDisconnect(NetworkInfo info) {
1386
Robert Greenwalt42acef32009-08-12 16:08:25 -07001387 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
Robert Greenwalt42acef32009-08-12 16:08:25 -07001389 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-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 Greenwaltd55a6b42011-03-25 13:09:25 -07001396 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-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 Project9066cfe2009-03-03 19:31:44 -08001404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -07001417 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1418 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001420
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001421 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001422 tryFailover(prevNetType);
1423 if (mActiveDefaultNetwork != -1) {
1424 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001425 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1426 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001427 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001428 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1429 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001430 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001431 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-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 Greenwaltda03c4e2010-01-20 19:29:41 -08001454 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001455 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001456
Wink Saville628b0852011-08-04 15:01:58 -07001457 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-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 Greenwaltf21ef7d2011-01-11 13:56:33 -08001462 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001463 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1464 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001465 }
1466 }
1467
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001468 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001469 /*
Robert Greenwaltbff90182011-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 Greenwalt42acef32009-08-12 16:08:25 -07001473 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001474 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001475 if (mActiveDefaultNetwork == prevNetType) {
1476 mActiveDefaultNetwork = -1;
1477 }
1478
Robert Greenwaltf21ef7d2011-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 Greenwaltd55a6b42011-03-25 13:09:25 -07001484// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001485// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001486 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001487 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001488 if (mNetConfigs[checkType] == null) continue;
1489 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-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 Greenwaltd55a6b42011-03-25 13:09:25 -07001501// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001502
Robert Greenwaltf21ef7d2011-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 Greenwalt42acef32009-08-12 16:08:25 -07001508 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001509 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513
1514 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001515 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1516 }
1517
Wink Saville628b0852011-08-04 15:01:58 -07001518 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1519 sendGeneralBroadcastDelayed(info, ConnectivityManager.CONNECTIVITY_ACTION, delayMs);
1520 }
1521
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001522 private void sendInetConditionBroadcast(NetworkInfo info) {
1523 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1524 }
1525
Wink Saville628b0852011-08-04 15:01:58 -07001526 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001527 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -07001537 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1538 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001540 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-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 Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -08001558
Robert Greenwalt42acef32009-08-12 16:08:25 -07001559 String reason = info.getReason();
1560 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001561
Robert Greenwalt572172b2010-10-08 16:35:52 -07001562 String reasonText;
1563 if (reason == null) {
1564 reasonText = ".";
1565 } else {
1566 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001568 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-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 Greenwaltda03c4e2010-01-20 19:29:41 -08001585
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001586 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001587 tryFailover(info.getType());
1588 if (mActiveDefaultNetwork != -1) {
1589 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001590 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1591 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001592 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001593 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1594 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001595 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001596
Robert Greenwalt029be812010-09-20 18:01:43 -07001597 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001598 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-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 Greenwaltf21ef7d2011-01-11 13:56:33 -08001603 if (mActiveDefaultNetwork != -1) {
1604 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001605 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001606 }
1607
1608 private void sendStickyBroadcast(Intent intent) {
1609 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001610 if (!mSystemReady) {
1611 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001612 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001613 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Saville628b0852011-08-04 15:01:58 -07001614 if (DBG) {
1615 log("sendStickyBroadcast: NetworkInfo=" +
1616 intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
1617 }
1618
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001619 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001620 }
1621 }
1622
Wink Saville628b0852011-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 Lockwood0f79b542009-08-14 14:18:49 -04001633 void systemReady() {
1634 synchronized(this) {
1635 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001636 if (mInitialBroadcast != null) {
1637 mContext.sendStickyBroadcast(mInitialBroadcast);
1638 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001639 }
1640 }
Robert Greenwalt434203a2010-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 Project9066cfe2009-03-03 19:31:44 -08001643 }
1644
1645 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001646 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647
1648 // snapshot isFailover, because sendConnectedBroadcast() resets it
1649 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001650 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651
Robert Greenwalt42acef32009-08-12 16:08:25 -07001652 // if this is a default net and other default is running
1653 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001654 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001655 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1656 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001657 mNetConfigs[mActiveDefaultNetwork].priority >
1658 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001659 mNetworkPreference == mActiveDefaultNetwork) {
1660 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001661 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001662 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001663 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001664 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001665 teardown(thisNet);
1666 return;
1667 } else {
1668 // tear down the other
1669 NetworkStateTracker otherNet =
1670 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001671 if (DBG) {
1672 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001673 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001674 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001675 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001676 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001677 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001678 return;
1679 }
Robert Greenwalt14f2ef42010-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 Greenwaltf3331232010-09-24 14:32:21 -07001688 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001689 mNetTransitionWakeLockSerialNumber, 0),
1690 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001691 }
1692 }
1693 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-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 Greenwalt42acef32009-08-12 16:08:25 -07001702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001704 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001705 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001706 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 /**
Robert Greenwaltc76b8fa2010-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 Project9066cfe2009-03-03 19:31:44 -08001714 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001715 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001716 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001719 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001720 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001722 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001723
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001724 LinkProperties curLp = mCurrentLinkProperties[netType];
1725 LinkProperties newLp = null;
1726
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001727 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001728 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-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 Greenwalt0a46db52011-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 Savillee8222252011-07-13 13:44:13 -07001747 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001748 if (DBG) {
1749 log("handleConnectivityChange: addresses changed" +
1750 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1751 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001752 }
Robert Greenwalt0a46db52011-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 Savillee8222252011-07-13 13:44:13 -07001759 }
1760 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001761 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-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 Savillee8222252011-07-13 13:44:13 -07001767 }
Wink Savillee8222252011-07-13 13:44:13 -07001768 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001769 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001770 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001771 }
1772 } else {
Robert Greenwalt0a46db52011-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 Greenwalt42acef32009-08-12 16:08:25 -07001778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001780 mCurrentLinkProperties[netType] = newLp;
1781 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001782
Wink Savillee8222252011-07-13 13:44:13 -07001783 if (doReset || resetMask != 0) {
Robert Greenwaltec896c62011-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) {
Wink Savillee8222252011-07-13 13:44:13 -07001788 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1789 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001790 }
1791 }
1792 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001793
1794 // TODO: Temporary notifying upstread change to Tethering.
1795 // @see bug/4455071
1796 /** Notify TetheringService if interface name has been changed. */
1797 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1798 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1799 if (isTetheringSupported()) {
1800 mTethering.handleTetherIfaceChange();
1801 }
1802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001805 /**
1806 * Add and remove routes using the old properties (null if not previously connected),
1807 * new properties (null if becoming disconnected). May even be double null, which
1808 * is a noop.
1809 * Uses isLinkDefault to determine if default routes should be set or conversely if
1810 * host routes should be set to the dns servers
1811 */
1812 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1813 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001814 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1815 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001816 if (curLp != null) {
1817 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001818 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001819 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001820 } else if (newLp != null) {
1821 routeDiff.added = newLp.getRoutes();
1822 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001823 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001824
Robert Greenwaltad55d352011-07-22 11:55:33 -07001825 for (RouteInfo r : routeDiff.removed) {
1826 if (isLinkDefault || ! r.isDefaultRoute()) {
1827 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001828 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001829 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001830
Robert Greenwaltad55d352011-07-22 11:55:33 -07001831 for (RouteInfo r : routeDiff.added) {
1832 if (isLinkDefault || ! r.isDefaultRoute()) {
1833 addRoute(newLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001834 }
1835 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001836
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001837 if (!isLinkDefault) {
1838 // handle DNS routes
Robert Greenwaltad55d352011-07-22 11:55:33 -07001839 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1840 // no change in routes, check for change in dns themselves
1841 for (InetAddress oldDns : dnsDiff.removed) {
1842 removeRouteToAddress(curLp, oldDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001843 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001844 for (InetAddress newDns : dnsDiff.added) {
1845 addRouteToAddress(newLp, newDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001846 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001847 } else {
1848 // routes changed - remove all old dns entries and add new
1849 if (curLp != null) {
1850 for (InetAddress oldDns : curLp.getDnses()) {
1851 removeRouteToAddress(curLp, oldDns);
1852 }
1853 }
1854 if (newLp != null) {
1855 for (InetAddress newDns : newLp.getDnses()) {
1856 addRouteToAddress(newLp, newDns);
1857 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001858 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001859 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001860 }
1861 }
1862
1863
Irfan Sheriffd649c122010-06-09 15:39:36 -07001864 /**
1865 * Reads the network specific TCP buffer sizes from SystemProperties
1866 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1867 * wide use
1868 */
1869 public void updateNetworkSettings(NetworkStateTracker nt) {
1870 String key = nt.getTcpBufferSizesPropName();
1871 String bufferSizes = SystemProperties.get(key);
1872
1873 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001874 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001875
1876 // Setting to default values so we won't be stuck to previous values
1877 key = "net.tcp.buffersize.default";
1878 bufferSizes = SystemProperties.get(key);
1879 }
1880
1881 // Set values in kernel
1882 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001883 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001884 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001885 + "] which comes from [" + key + "]");
1886 }
1887 setBufferSize(bufferSizes);
1888 }
1889 }
1890
1891 /**
1892 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1893 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1894 *
1895 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1896 * writeMin, writeInitial, writeMax"
1897 */
1898 private void setBufferSize(String bufferSizes) {
1899 try {
1900 String[] values = bufferSizes.split(",");
1901
1902 if (values.length == 6) {
1903 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001904 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1905 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1906 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1907 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1908 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1909 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001910 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001911 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001912 }
1913 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001914 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001915 }
1916 }
1917
Robert Greenwalt42acef32009-08-12 16:08:25 -07001918 /**
1919 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1920 * on the highest priority active net which this process requested.
1921 * If there aren't any, clear it out
1922 */
1923 private void reassessPidDns(int myPid, boolean doBump)
1924 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001925 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001926 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001927 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001928 continue;
1929 }
1930 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001931 if (nt.getNetworkInfo().isConnected() &&
1932 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001933 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001934 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001935 List pids = mNetRequestersPids[i];
1936 for (int j=0; j<pids.size(); j++) {
1937 Integer pid = (Integer)pids.get(j);
1938 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001939 Collection<InetAddress> dnses = p.getDnses();
1940 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001941 if (doBump) {
1942 bumpDns();
1943 }
1944 return;
1945 }
1946 }
1947 }
1948 }
1949 // nothing found - delete
1950 for (int i = 1; ; i++) {
1951 String prop = "net.dns" + i + "." + myPid;
1952 if (SystemProperties.get(prop).length() == 0) {
1953 if (doBump) {
1954 bumpDns();
1955 }
1956 return;
1957 }
1958 SystemProperties.set(prop, "");
1959 }
1960 }
1961
Robert Greenwalt10398722010-12-17 15:20:36 -08001962 // return true if results in a change
1963 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001964 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001965 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001966 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001967 String dnsString = dns.getHostAddress();
1968 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1969 changed = true;
1970 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1971 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001972 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001973 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001974 }
1975
1976 private void bumpDns() {
1977 /*
1978 * Bump the property that tells the name resolver library to reread
1979 * the DNS server list from the properties.
1980 */
1981 String propVal = SystemProperties.get("net.dnschange");
1982 int n = 0;
1983 if (propVal.length() != 0) {
1984 try {
1985 n = Integer.parseInt(propVal);
1986 } catch (NumberFormatException e) {}
1987 }
1988 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001989 /*
1990 * Tell the VMs to toss their DNS caches
1991 */
1992 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1993 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001994 /*
1995 * Connectivity events can happen before boot has completed ...
1996 */
1997 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001998 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001999 }
2000
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002001 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002002 private boolean updateDns(String network, String iface,
2003 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002004 boolean changed = false;
2005 int last = 0;
2006 if (dnses.size() == 0 && mDefaultDns != null) {
2007 ++last;
2008 String value = mDefaultDns.getHostAddress();
2009 if (!value.equals(SystemProperties.get("net.dns1"))) {
2010 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002011 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002012 }
2013 changed = true;
2014 SystemProperties.set("net.dns1", value);
2015 }
2016 } else {
2017 for (InetAddress dns : dnses) {
2018 ++last;
2019 String key = "net.dns" + last;
2020 String value = dns.getHostAddress();
2021 if (!changed && value.equals(SystemProperties.get(key))) {
2022 continue;
2023 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002024 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002025 log("adding dns " + value + " for " + network);
2026 }
2027 changed = true;
2028 SystemProperties.set(key, value);
2029 }
2030 }
2031 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2032 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002033 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002034 changed = true;
2035 SystemProperties.set(key, "");
2036 }
2037 mNumDnsEntries = last;
2038
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002039 if (changed) {
2040 try {
2041 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2042 mNetd.setDefaultInterfaceForDns(iface);
2043 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002044 loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002045 }
2046 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002047 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2048 SystemProperties.set("net.dns.search", domains);
2049 changed = true;
2050 }
2051 return changed;
2052 }
2053
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002054 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002055 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002056 NetworkStateTracker nt = mNetTrackers[netType];
2057 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002058 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002059 if (p == null) return;
2060 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002061 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002062 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002063 String network = nt.getNetworkInfo().getTypeName();
2064 synchronized (mDnsLock) {
2065 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002066 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002067 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002068 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002069 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002070 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002071 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002072 NetworkUtils.makeStrings(dnses));
2073 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002074 loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002075 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002076 // set per-pid dns for attached secondary nets
2077 List pids = mNetRequestersPids[netType];
2078 for (int y=0; y< pids.size(); y++) {
2079 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002080 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002083 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002085 }
2086
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002087 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002088 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2089 NETWORK_RESTORE_DELAY_PROP_NAME);
2090 if(restoreDefaultNetworkDelayStr != null &&
2091 restoreDefaultNetworkDelayStr.length() != 0) {
2092 try {
2093 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2094 } catch (NumberFormatException e) {
2095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002097 // if the system property isn't set, use the value for the apn type
2098 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2099
2100 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2101 (mNetConfigs[networkType] != null)) {
2102 ret = mNetConfigs[networkType].restoreTime;
2103 }
2104 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106
2107 @Override
2108 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002109 if (mContext.checkCallingOrSelfPermission(
2110 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002112 pw.println("Permission Denial: can't dump ConnectivityService " +
2113 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2114 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 return;
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 pw.println();
2118 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002119 if (nst != null) {
2120 if (nst.getNetworkInfo().isConnected()) {
2121 pw.println("Active network: " + nst.getNetworkInfo().
2122 getTypeName());
2123 }
2124 pw.println(nst.getNetworkInfo());
2125 pw.println(nst);
2126 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002129
2130 pw.println("Network Requester Pids:");
2131 for (int net : mPriorityList) {
2132 String pidString = net + ": ";
2133 for (Object pid : mNetRequestersPids[net]) {
2134 pidString = pidString + pid.toString() + ", ";
2135 }
2136 pw.println(pidString);
2137 }
2138 pw.println();
2139
2140 pw.println("FeatureUsers:");
2141 for (Object requester : mFeatureUsers) {
2142 pw.println(requester.toString());
2143 }
2144 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002145
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002146 synchronized (this) {
2147 pw.println("NetworkTranstionWakeLock is currently " +
2148 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2149 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2150 }
2151 pw.println();
2152
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002153 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002154
2155 if (mInetLog != null) {
2156 pw.println();
2157 pw.println("Inet condition reports:");
2158 for(int i = 0; i < mInetLog.size(); i++) {
2159 pw.println(mInetLog.get(i));
2160 }
2161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163
Robert Greenwalt42acef32009-08-12 16:08:25 -07002164 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002166 public MyHandler(Looper looper) {
2167 super(looper);
2168 }
2169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 @Override
2171 public void handleMessage(Message msg) {
2172 NetworkInfo info;
2173 switch (msg.what) {
2174 case NetworkStateTracker.EVENT_STATE_CHANGED:
2175 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002176 int type = info.getType();
2177 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002178
Wink Savilleed9c02b2010-12-03 12:01:38 -08002179 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002180 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002181 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182
2183 // Connectivity state changed:
2184 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002185 // [12-9] Network subtype (for mobile network, as defined
2186 // by TelephonyManager)
2187 // [8-3] Detailed state ordinal (as defined by
2188 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 // [2-0] Network type (as defined by ConnectivityManager)
2190 int eventLogParam = (info.getType() & 0x7) |
2191 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2192 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002193 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002194 eventLogParam);
2195
2196 if (info.getDetailedState() ==
2197 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002199 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002201 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002203 // the logic here is, handle SUSPENDED the same as
2204 // DISCONNECTED. The only difference being we are
2205 // broadcasting an intent with NetworkInfo that's
2206 // suspended. This allows the applications an
2207 // opportunity to handle DISCONNECTED and SUSPENDED
2208 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002210 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 handleConnect(info);
2212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002215 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002216 // TODO: Temporary allowing network configuration
2217 // change not resetting sockets.
2218 // @see bug/4455071
2219 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002221 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002222 String causedBy = null;
2223 synchronized (ConnectivityService.this) {
2224 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2225 mNetTransitionWakeLock.isHeld()) {
2226 mNetTransitionWakeLock.release();
2227 causedBy = mNetTransitionWakeLockCausedBy;
2228 }
2229 }
2230 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002231 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002232 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002233 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002234 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002235 FeatureUser u = (FeatureUser)msg.obj;
2236 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002237 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002238 case EVENT_INET_CONDITION_CHANGE:
2239 {
2240 int netType = msg.arg1;
2241 int condition = msg.arg2;
2242 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002243 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002244 }
2245 case EVENT_INET_CONDITION_HOLD_END:
2246 {
2247 int netType = msg.arg1;
2248 int sequence = msg.arg2;
2249 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002250 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002251 }
2252 case EVENT_SET_NETWORK_PREFERENCE:
2253 {
2254 int preference = msg.arg1;
2255 handleSetNetworkPreference(preference);
2256 break;
2257 }
2258 case EVENT_SET_BACKGROUND_DATA:
2259 {
2260 boolean enabled = (msg.arg1 == ENABLED);
2261 handleSetBackgroundData(enabled);
2262 break;
2263 }
2264 case EVENT_SET_MOBILE_DATA:
2265 {
2266 boolean enabled = (msg.arg1 == ENABLED);
2267 handleSetMobileData(enabled);
2268 break;
2269 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002270 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2271 {
2272 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002273 break;
2274 }
2275 case EVENT_SET_DEPENDENCY_MET:
2276 {
2277 boolean met = (msg.arg1 == ENABLED);
2278 handleSetDependencyMet(msg.arg2, met);
2279 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002280 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002281 case EVENT_RESTORE_DNS:
2282 {
2283 if (mActiveDefaultNetwork != -1) {
2284 handleDnsConfigurationChange(mActiveDefaultNetwork);
2285 }
2286 break;
2287 }
Wink Saville628b0852011-08-04 15:01:58 -07002288 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2289 {
2290 Intent intent = (Intent)msg.obj;
2291 log("EVENT_SEND_STICKY_BROADCAST_INTENT: sendStickyBroadcast intent=" + intent);
2292 sendStickyBroadcast(intent);
2293 break;
2294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 }
2296 }
2297 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002298
2299 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002300 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002301 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002302
2303 if (isTetheringSupported()) {
2304 return mTethering.tether(iface);
2305 } else {
2306 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2307 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002308 }
2309
2310 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002311 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002312 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002313
2314 if (isTetheringSupported()) {
2315 return mTethering.untether(iface);
2316 } else {
2317 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2318 }
2319 }
2320
2321 // javadoc from interface
2322 public int getLastTetherError(String iface) {
2323 enforceTetherAccessPermission();
2324
2325 if (isTetheringSupported()) {
2326 return mTethering.getLastTetherError(iface);
2327 } else {
2328 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2329 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002330 }
2331
2332 // TODO - proper iface API for selection by property, inspection, etc
2333 public String[] getTetherableUsbRegexs() {
2334 enforceTetherAccessPermission();
2335 if (isTetheringSupported()) {
2336 return mTethering.getTetherableUsbRegexs();
2337 } else {
2338 return new String[0];
2339 }
2340 }
2341
2342 public String[] getTetherableWifiRegexs() {
2343 enforceTetherAccessPermission();
2344 if (isTetheringSupported()) {
2345 return mTethering.getTetherableWifiRegexs();
2346 } else {
2347 return new String[0];
2348 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002349 }
2350
Danica Chang6fdd0c62010-08-11 14:54:43 -07002351 public String[] getTetherableBluetoothRegexs() {
2352 enforceTetherAccessPermission();
2353 if (isTetheringSupported()) {
2354 return mTethering.getTetherableBluetoothRegexs();
2355 } else {
2356 return new String[0];
2357 }
2358 }
2359
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002360 public int setUsbTethering(boolean enable) {
2361 enforceTetherAccessPermission();
2362 if (isTetheringSupported()) {
2363 return mTethering.setUsbTethering(enable);
2364 } else {
2365 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2366 }
2367 }
2368
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002369 // TODO - move iface listing, queries, etc to new module
2370 // javadoc from interface
2371 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002372 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002373 return mTethering.getTetherableIfaces();
2374 }
2375
2376 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002377 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002378 return mTethering.getTetheredIfaces();
2379 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002380
Robert Greenwalt5a735062010-03-02 17:25:02 -08002381 public String[] getTetheringErroredIfaces() {
2382 enforceTetherAccessPermission();
2383 return mTethering.getErroredIfaces();
2384 }
2385
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002386 // if ro.tether.denied = true we default to no tethering
2387 // gservices could set the secure setting to 1 though to enable it on a build where it
2388 // had previously been turned off.
2389 public boolean isTetheringSupported() {
2390 enforceTetherAccessPermission();
2391 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002392 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2393 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2394 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002395 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002396
2397 // An API NetworkStateTrackers can call when they lose their network.
2398 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2399 // whichever happens first. The timer is started by the first caller and not
2400 // restarted by subsequent callers.
2401 public void requestNetworkTransitionWakelock(String forWhom) {
2402 enforceConnectivityInternalPermission();
2403 synchronized (this) {
2404 if (mNetTransitionWakeLock.isHeld()) return;
2405 mNetTransitionWakeLockSerialNumber++;
2406 mNetTransitionWakeLock.acquire();
2407 mNetTransitionWakeLockCausedBy = forWhom;
2408 }
2409 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002410 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002411 mNetTransitionWakeLockSerialNumber, 0),
2412 mNetTransitionWakeLockTimeout);
2413 return;
2414 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002415
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002416 // 100 percent is full good, 0 is full bad.
2417 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002418 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002419 mContext.enforceCallingOrSelfPermission(
2420 android.Manifest.permission.STATUS_BAR,
2421 "ConnectivityService");
2422
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002423 if (DBG) {
2424 int pid = getCallingPid();
2425 int uid = getCallingUid();
2426 String s = pid + "(" + uid + ") reports inet is " +
2427 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2428 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2429 mInetLog.add(s);
2430 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2431 mInetLog.remove(0);
2432 }
2433 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002434 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002435 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2436 }
2437
2438 private void handleInetConditionChange(int netType, int condition) {
2439 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002440 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002441 netType + ", condition=" + condition +
2442 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2443 }
2444 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002445 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002446 return;
2447 }
2448 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002449 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002450 return;
2451 }
2452 mDefaultInetCondition = condition;
2453 int delay;
2454 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002455 if (VDBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002456 // setup a new hold to debounce this
2457 if (mDefaultInetCondition > 50) {
2458 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2459 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2460 } else {
2461 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2462 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2463 }
2464 mInetConditionChangeInFlight = true;
2465 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2466 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2467 } else {
2468 // we've set the new condition, when this hold ends that will get
2469 // picked up
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002470 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002471 }
2472 }
2473
2474 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002475 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002476 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002477 ", condition =" + mDefaultInetCondition +
2478 ", published condition =" + mDefaultInetConditionPublished);
2479 }
2480 mInetConditionChangeInFlight = false;
2481
2482 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002483 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002484 return;
2485 }
2486 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002487 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002488 return;
2489 }
Wink Saville628b0852011-08-04 15:01:58 -07002490 // TODO: Figure out why this optimization sometimes causes a
2491 // change in mDefaultInetCondition to be missed and the
2492 // UI to not be updated.
2493 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2494 // if (DBG) log("no change in condition - aborting");
2495 // return;
2496 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002497 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2498 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002499 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002500 return;
2501 }
2502 mDefaultInetConditionPublished = mDefaultInetCondition;
2503 sendInetConditionBroadcast(networkInfo);
2504 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002505 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002506
2507 public synchronized ProxyProperties getProxy() {
2508 if (mGlobalProxy != null) return mGlobalProxy;
2509 if (mDefaultProxy != null) return mDefaultProxy;
2510 return null;
2511 }
2512
2513 public void setGlobalProxy(ProxyProperties proxyProperties) {
2514 enforceChangePermission();
2515 synchronized (mGlobalProxyLock) {
2516 if (proxyProperties == mGlobalProxy) return;
2517 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2518 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2519
2520 String host = "";
2521 int port = 0;
2522 String exclList = "";
2523 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2524 mGlobalProxy = new ProxyProperties(proxyProperties);
2525 host = mGlobalProxy.getHost();
2526 port = mGlobalProxy.getPort();
2527 exclList = mGlobalProxy.getExclusionList();
2528 } else {
2529 mGlobalProxy = null;
2530 }
2531 ContentResolver res = mContext.getContentResolver();
2532 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2533 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002534 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002535 exclList);
2536 }
2537
2538 if (mGlobalProxy == null) {
2539 proxyProperties = mDefaultProxy;
2540 }
2541 sendProxyBroadcast(proxyProperties);
2542 }
2543
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002544 private void loadGlobalProxy() {
2545 ContentResolver res = mContext.getContentResolver();
2546 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2547 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2548 String exclList = Settings.Secure.getString(res,
2549 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2550 if (!TextUtils.isEmpty(host)) {
2551 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2552 synchronized (mGlobalProxyLock) {
2553 mGlobalProxy = proxyProperties;
2554 }
2555 }
2556 }
2557
Robert Greenwalt434203a2010-10-11 16:00:27 -07002558 public ProxyProperties getGlobalProxy() {
2559 synchronized (mGlobalProxyLock) {
2560 return mGlobalProxy;
2561 }
2562 }
2563
2564 private void handleApplyDefaultProxy(int type) {
2565 // check if new default - push it out to all VM if so
2566 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2567 synchronized (this) {
2568 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2569 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002570 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002571 mDefaultProxy = proxy;
2572 } else {
2573 mDefaultProxy = null;
2574 }
2575 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002576 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002577 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2578 if (mGlobalProxy != null) return;
2579 sendProxyBroadcast(proxy);
2580 }
2581
2582 private void handleDeprecatedGlobalHttpProxy() {
2583 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2584 Settings.Secure.HTTP_PROXY);
2585 if (!TextUtils.isEmpty(proxy)) {
2586 String data[] = proxy.split(":");
2587 String proxyHost = data[0];
2588 int proxyPort = 8080;
2589 if (data.length > 1) {
2590 try {
2591 proxyPort = Integer.parseInt(data[1]);
2592 } catch (NumberFormatException e) {
2593 return;
2594 }
2595 }
2596 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2597 setGlobalProxy(p);
2598 }
2599 }
2600
2601 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002602 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002603 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002604 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002605 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2606 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002607 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002608 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002609 }
2610
2611 private static class SettingsObserver extends ContentObserver {
2612 private int mWhat;
2613 private Handler mHandler;
2614 SettingsObserver(Handler handler, int what) {
2615 super(handler);
2616 mHandler = handler;
2617 mWhat = what;
2618 }
2619
2620 void observe(Context context) {
2621 ContentResolver resolver = context.getContentResolver();
2622 resolver.registerContentObserver(Settings.Secure.getUriFor(
2623 Settings.Secure.HTTP_PROXY), false, this);
2624 }
2625
2626 @Override
2627 public void onChange(boolean selfChange) {
2628 mHandler.obtainMessage(mWhat).sendToTarget();
2629 }
2630 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002631
2632 private void log(String s) {
2633 Slog.d(TAG, s);
2634 }
2635
2636 private void loge(String s) {
2637 Slog.e(TAG, s);
2638 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002639
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002640 int convertFeatureToNetworkType(String feature){
2641 int networkType = -1;
2642 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2643 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2644 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2645 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2646 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2647 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2648 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2649 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2650 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2651 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2652 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2653 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2654 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2655 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2656 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2657 }
2658 return networkType;
2659 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002660
2661 private static <T> T checkNotNull(T value, String message) {
2662 if (value == null) {
2663 throw new NullPointerException(message);
2664 }
2665 return value;
2666 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002667
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002668 /**
2669 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002670 * VpnBuilder and not available in ConnectivityManager. Permissions
2671 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002672 * @hide
2673 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002674 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002675 public boolean protectVpn(ParcelFileDescriptor socket) {
2676 try {
2677 int type = mActiveDefaultNetwork;
2678 if (ConnectivityManager.isNetworkTypeValid(type)) {
2679 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2680 return true;
2681 }
2682 } catch (Exception e) {
2683 // ignore
2684 } finally {
2685 try {
2686 socket.close();
2687 } catch (Exception e) {
2688 // ignore
2689 }
2690 }
2691 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002692 }
2693
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002694 /**
2695 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002696 * and not available in ConnectivityManager. Permissions are checked
2697 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002698 * @hide
2699 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002700 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002701 public boolean prepareVpn(String oldPackage, String newPackage) {
2702 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002703 }
2704
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002705 /**
2706 * Configure a TUN interface and return its file descriptor. Parameters
2707 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002708 * and not available in ConnectivityManager. Permissions are checked in
2709 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002710 * @hide
2711 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002712 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002713 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002714 return mVpn.establish(config);
2715 }
2716
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002717 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002718 * Start legacy VPN and return an intent to VpnDialogs. This method is
2719 * used by VpnSettings and not available in ConnectivityManager.
2720 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002721 * @hide
2722 */
2723 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002724 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2725 mVpn.startLegacyVpn(config, racoon, mtpd);
2726 }
2727
2728 /**
2729 * Return the information of the ongoing legacy VPN. This method is used
2730 * by VpnSettings and not available in ConnectivityManager. Permissions
2731 * are checked in Vpn class.
2732 * @hide
2733 */
2734 @Override
2735 public LegacyVpnInfo getLegacyVpnInfo() {
2736 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002737 }
2738
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002739 /**
2740 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2741 * through NetworkStateTracker since it works differently. For example, it
2742 * needs to override DNS servers but never takes the default routes. It
2743 * relies on another data network, and it could keep existing connections
2744 * alive after reconnecting, switching between networks, or even resuming
2745 * from deep sleep. Calls from applications should be done synchronously
2746 * to avoid race conditions. As these are all hidden APIs, refactoring can
2747 * be done whenever a better abstraction is developed.
2748 */
2749 public class VpnCallback {
2750
2751 private VpnCallback() {
2752 }
2753
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002754 public void override(List<String> dnsServers, List<String> searchDomains) {
2755 if (dnsServers == null) {
2756 restore();
2757 return;
2758 }
2759
2760 // Convert DNS servers into addresses.
2761 List<InetAddress> addresses = new ArrayList<InetAddress>();
2762 for (String address : dnsServers) {
2763 // Double check the addresses and remove invalid ones.
2764 try {
2765 addresses.add(InetAddress.parseNumericAddress(address));
2766 } catch (Exception e) {
2767 // ignore
2768 }
2769 }
2770 if (addresses.isEmpty()) {
2771 restore();
2772 return;
2773 }
2774
2775 // Concatenate search domains into a string.
2776 StringBuilder buffer = new StringBuilder();
2777 if (searchDomains != null) {
2778 for (String domain : searchDomains) {
2779 buffer.append(domain).append(' ');
2780 }
2781 }
2782 String domains = buffer.toString().trim();
2783
2784 // Apply DNS changes.
2785 boolean changed = false;
2786 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002787 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002788 mDnsOverridden = true;
2789 }
2790 if (changed) {
2791 bumpDns();
2792 }
2793
2794 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002795 }
2796
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002797 public void restore() {
2798 synchronized (mDnsLock) {
2799 if (!mDnsOverridden) {
2800 return;
2801 }
2802 mDnsOverridden = false;
2803 }
2804 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002805 }
2806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807}