blob: acfc7a4d9522628f4b281781f4ba3cb2b19b77de [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 Greenwalte6b24292011-08-09 16:52:58 -07001834 } else {
1835 // many radios add a default route even when we don't want one.
1836 // remove the default route unless somebody else has asked for it
1837 String ifaceName = newLp.getInterfaceName();
1838 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
1839 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1840 try {
1841 mNetd.removeRoute(ifaceName, r);
1842 } catch (Exception e) {
1843 // never crash - catch them all
1844 loge("Exception trying to remove a route: " + e);
1845 }
1846 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001847 }
1848 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001849
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001850 if (!isLinkDefault) {
1851 // handle DNS routes
Robert Greenwaltad55d352011-07-22 11:55:33 -07001852 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1853 // no change in routes, check for change in dns themselves
1854 for (InetAddress oldDns : dnsDiff.removed) {
1855 removeRouteToAddress(curLp, oldDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001856 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001857 for (InetAddress newDns : dnsDiff.added) {
1858 addRouteToAddress(newLp, newDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001859 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001860 } else {
1861 // routes changed - remove all old dns entries and add new
1862 if (curLp != null) {
1863 for (InetAddress oldDns : curLp.getDnses()) {
1864 removeRouteToAddress(curLp, oldDns);
1865 }
1866 }
1867 if (newLp != null) {
1868 for (InetAddress newDns : newLp.getDnses()) {
1869 addRouteToAddress(newLp, newDns);
1870 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001871 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001872 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001873 }
1874 }
1875
1876
Irfan Sheriffd649c122010-06-09 15:39:36 -07001877 /**
1878 * Reads the network specific TCP buffer sizes from SystemProperties
1879 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1880 * wide use
1881 */
1882 public void updateNetworkSettings(NetworkStateTracker nt) {
1883 String key = nt.getTcpBufferSizesPropName();
1884 String bufferSizes = SystemProperties.get(key);
1885
1886 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001887 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001888
1889 // Setting to default values so we won't be stuck to previous values
1890 key = "net.tcp.buffersize.default";
1891 bufferSizes = SystemProperties.get(key);
1892 }
1893
1894 // Set values in kernel
1895 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001896 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001897 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001898 + "] which comes from [" + key + "]");
1899 }
1900 setBufferSize(bufferSizes);
1901 }
1902 }
1903
1904 /**
1905 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1906 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1907 *
1908 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1909 * writeMin, writeInitial, writeMax"
1910 */
1911 private void setBufferSize(String bufferSizes) {
1912 try {
1913 String[] values = bufferSizes.split(",");
1914
1915 if (values.length == 6) {
1916 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001917 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1918 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1919 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1920 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1921 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1922 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001923 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001924 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001925 }
1926 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001927 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001928 }
1929 }
1930
Robert Greenwalt42acef32009-08-12 16:08:25 -07001931 /**
1932 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1933 * on the highest priority active net which this process requested.
1934 * If there aren't any, clear it out
1935 */
1936 private void reassessPidDns(int myPid, boolean doBump)
1937 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001938 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001939 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001940 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001941 continue;
1942 }
1943 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001944 if (nt.getNetworkInfo().isConnected() &&
1945 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001946 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001947 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001948 List pids = mNetRequestersPids[i];
1949 for (int j=0; j<pids.size(); j++) {
1950 Integer pid = (Integer)pids.get(j);
1951 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001952 Collection<InetAddress> dnses = p.getDnses();
1953 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001954 if (doBump) {
1955 bumpDns();
1956 }
1957 return;
1958 }
1959 }
1960 }
1961 }
1962 // nothing found - delete
1963 for (int i = 1; ; i++) {
1964 String prop = "net.dns" + i + "." + myPid;
1965 if (SystemProperties.get(prop).length() == 0) {
1966 if (doBump) {
1967 bumpDns();
1968 }
1969 return;
1970 }
1971 SystemProperties.set(prop, "");
1972 }
1973 }
1974
Robert Greenwalt10398722010-12-17 15:20:36 -08001975 // return true if results in a change
1976 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001977 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001978 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001979 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001980 String dnsString = dns.getHostAddress();
1981 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1982 changed = true;
1983 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1984 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001985 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001986 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001987 }
1988
1989 private void bumpDns() {
1990 /*
1991 * Bump the property that tells the name resolver library to reread
1992 * the DNS server list from the properties.
1993 */
1994 String propVal = SystemProperties.get("net.dnschange");
1995 int n = 0;
1996 if (propVal.length() != 0) {
1997 try {
1998 n = Integer.parseInt(propVal);
1999 } catch (NumberFormatException e) {}
2000 }
2001 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002002 /*
2003 * Tell the VMs to toss their DNS caches
2004 */
2005 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2006 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002007 /*
2008 * Connectivity events can happen before boot has completed ...
2009 */
2010 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002011 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002012 }
2013
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002014 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002015 private boolean updateDns(String network, String iface,
2016 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002017 boolean changed = false;
2018 int last = 0;
2019 if (dnses.size() == 0 && mDefaultDns != null) {
2020 ++last;
2021 String value = mDefaultDns.getHostAddress();
2022 if (!value.equals(SystemProperties.get("net.dns1"))) {
2023 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002024 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002025 }
2026 changed = true;
2027 SystemProperties.set("net.dns1", value);
2028 }
2029 } else {
2030 for (InetAddress dns : dnses) {
2031 ++last;
2032 String key = "net.dns" + last;
2033 String value = dns.getHostAddress();
2034 if (!changed && value.equals(SystemProperties.get(key))) {
2035 continue;
2036 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002037 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002038 log("adding dns " + value + " for " + network);
2039 }
2040 changed = true;
2041 SystemProperties.set(key, value);
2042 }
2043 }
2044 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2045 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002046 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002047 changed = true;
2048 SystemProperties.set(key, "");
2049 }
2050 mNumDnsEntries = last;
2051
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002052 if (changed) {
2053 try {
2054 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2055 mNetd.setDefaultInterfaceForDns(iface);
2056 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002057 loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002058 }
2059 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002060 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2061 SystemProperties.set("net.dns.search", domains);
2062 changed = true;
2063 }
2064 return changed;
2065 }
2066
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002067 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002068 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002069 NetworkStateTracker nt = mNetTrackers[netType];
2070 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002071 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002072 if (p == null) return;
2073 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002074 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002075 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002076 String network = nt.getNetworkInfo().getTypeName();
2077 synchronized (mDnsLock) {
2078 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002079 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002080 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002081 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002082 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002083 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002084 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002085 NetworkUtils.makeStrings(dnses));
2086 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002087 loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002088 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002089 // set per-pid dns for attached secondary nets
2090 List pids = mNetRequestersPids[netType];
2091 for (int y=0; y< pids.size(); y++) {
2092 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002093 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
2095 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002096 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002098 }
2099
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002100 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002101 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2102 NETWORK_RESTORE_DELAY_PROP_NAME);
2103 if(restoreDefaultNetworkDelayStr != null &&
2104 restoreDefaultNetworkDelayStr.length() != 0) {
2105 try {
2106 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2107 } catch (NumberFormatException e) {
2108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002110 // if the system property isn't set, use the value for the apn type
2111 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2112
2113 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2114 (mNetConfigs[networkType] != null)) {
2115 ret = mNetConfigs[networkType].restoreTime;
2116 }
2117 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119
2120 @Override
2121 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002122 if (mContext.checkCallingOrSelfPermission(
2123 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002125 pw.println("Permission Denial: can't dump ConnectivityService " +
2126 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2127 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 return;
2129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 pw.println();
2131 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002132 if (nst != null) {
2133 if (nst.getNetworkInfo().isConnected()) {
2134 pw.println("Active network: " + nst.getNetworkInfo().
2135 getTypeName());
2136 }
2137 pw.println(nst.getNetworkInfo());
2138 pw.println(nst);
2139 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002142
2143 pw.println("Network Requester Pids:");
2144 for (int net : mPriorityList) {
2145 String pidString = net + ": ";
2146 for (Object pid : mNetRequestersPids[net]) {
2147 pidString = pidString + pid.toString() + ", ";
2148 }
2149 pw.println(pidString);
2150 }
2151 pw.println();
2152
2153 pw.println("FeatureUsers:");
2154 for (Object requester : mFeatureUsers) {
2155 pw.println(requester.toString());
2156 }
2157 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002158
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002159 synchronized (this) {
2160 pw.println("NetworkTranstionWakeLock is currently " +
2161 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2162 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2163 }
2164 pw.println();
2165
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002166 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002167
2168 if (mInetLog != null) {
2169 pw.println();
2170 pw.println("Inet condition reports:");
2171 for(int i = 0; i < mInetLog.size(); i++) {
2172 pw.println(mInetLog.get(i));
2173 }
2174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 }
2176
Robert Greenwalt42acef32009-08-12 16:08:25 -07002177 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002179 public MyHandler(Looper looper) {
2180 super(looper);
2181 }
2182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 @Override
2184 public void handleMessage(Message msg) {
2185 NetworkInfo info;
2186 switch (msg.what) {
2187 case NetworkStateTracker.EVENT_STATE_CHANGED:
2188 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002189 int type = info.getType();
2190 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002191
Wink Savilleed9c02b2010-12-03 12:01:38 -08002192 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002193 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002194 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195
2196 // Connectivity state changed:
2197 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002198 // [12-9] Network subtype (for mobile network, as defined
2199 // by TelephonyManager)
2200 // [8-3] Detailed state ordinal (as defined by
2201 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 // [2-0] Network type (as defined by ConnectivityManager)
2203 int eventLogParam = (info.getType() & 0x7) |
2204 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2205 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002206 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002207 eventLogParam);
2208
2209 if (info.getDetailedState() ==
2210 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002212 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002214 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002216 // the logic here is, handle SUSPENDED the same as
2217 // DISCONNECTED. The only difference being we are
2218 // broadcasting an intent with NetworkInfo that's
2219 // suspended. This allows the applications an
2220 // opportunity to handle DISCONNECTED and SUSPENDED
2221 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002223 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 handleConnect(info);
2225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002228 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002229 // TODO: Temporary allowing network configuration
2230 // change not resetting sockets.
2231 // @see bug/4455071
2232 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002234 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002235 String causedBy = null;
2236 synchronized (ConnectivityService.this) {
2237 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2238 mNetTransitionWakeLock.isHeld()) {
2239 mNetTransitionWakeLock.release();
2240 causedBy = mNetTransitionWakeLockCausedBy;
2241 }
2242 }
2243 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002244 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002245 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002246 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002247 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002248 FeatureUser u = (FeatureUser)msg.obj;
2249 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002250 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002251 case EVENT_INET_CONDITION_CHANGE:
2252 {
2253 int netType = msg.arg1;
2254 int condition = msg.arg2;
2255 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002256 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002257 }
2258 case EVENT_INET_CONDITION_HOLD_END:
2259 {
2260 int netType = msg.arg1;
2261 int sequence = msg.arg2;
2262 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002263 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002264 }
2265 case EVENT_SET_NETWORK_PREFERENCE:
2266 {
2267 int preference = msg.arg1;
2268 handleSetNetworkPreference(preference);
2269 break;
2270 }
2271 case EVENT_SET_BACKGROUND_DATA:
2272 {
2273 boolean enabled = (msg.arg1 == ENABLED);
2274 handleSetBackgroundData(enabled);
2275 break;
2276 }
2277 case EVENT_SET_MOBILE_DATA:
2278 {
2279 boolean enabled = (msg.arg1 == ENABLED);
2280 handleSetMobileData(enabled);
2281 break;
2282 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002283 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2284 {
2285 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002286 break;
2287 }
2288 case EVENT_SET_DEPENDENCY_MET:
2289 {
2290 boolean met = (msg.arg1 == ENABLED);
2291 handleSetDependencyMet(msg.arg2, met);
2292 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002293 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002294 case EVENT_RESTORE_DNS:
2295 {
2296 if (mActiveDefaultNetwork != -1) {
2297 handleDnsConfigurationChange(mActiveDefaultNetwork);
2298 }
2299 break;
2300 }
Wink Saville628b0852011-08-04 15:01:58 -07002301 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2302 {
2303 Intent intent = (Intent)msg.obj;
2304 log("EVENT_SEND_STICKY_BROADCAST_INTENT: sendStickyBroadcast intent=" + intent);
2305 sendStickyBroadcast(intent);
2306 break;
2307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309 }
2310 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002311
2312 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002313 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002314 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002315
2316 if (isTetheringSupported()) {
2317 return mTethering.tether(iface);
2318 } else {
2319 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2320 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002321 }
2322
2323 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002324 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002325 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002326
2327 if (isTetheringSupported()) {
2328 return mTethering.untether(iface);
2329 } else {
2330 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2331 }
2332 }
2333
2334 // javadoc from interface
2335 public int getLastTetherError(String iface) {
2336 enforceTetherAccessPermission();
2337
2338 if (isTetheringSupported()) {
2339 return mTethering.getLastTetherError(iface);
2340 } else {
2341 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2342 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002343 }
2344
2345 // TODO - proper iface API for selection by property, inspection, etc
2346 public String[] getTetherableUsbRegexs() {
2347 enforceTetherAccessPermission();
2348 if (isTetheringSupported()) {
2349 return mTethering.getTetherableUsbRegexs();
2350 } else {
2351 return new String[0];
2352 }
2353 }
2354
2355 public String[] getTetherableWifiRegexs() {
2356 enforceTetherAccessPermission();
2357 if (isTetheringSupported()) {
2358 return mTethering.getTetherableWifiRegexs();
2359 } else {
2360 return new String[0];
2361 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002362 }
2363
Danica Chang6fdd0c62010-08-11 14:54:43 -07002364 public String[] getTetherableBluetoothRegexs() {
2365 enforceTetherAccessPermission();
2366 if (isTetheringSupported()) {
2367 return mTethering.getTetherableBluetoothRegexs();
2368 } else {
2369 return new String[0];
2370 }
2371 }
2372
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002373 public int setUsbTethering(boolean enable) {
2374 enforceTetherAccessPermission();
2375 if (isTetheringSupported()) {
2376 return mTethering.setUsbTethering(enable);
2377 } else {
2378 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2379 }
2380 }
2381
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002382 // TODO - move iface listing, queries, etc to new module
2383 // javadoc from interface
2384 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002385 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002386 return mTethering.getTetherableIfaces();
2387 }
2388
2389 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002390 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002391 return mTethering.getTetheredIfaces();
2392 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002393
Robert Greenwalt5a735062010-03-02 17:25:02 -08002394 public String[] getTetheringErroredIfaces() {
2395 enforceTetherAccessPermission();
2396 return mTethering.getErroredIfaces();
2397 }
2398
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002399 // if ro.tether.denied = true we default to no tethering
2400 // gservices could set the secure setting to 1 though to enable it on a build where it
2401 // had previously been turned off.
2402 public boolean isTetheringSupported() {
2403 enforceTetherAccessPermission();
2404 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002405 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2406 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2407 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002408 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002409
2410 // An API NetworkStateTrackers can call when they lose their network.
2411 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2412 // whichever happens first. The timer is started by the first caller and not
2413 // restarted by subsequent callers.
2414 public void requestNetworkTransitionWakelock(String forWhom) {
2415 enforceConnectivityInternalPermission();
2416 synchronized (this) {
2417 if (mNetTransitionWakeLock.isHeld()) return;
2418 mNetTransitionWakeLockSerialNumber++;
2419 mNetTransitionWakeLock.acquire();
2420 mNetTransitionWakeLockCausedBy = forWhom;
2421 }
2422 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002423 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002424 mNetTransitionWakeLockSerialNumber, 0),
2425 mNetTransitionWakeLockTimeout);
2426 return;
2427 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002428
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002429 // 100 percent is full good, 0 is full bad.
2430 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002431 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002432 mContext.enforceCallingOrSelfPermission(
2433 android.Manifest.permission.STATUS_BAR,
2434 "ConnectivityService");
2435
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002436 if (DBG) {
2437 int pid = getCallingPid();
2438 int uid = getCallingUid();
2439 String s = pid + "(" + uid + ") reports inet is " +
2440 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2441 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2442 mInetLog.add(s);
2443 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2444 mInetLog.remove(0);
2445 }
2446 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002447 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002448 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2449 }
2450
2451 private void handleInetConditionChange(int netType, int condition) {
2452 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002453 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002454 netType + ", condition=" + condition +
2455 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2456 }
2457 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002458 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002459 return;
2460 }
2461 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002462 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002463 return;
2464 }
2465 mDefaultInetCondition = condition;
2466 int delay;
2467 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002468 if (VDBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002469 // setup a new hold to debounce this
2470 if (mDefaultInetCondition > 50) {
2471 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2472 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2473 } else {
2474 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2475 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2476 }
2477 mInetConditionChangeInFlight = true;
2478 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2479 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2480 } else {
2481 // we've set the new condition, when this hold ends that will get
2482 // picked up
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002483 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002484 }
2485 }
2486
2487 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002488 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002489 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002490 ", condition =" + mDefaultInetCondition +
2491 ", published condition =" + mDefaultInetConditionPublished);
2492 }
2493 mInetConditionChangeInFlight = false;
2494
2495 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002496 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002497 return;
2498 }
2499 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002500 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002501 return;
2502 }
Wink Saville628b0852011-08-04 15:01:58 -07002503 // TODO: Figure out why this optimization sometimes causes a
2504 // change in mDefaultInetCondition to be missed and the
2505 // UI to not be updated.
2506 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2507 // if (DBG) log("no change in condition - aborting");
2508 // return;
2509 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002510 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2511 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002512 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002513 return;
2514 }
2515 mDefaultInetConditionPublished = mDefaultInetCondition;
2516 sendInetConditionBroadcast(networkInfo);
2517 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002518 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002519
2520 public synchronized ProxyProperties getProxy() {
2521 if (mGlobalProxy != null) return mGlobalProxy;
2522 if (mDefaultProxy != null) return mDefaultProxy;
2523 return null;
2524 }
2525
2526 public void setGlobalProxy(ProxyProperties proxyProperties) {
2527 enforceChangePermission();
2528 synchronized (mGlobalProxyLock) {
2529 if (proxyProperties == mGlobalProxy) return;
2530 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2531 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2532
2533 String host = "";
2534 int port = 0;
2535 String exclList = "";
2536 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2537 mGlobalProxy = new ProxyProperties(proxyProperties);
2538 host = mGlobalProxy.getHost();
2539 port = mGlobalProxy.getPort();
2540 exclList = mGlobalProxy.getExclusionList();
2541 } else {
2542 mGlobalProxy = null;
2543 }
2544 ContentResolver res = mContext.getContentResolver();
2545 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2546 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002547 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002548 exclList);
2549 }
2550
2551 if (mGlobalProxy == null) {
2552 proxyProperties = mDefaultProxy;
2553 }
2554 sendProxyBroadcast(proxyProperties);
2555 }
2556
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002557 private void loadGlobalProxy() {
2558 ContentResolver res = mContext.getContentResolver();
2559 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2560 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2561 String exclList = Settings.Secure.getString(res,
2562 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2563 if (!TextUtils.isEmpty(host)) {
2564 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2565 synchronized (mGlobalProxyLock) {
2566 mGlobalProxy = proxyProperties;
2567 }
2568 }
2569 }
2570
Robert Greenwalt434203a2010-10-11 16:00:27 -07002571 public ProxyProperties getGlobalProxy() {
2572 synchronized (mGlobalProxyLock) {
2573 return mGlobalProxy;
2574 }
2575 }
2576
2577 private void handleApplyDefaultProxy(int type) {
2578 // check if new default - push it out to all VM if so
2579 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2580 synchronized (this) {
2581 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2582 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002583 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002584 mDefaultProxy = proxy;
2585 } else {
2586 mDefaultProxy = null;
2587 }
2588 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002589 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002590 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2591 if (mGlobalProxy != null) return;
2592 sendProxyBroadcast(proxy);
2593 }
2594
2595 private void handleDeprecatedGlobalHttpProxy() {
2596 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2597 Settings.Secure.HTTP_PROXY);
2598 if (!TextUtils.isEmpty(proxy)) {
2599 String data[] = proxy.split(":");
2600 String proxyHost = data[0];
2601 int proxyPort = 8080;
2602 if (data.length > 1) {
2603 try {
2604 proxyPort = Integer.parseInt(data[1]);
2605 } catch (NumberFormatException e) {
2606 return;
2607 }
2608 }
2609 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2610 setGlobalProxy(p);
2611 }
2612 }
2613
2614 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002615 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002616 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002617 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002618 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2619 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002620 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002621 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002622 }
2623
2624 private static class SettingsObserver extends ContentObserver {
2625 private int mWhat;
2626 private Handler mHandler;
2627 SettingsObserver(Handler handler, int what) {
2628 super(handler);
2629 mHandler = handler;
2630 mWhat = what;
2631 }
2632
2633 void observe(Context context) {
2634 ContentResolver resolver = context.getContentResolver();
2635 resolver.registerContentObserver(Settings.Secure.getUriFor(
2636 Settings.Secure.HTTP_PROXY), false, this);
2637 }
2638
2639 @Override
2640 public void onChange(boolean selfChange) {
2641 mHandler.obtainMessage(mWhat).sendToTarget();
2642 }
2643 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002644
2645 private void log(String s) {
2646 Slog.d(TAG, s);
2647 }
2648
2649 private void loge(String s) {
2650 Slog.e(TAG, s);
2651 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002652
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002653 int convertFeatureToNetworkType(String feature){
2654 int networkType = -1;
2655 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2656 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2657 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2658 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2659 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2660 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2661 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2662 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2663 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2664 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2665 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2666 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2667 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2668 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2669 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2670 }
2671 return networkType;
2672 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002673
2674 private static <T> T checkNotNull(T value, String message) {
2675 if (value == null) {
2676 throw new NullPointerException(message);
2677 }
2678 return value;
2679 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002680
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002681 /**
2682 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002683 * VpnBuilder and not available in ConnectivityManager. Permissions
2684 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002685 * @hide
2686 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002687 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002688 public boolean protectVpn(ParcelFileDescriptor socket) {
2689 try {
2690 int type = mActiveDefaultNetwork;
2691 if (ConnectivityManager.isNetworkTypeValid(type)) {
2692 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2693 return true;
2694 }
2695 } catch (Exception e) {
2696 // ignore
2697 } finally {
2698 try {
2699 socket.close();
2700 } catch (Exception e) {
2701 // ignore
2702 }
2703 }
2704 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002705 }
2706
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002707 /**
2708 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002709 * and not available in ConnectivityManager. Permissions are checked
2710 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002711 * @hide
2712 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002713 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002714 public boolean prepareVpn(String oldPackage, String newPackage) {
2715 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002716 }
2717
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002718 /**
2719 * Configure a TUN interface and return its file descriptor. Parameters
2720 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002721 * and not available in ConnectivityManager. Permissions are checked in
2722 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002723 * @hide
2724 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002725 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002726 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002727 return mVpn.establish(config);
2728 }
2729
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002730 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002731 * Start legacy VPN and return an intent to VpnDialogs. This method is
2732 * used by VpnSettings and not available in ConnectivityManager.
2733 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002734 * @hide
2735 */
2736 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002737 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2738 mVpn.startLegacyVpn(config, racoon, mtpd);
2739 }
2740
2741 /**
2742 * Return the information of the ongoing legacy VPN. This method is used
2743 * by VpnSettings and not available in ConnectivityManager. Permissions
2744 * are checked in Vpn class.
2745 * @hide
2746 */
2747 @Override
2748 public LegacyVpnInfo getLegacyVpnInfo() {
2749 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002750 }
2751
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002752 /**
2753 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2754 * through NetworkStateTracker since it works differently. For example, it
2755 * needs to override DNS servers but never takes the default routes. It
2756 * relies on another data network, and it could keep existing connections
2757 * alive after reconnecting, switching between networks, or even resuming
2758 * from deep sleep. Calls from applications should be done synchronously
2759 * to avoid race conditions. As these are all hidden APIs, refactoring can
2760 * be done whenever a better abstraction is developed.
2761 */
2762 public class VpnCallback {
2763
2764 private VpnCallback() {
2765 }
2766
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002767 public void override(List<String> dnsServers, List<String> searchDomains) {
2768 if (dnsServers == null) {
2769 restore();
2770 return;
2771 }
2772
2773 // Convert DNS servers into addresses.
2774 List<InetAddress> addresses = new ArrayList<InetAddress>();
2775 for (String address : dnsServers) {
2776 // Double check the addresses and remove invalid ones.
2777 try {
2778 addresses.add(InetAddress.parseNumericAddress(address));
2779 } catch (Exception e) {
2780 // ignore
2781 }
2782 }
2783 if (addresses.isEmpty()) {
2784 restore();
2785 return;
2786 }
2787
2788 // Concatenate search domains into a string.
2789 StringBuilder buffer = new StringBuilder();
2790 if (searchDomains != null) {
2791 for (String domain : searchDomains) {
2792 buffer.append(domain).append(' ');
2793 }
2794 }
2795 String domains = buffer.toString().trim();
2796
2797 // Apply DNS changes.
2798 boolean changed = false;
2799 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002800 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002801 mDnsOverridden = true;
2802 }
2803 if (changed) {
2804 bumpDns();
2805 }
2806
2807 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002808 }
2809
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002810 public void restore() {
2811 synchronized (mDnsLock) {
2812 if (!mDnsOverridden) {
2813 return;
2814 }
2815 mDnsOverridden = false;
2816 }
2817 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002818 }
2819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820}