blob: 1bbe9343d6eba98b40d16bd2f38e707e182e1a16 [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 Sharkeyd2a45872011-05-28 20:56:34 -070043import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070045import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070046import android.net.Proxy;
47import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070048import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.wifi.WifiStateTracker;
50import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040051import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070053import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070054import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070055import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Looper;
57import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070058import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070059import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070060import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.os.ServiceManager;
62import android.os.SystemProperties;
63import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070064import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080066import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Chia-chi Yeh2e467642011-07-04 03:23:12 -070069import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070070import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070071import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080072import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073import com.android.server.connectivity.Vpn;
74
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070075import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070076import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070079import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -070081import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070082import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070083import java.net.InetAddress;
84import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070086import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070087import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070088import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070089import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import java.util.List;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
93/**
94 * @hide
95 */
96public class ConnectivityService extends IConnectivityManager.Stub {
97
Robert Greenwaltba175a52010-10-05 19:12:26 -070098 private static final boolean DBG = true;
Wink Savillee8222252011-07-13 13:44:13 -070099 private static final boolean VDBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private static final String TAG = "ConnectivityService";
101
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700102 private static final boolean LOGD_RULES = false;
103
Robert Greenwalt42acef32009-08-12 16:08:25 -0700104 // how long to wait before switching back to a radio's default network
105 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
106 // system property that can override the above value
107 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
108 "android.telephony.apn-restore";
109
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700110 // used in recursive route setting to add gateways for the host for which
111 // a host route was requested.
112 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
113
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800114 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800115 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117 private Vpn mVpn;
118
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700119 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
120 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700121 /** Currently active network rules by UID. */
122 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700123 /** Set of ifaces that are costly. */
124 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 /**
127 * Sometimes we want to refer to the individual network state
128 * trackers separately, and sometimes we just want to treat them
129 * abstractly.
130 */
131 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700132
133 /**
Wink Savillee8222252011-07-13 13:44:13 -0700134 * The link properties that define the current links
135 */
136 private LinkProperties mCurrentLinkProperties[];
137
138 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139 * A per Net list of the PID's that requested access to the net
140 * used both as a refcount and for per-PID DNS selection
141 */
142 private List mNetRequestersPids[];
143
Robert Greenwalt42acef32009-08-12 16:08:25 -0700144 // priority order of the nettrackers
145 // (excluding dynamically set mNetworkPreference)
146 // TODO - move mNetworkTypePreference into this
147 private int[] mPriorityList;
148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 private Context mContext;
150 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700151 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700152 // 0 is full bad, 100 is full good
153 private int mDefaultInetCondition = 0;
154 private int mDefaultInetConditionPublished = 0;
155 private boolean mInetConditionChangeInFlight = false;
156 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700158 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700160 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
162 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700163 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800165 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
166
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700167 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700168 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700169
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700170 private static final int ENABLED = 1;
171 private static final int DISABLED = 0;
172
173 // Share the event space with NetworkStateTracker (which can't see this
174 // internal class but sends us events). If you change these, change
175 // NetworkStateTracker.java too.
176 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
177 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
178
179 /**
180 * used internally as a delayed event to make us switch back to the
181 * default network
182 */
183 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
184 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
185
186 /**
187 * used internally to change our mobile data enabled flag
188 */
189 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
190 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
191
192 /**
193 * used internally to change our network preference setting
194 * arg1 = networkType to prefer
195 */
196 private static final int EVENT_SET_NETWORK_PREFERENCE =
197 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
198
199 /**
200 * used internally to synchronize inet condition reports
201 * arg1 = networkType
202 * arg2 = condition (0 bad, 100 good)
203 */
204 private static final int EVENT_INET_CONDITION_CHANGE =
205 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
206
207 /**
208 * used internally to mark the end of inet condition hold periods
209 * arg1 = networkType
210 */
211 private static final int EVENT_INET_CONDITION_HOLD_END =
212 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
213
214 /**
215 * used internally to set the background data preference
216 * arg1 = TRUE for enabled, FALSE for disabled
217 */
218 private static final int EVENT_SET_BACKGROUND_DATA =
219 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
220
221 /**
222 * used internally to set enable/disable cellular data
223 * arg1 = ENBALED or DISABLED
224 */
225 private static final int EVENT_SET_MOBILE_DATA =
226 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
227
Robert Greenwaltf3331232010-09-24 14:32:21 -0700228 /**
229 * used internally to clear a wakelock when transitioning
230 * from one net to another
231 */
232 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
233 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
234
Robert Greenwalt434203a2010-10-11 16:00:27 -0700235 /**
236 * used internally to reload global proxy settings
237 */
238 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
239 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
240
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700241 /**
242 * used internally to set external dependency met/unmet
243 * arg1 = ENABLED (met) or DISABLED (unmet)
244 * arg2 = NetworkType
245 */
246 private static final int EVENT_SET_DEPENDENCY_MET =
247 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
248
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700249 /**
250 * used internally to restore DNS properties back to the
251 * default network
252 */
253 private static final int EVENT_RESTORE_DNS =
254 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
255
Robert Greenwalt42acef32009-08-12 16:08:25 -0700256 private Handler mHandler;
257
258 // list of DeathRecipients used to make sure features are turned off when
259 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500260 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700261
Mike Lockwood0f79b542009-08-14 14:18:49 -0400262 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800263 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400264
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700265 private PowerManager.WakeLock mNetTransitionWakeLock;
266 private String mNetTransitionWakeLockCausedBy = "";
267 private int mNetTransitionWakeLockSerialNumber;
268 private int mNetTransitionWakeLockTimeout;
269
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700270 private InetAddress mDefaultDns;
271
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700272 // this collection is used to refcount the added routes - if there are none left
273 // it's time to remove the route from the route table
274 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
275
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700276 // used in DBG mode to track inet condition reports
277 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
278 private ArrayList mInetLog;
279
Robert Greenwalt434203a2010-10-11 16:00:27 -0700280 // track the current default http proxy - tell the world if we get a new one (real change)
281 private ProxyProperties mDefaultProxy = null;
282 // track the global proxy.
283 private ProxyProperties mGlobalProxy = null;
284 private final Object mGlobalProxyLock = new Object();
285
286 private SettingsObserver mSettingsObserver;
287
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700288 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700289 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700290
Robert Greenwalt511288a2009-12-07 11:33:18 -0800291 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700292 public int mSimultaneity;
293 public int mType;
294 public RadioAttributes(String init) {
295 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700296 mType = Integer.parseInt(fragments[0]);
297 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700298 }
299 }
300 RadioAttributes[] mRadioAttributes;
301
Robert Greenwalt50393202011-06-21 17:26:14 -0700302 // the set of network types that can only be enabled by system/sig apps
303 List mProtectedNetworks;
304
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700305 public ConnectivityService(
306 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800307 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800308
Wink Savillebb08caf2010-09-02 19:23:52 -0700309 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
310 handlerThread.start();
311 mHandler = new MyHandler(handlerThread.getLooper());
312
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800313 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
314 Settings.Secure.BACKGROUND_DATA, 1) == 1);
315
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800316 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800317 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
318 String id = Settings.Secure.getString(context.getContentResolver(),
319 Settings.Secure.ANDROID_ID);
320 if (id != null && id.length() > 0) {
321 String name = new String("android_").concat(id);
322 SystemProperties.set("net.hostname", name);
323 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800324 }
325
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700326 // read our default dns server ip
327 String dns = Settings.Secure.getString(context.getContentResolver(),
328 Settings.Secure.DEFAULT_DNS_SERVER);
329 if (dns == null || dns.length() == 0) {
330 dns = context.getResources().getString(
331 com.android.internal.R.string.config_default_dns_server);
332 }
333 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800334 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
335 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800336 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700337 }
338
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700339 mContext = checkNotNull(context, "missing Context");
340 mNetd = checkNotNull(netd, "missing INetworkManagementService");
341 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700342
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700343 try {
344 mPolicyManager.registerListener(mPolicyListener);
345 } catch (RemoteException e) {
346 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700347 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700348 }
349
350 final PowerManager powerManager = (PowerManager) context.getSystemService(
351 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700352 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
353 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
354 com.android.internal.R.integer.config_networkTransitionTimeout);
355
Robert Greenwalt42acef32009-08-12 16:08:25 -0700356 mNetTrackers = new NetworkStateTracker[
357 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700358 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700361
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700362 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700363 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700364
Robert Greenwalt42acef32009-08-12 16:08:25 -0700365 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366 String[] raStrings = context.getResources().getStringArray(
367 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700368 for (String raString : raStrings) {
369 RadioAttributes r = new RadioAttributes(raString);
370 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800371 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700372 continue;
373 }
374 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800375 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700376 r.mType);
377 continue;
378 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700379 mRadioAttributes[r.mType] = r;
380 }
381
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700382 String[] naStrings = context.getResources().getStringArray(
383 com.android.internal.R.array.networkAttributes);
384 for (String naString : naStrings) {
385 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700386 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700387 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800388 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700389 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700390 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700391 }
Wink Saville975c8482011-04-07 14:23:45 -0700392 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800393 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700394 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700395 continue;
396 }
Wink Saville975c8482011-04-07 14:23:45 -0700397 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800398 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700399 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700400 continue;
401 }
Wink Saville975c8482011-04-07 14:23:45 -0700402 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700403 mNetworksDefined++;
404 } catch(Exception e) {
405 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700406 }
407 }
408
Robert Greenwalt50393202011-06-21 17:26:14 -0700409 mProtectedNetworks = new ArrayList<Integer>();
410 int[] protectedNetworks = context.getResources().getIntArray(
411 com.android.internal.R.array.config_protectedNetworks);
412 for (int p : protectedNetworks) {
413 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
414 mProtectedNetworks.add(p);
415 } else {
416 if (DBG) loge("Ignoring protectedNetwork " + p);
417 }
418 }
419
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700420 // high priority first
421 mPriorityList = new int[mNetworksDefined];
422 {
423 int insertionPoint = mNetworksDefined-1;
424 int currentLowest = 0;
425 int nextLowest = 0;
426 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700427 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700428 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700429 if (na.priority < currentLowest) continue;
430 if (na.priority > currentLowest) {
431 if (na.priority < nextLowest || nextLowest == 0) {
432 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700433 }
434 continue;
435 }
Wink Saville975c8482011-04-07 14:23:45 -0700436 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700437 }
438 currentLowest = nextLowest;
439 nextLowest = 0;
440 }
441 }
442
443 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
444 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445 mNetRequestersPids[i] = new ArrayList();
446 }
447
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500448 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700449
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700450 mNumDnsEntries = 0;
451
452 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
453 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 /*
455 * Create the network state trackers for Wi-Fi and mobile
456 * data. Maybe this could be done with a factory class,
457 * but it's not clear that it's worth it, given that
458 * the number of different network types is not going
459 * to change very often.
460 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700461 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700462 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700463 case ConnectivityManager.TYPE_WIFI:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800464 if (DBG) log("Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700465 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700466 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700467 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700468 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700469 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700470 wst.startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700471 break;
472 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700473 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700474 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700475 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700476 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800477 case ConnectivityManager.TYPE_DUMMY:
478 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700479 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800480 mNetTrackers[netType].startMonitoring(context, mHandler);
481 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800482 case ConnectivityManager.TYPE_BLUETOOTH:
483 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
484 mNetTrackers[netType].startMonitoring(context, mHandler);
485 break;
Benoit Goby19970692010-12-22 14:29:40 -0800486 case ConnectivityManager.TYPE_ETHERNET:
487 mNetTrackers[netType] = EthernetDataTracker.getInstance();
488 mNetTrackers[netType].startMonitoring(context, mHandler);
489 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700490 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800491 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700492 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700493 continue;
494 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700495 mCurrentLinkProperties[netType] = null;
Robert Greenwaltc96e6cc2011-07-15 11:16:45 -0700496 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700497 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800498
Chia-chi Yehc9338302011-05-11 16:35:13 -0700499 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
500 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
501
502 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700503 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700504 mTethering.getTetherableWifiRegexs().length != 0 ||
505 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700506 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800507
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700508 mVpn = new Vpn(mContext, new VpnCallback());
509
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700510 try {
511 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700512 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700513 } catch (RemoteException e) {
514 loge("Error registering observer :" + e);
515 }
516
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700517 if (DBG) {
518 mInetLog = new ArrayList();
519 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700520
521 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
522 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800523
524 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
526
527 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700528 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 * @param preference the new preference
530 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700531 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700533
534 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 }
536
537 public int getNetworkPreference() {
538 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700539 int preference;
540 synchronized(this) {
541 preference = mNetworkPreference;
542 }
543 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
545
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700546 private void handleSetNetworkPreference(int preference) {
547 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700548 mNetConfigs[preference] != null &&
549 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700550 if (mNetworkPreference != preference) {
551 final ContentResolver cr = mContext.getContentResolver();
552 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
553 synchronized(this) {
554 mNetworkPreference = preference;
555 }
556 enforcePreference();
557 }
558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 private int getPersistedNetworkPreference() {
562 final ContentResolver cr = mContext.getContentResolver();
563
564 final int networkPrefSetting = Settings.Secure
565 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
566 if (networkPrefSetting != -1) {
567 return networkPrefSetting;
568 }
569
570 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
571 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700574 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 * In this method, we only tear down a non-preferred network. Establishing
576 * a connection to the preferred network is taken care of when we handle
577 * the disconnect event from the non-preferred network
578 * (see {@link #handleDisconnect(NetworkInfo)}).
579 */
580 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700581 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 return;
583
Robert Greenwalt42acef32009-08-12 16:08:25 -0700584 if (!mNetTrackers[mNetworkPreference].isAvailable())
585 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
Robert Greenwalt42acef32009-08-12 16:08:25 -0700587 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700588 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700589 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700590 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800591 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700592 " in enforcePreference");
593 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700594 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596 }
597 }
598
599 private boolean teardown(NetworkStateTracker netTracker) {
600 if (netTracker.teardown()) {
601 netTracker.setTeardownRequested(true);
602 return true;
603 } else {
604 return false;
605 }
606 }
607
608 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700609 * Check if UID should be blocked from using the network represented by the
610 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700611 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700612 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
613 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700614
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700615 final boolean networkCostly;
616 final int uidRules;
617 synchronized (mRulesLock) {
618 networkCostly = mMeteredIfaces.contains(iface);
619 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700620 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700621
622 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
623 return true;
624 }
625
626 // no restrictive rules; network is visible
627 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700628 }
629
630 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700631 * Return a filtered {@link NetworkInfo}, potentially marked
632 * {@link DetailedState#BLOCKED} based on
633 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700634 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700635 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
636 NetworkInfo info = tracker.getNetworkInfo();
637 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700638 // network is blocked; clone and override state
639 info = new NetworkInfo(info);
640 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700641 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700642 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700643 }
644
645 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 * Return NetworkInfo for the active (i.e., connected) network interface.
647 * It is assumed that at most one network is active at a time. If more
648 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700649 * @return the info for the active network, or {@code null} if none is
650 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700652 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700654 enforceAccessPermission();
655 final int uid = Binder.getCallingUid();
656 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
658
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700659 @Override
660 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
661 enforceConnectivityInternalPermission();
662 return getNetworkInfo(mActiveDefaultNetwork, uid);
663 }
664
665 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 public NetworkInfo getNetworkInfo(int networkType) {
667 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700668 final int uid = Binder.getCallingUid();
669 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
671
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700672 private NetworkInfo getNetworkInfo(int networkType, int uid) {
673 NetworkInfo info = null;
674 if (isNetworkTypeValid(networkType)) {
675 final NetworkStateTracker tracker = mNetTrackers[networkType];
676 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700677 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700678 }
679 }
680 return info;
681 }
682
683 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 public NetworkInfo[] getAllNetworkInfo() {
685 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700686 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700687 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700688 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700689 for (NetworkStateTracker tracker : mNetTrackers) {
690 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700691 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700692 }
693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700695 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 }
697
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700698 /**
699 * Return LinkProperties for the active (i.e., connected) default
700 * network interface. It is assumed that at most one default network
701 * is active at a time. If more than one is active, it is indeterminate
702 * which will be returned.
703 * @return the ip properties for the active network, or {@code null} if
704 * none is active
705 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700706 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700707 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700708 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700709 }
710
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700711 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700712 public LinkProperties getLinkProperties(int networkType) {
713 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700714 if (isNetworkTypeValid(networkType)) {
715 final NetworkStateTracker tracker = mNetTrackers[networkType];
716 if (tracker != null) {
717 return tracker.getLinkProperties();
718 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700719 }
720 return null;
721 }
722
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700723 @Override
724 public NetworkState[] getAllNetworkState() {
725 enforceAccessPermission();
726 final int uid = Binder.getCallingUid();
727 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700728 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700729 for (NetworkStateTracker tracker : mNetTrackers) {
730 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700731 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700732 result.add(new NetworkState(
733 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
734 }
735 }
736 }
737 return result.toArray(new NetworkState[result.size()]);
738 }
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 public boolean setRadios(boolean turnOn) {
741 boolean result = true;
742 enforceChangePermission();
743 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700744 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746 return result;
747 }
748
749 public boolean setRadio(int netType, boolean turnOn) {
750 enforceChangePermission();
751 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
752 return false;
753 }
754 NetworkStateTracker tracker = mNetTrackers[netType];
755 return tracker != null && tracker.setRadio(turnOn);
756 }
757
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700758 /**
759 * Used to notice when the calling process dies so we can self-expire
760 *
761 * Also used to know if the process has cleaned up after itself when
762 * our auto-expire timer goes off. The timer has a link to an object.
763 *
764 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700765 private class FeatureUser implements IBinder.DeathRecipient {
766 int mNetworkType;
767 String mFeature;
768 IBinder mBinder;
769 int mPid;
770 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800771 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700772
773 FeatureUser(int type, String feature, IBinder binder) {
774 super();
775 mNetworkType = type;
776 mFeature = feature;
777 mBinder = binder;
778 mPid = getCallingPid();
779 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800780 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700781
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782 try {
783 mBinder.linkToDeath(this, 0);
784 } catch (RemoteException e) {
785 binderDied();
786 }
787 }
788
789 void unlinkDeathRecipient() {
790 mBinder.unlinkToDeath(this, 0);
791 }
792
793 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800794 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800795 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
796 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700797 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700798 }
799
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700800 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700801 if (VDBG) {
802 log("ConnectivityService FeatureUser expire(" +
803 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
804 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
805 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700806 stopUsingNetworkFeature(this, false);
807 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800808
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500809 public boolean isSameUser(FeatureUser u) {
810 if (u == null) return false;
811
812 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
813 }
814
815 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
816 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
817 TextUtils.equals(mFeature, feature)) {
818 return true;
819 }
820 return false;
821 }
822
Robert Greenwaltb9285352009-12-21 18:24:07 -0800823 public String toString() {
824 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
825 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
826 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700827 }
828
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700829 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700830 public int startUsingNetworkFeature(int networkType, String feature,
831 IBinder binder) {
832 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800833 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700836 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700837 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700838 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700840
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700841 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700842
843 // TODO - move this into the MobileDataStateTracker
844 int usedNetworkType = networkType;
845 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800846 usedNetworkType = convertFeatureToNetworkType(feature);
847 if (usedNetworkType < 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700848 loge("Can't match any netTracker!");
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800849 usedNetworkType = networkType;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700850 }
851 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700852
853 if (mProtectedNetworks.contains(usedNetworkType)) {
854 enforceConnectivityInternalPermission();
855 }
856
Robert Greenwalt42acef32009-08-12 16:08:25 -0700857 NetworkStateTracker network = mNetTrackers[usedNetworkType];
858 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800859 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700860 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700861 NetworkStateTracker radio = mNetTrackers[networkType];
862 NetworkInfo ni = network.getNetworkInfo();
863
864 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800865 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800866 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
867 return Phone.APN_TYPE_NOT_AVAILABLE;
868 } else {
869 // else make the attempt anyway - probably giving REQUEST_STARTED below
870 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700871 }
872
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500873 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
874
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700875 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500876 boolean addToList = true;
877 if (restoreTimer < 0) {
878 // In case there is no timer is specified for the feature,
879 // make sure we don't add duplicate entry with the same request.
880 for (FeatureUser u : mFeatureUsers) {
881 if (u.isSameUser(f)) {
882 // Duplicate user is found. Do not add.
883 addToList = false;
884 break;
885 }
886 }
887 }
888
889 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700890 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
891 // this gets used for per-pid dns when connected
892 mNetRequestersPids[usedNetworkType].add(currentPid);
893 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700894 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700895
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700896 if (restoreTimer >= 0) {
897 mHandler.sendMessageDelayed(
898 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
899 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700900
Robert Greenwalta64bf832009-08-19 20:19:33 -0700901 if ((ni.isConnectedOrConnecting() == true) &&
902 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700903 if (ni.isConnected() == true) {
904 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -0700905 handleDnsConfigurationChange(usedNetworkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800906 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700907 return Phone.APN_ALREADY_ACTIVE;
908 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800909 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700910 return Phone.APN_REQUEST_STARTED;
911 }
912
913 // check if the radio in play can make another contact
914 // assume if cannot for now
915
Wink Savilleed9c02b2010-12-03 12:01:38 -0800916 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700917 network.reconnect();
918 return Phone.APN_REQUEST_STARTED;
919 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800920 // need to remember this unsupported request so we respond appropriately on stop
921 synchronized(this) {
922 mFeatureUsers.add(f);
923 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
924 // this gets used for per-pid dns when connected
925 mNetRequestersPids[usedNetworkType].add(currentPid);
926 }
927 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700928 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700929 }
930 }
931 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700934 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700936 enforceChangePermission();
937
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700938 int pid = getCallingPid();
939 int uid = getCallingUid();
940
941 FeatureUser u = null;
942 boolean found = false;
943
944 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500945 for (FeatureUser x : mFeatureUsers) {
946 if (x.isSameUser(pid, uid, networkType, feature)) {
947 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700948 found = true;
949 break;
950 }
951 }
952 }
953 if (found && u != null) {
954 // stop regardless of how many other time this proc had called start
955 return stopUsingNetworkFeature(u, true);
956 } else {
957 // none found!
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700958 if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700959 return 1;
960 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700961 }
962
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700963 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
964 int networkType = u.mNetworkType;
965 String feature = u.mFeature;
966 int pid = u.mPid;
967 int uid = u.mUid;
968
969 NetworkStateTracker tracker = null;
970 boolean callTeardown = false; // used to carry our decision outside of sync block
971
Robert Greenwalt42acef32009-08-12 16:08:25 -0700972 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800973 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700974 ": " + feature);
975 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
978 return -1;
979 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700980
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700981 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
982 // sync block
983 synchronized(this) {
984 // check if this process still has an outstanding start request
985 if (!mFeatureUsers.contains(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800986 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700987 return 1;
988 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700989 u.unlinkDeathRecipient();
990 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
991 // If we care about duplicate requests, check for that here.
992 //
993 // This is done to support the extension of a request - the app
994 // can request we start the network feature again and renew the
995 // auto-shutoff delay. Normal "stop" calls from the app though
996 // do not pay attention to duplicate requests - in effect the
997 // API does not refcount and a single stop will counter multiple starts.
998 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500999 for (FeatureUser x : mFeatureUsers) {
1000 if (x.isSameUser(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001001 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001002 return 1;
1003 }
1004 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001005 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001006
1007 // TODO - move to MobileDataStateTracker
1008 int usedNetworkType = networkType;
1009 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -08001010 usedNetworkType = convertFeatureToNetworkType(feature);
1011 if (usedNetworkType < 0) {
1012 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001013 }
1014 }
1015 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001016 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001017 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001018 return -1;
1019 }
1020 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001021 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001022 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001023 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001024 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001025 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001026 "others still using it");
1027 return 1;
1028 }
1029 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001030 } else {
1031 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001032 }
1033 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001034 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001035 if (callTeardown) {
1036 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001037 return 1;
1038 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001039 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042
1043 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001044 * @deprecated use requestRouteToHostAddress instead
1045 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 * Ensure that a network route exists to deliver traffic to the specified
1047 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001048 * @param networkType the type of the network over which traffic to the
1049 * specified host is to be routed
1050 * @param hostAddress the IP address of the host to which the route is
1051 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 * @return {@code true} on success, {@code false} on failure
1053 */
1054 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001055 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1056
1057 if (inetAddress == null) {
1058 return false;
1059 }
1060
1061 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1062 }
1063
1064 /**
1065 * Ensure that a network route exists to deliver traffic to the specified
1066 * host via the specified network interface.
1067 * @param networkType the type of the network over which traffic to the
1068 * specified host is to be routed
1069 * @param hostAddress the IP address of the host to which the route is
1070 * desired
1071 * @return {@code true} on success, {@code false} on failure
1072 */
1073 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001075 if (mProtectedNetworks.contains(networkType)) {
1076 enforceConnectivityInternalPermission();
1077 }
1078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1080 return false;
1081 }
1082 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001083
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001084 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1085 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001086 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001087 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001088 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001089 }
1090 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001092 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001093 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001094 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001095 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001096 } catch (UnknownHostException e) {}
1097 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001098 }
1099
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001100 private boolean addRoute(LinkProperties p, RouteInfo r) {
1101 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001102 }
1103
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001104 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1105 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1106 }
1107
Robert Greenwaltad55d352011-07-22 11:55:33 -07001108 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1109 return modifyRouteToAddress(lp, addr, true);
1110 }
1111
1112 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1113 return modifyRouteToAddress(lp, addr, false);
1114 }
1115
1116 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1117 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1118 if (bestRoute == null) {
1119 bestRoute = RouteInfo.makeHostRoute(addr);
1120 } else {
1121 if (bestRoute.getGateway().equals(addr)) {
1122 // if there is no better route, add the implied hostroute for our gateway
1123 bestRoute = RouteInfo.makeHostRoute(addr);
1124 } else {
1125 // if we will connect to this through another route, add a direct route
1126 // to it's gateway
1127 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1128 }
1129 }
1130 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1131 }
1132
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001133 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1134 boolean doAdd) {
1135 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1136
1137 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1138 loge("Error adding route - too much recursion");
1139 return false;
1140 }
1141
1142 if (r.isHostRoute() == false) {
1143 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1144 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001145 if (bestRoute.getGateway().equals(r.getGateway())) {
1146 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001147 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001148 } else {
1149 // if we will connect to our gateway through another route, add a direct
1150 // route to it's gateway
1151 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001152 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001153 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001154 }
1155 }
1156 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001157 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001158 mAddedRoutes.add(r);
1159 try {
1160 mNetd.addRoute(ifaceName, r);
1161 } catch (Exception e) {
1162 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001163 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001164 return false;
1165 }
1166 } else {
1167 // if we remove this one and there are no more like it, then refcount==0 and
1168 // we can remove it from the table
1169 mAddedRoutes.remove(r);
1170 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001171 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001172 try {
1173 mNetd.removeRoute(ifaceName, r);
1174 } catch (Exception e) {
1175 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001176 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001177 return false;
1178 }
1179 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001180 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001181 }
1182 }
1183 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
1186 /**
1187 * @see ConnectivityManager#getBackgroundDataSetting()
1188 */
1189 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001190 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 /**
1194 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1195 */
1196 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1197 mContext.enforceCallingOrSelfPermission(
1198 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1199 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001200
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001201 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1202
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1204 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001207 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-02-25 13:44:09 -08001208 Settings.Secure.putInt(mContext.getContentResolver(),
1209 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1210 Intent broadcast = new Intent(
1211 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1212 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001213 }
1214
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001215 /**
1216 * @see ConnectivityManager#getMobileDataEnabled()
1217 */
1218 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001219 // TODO: This detail should probably be in DataConnectionTracker's
1220 // which is where we store the value and maybe make this
1221 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001222 enforceAccessPermission();
1223 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1224 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001225 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001226 return retVal;
1227 }
1228
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001229 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001230 enforceConnectivityInternalPermission();
1231
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1233 (met ? ENABLED : DISABLED), networkType));
1234 }
1235
1236 private void handleSetDependencyMet(int networkType, boolean met) {
1237 if (mNetTrackers[networkType] != null) {
1238 if (DBG) {
1239 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1240 }
1241 mNetTrackers[networkType].setDependencyMet(met);
1242 }
1243 }
1244
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001245 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1246 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001247 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001248 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001249 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001250
1251 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001252 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001253 }
1254
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001255 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001256 // skip update when we've already applied rules
1257 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1258 if (oldRules == uidRules) return;
1259
1260 mUidRules.put(uid, uidRules);
1261 }
1262
1263 // TODO: dispatch into NMS to push rules towards kernel module
1264 // TODO: notify UID when it has requested targeted updates
1265 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001266
1267 @Override
1268 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1269 // only someone like NPMS should only be calling us
1270 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1271
1272 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001273 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001274 }
1275
1276 synchronized (mRulesLock) {
1277 mMeteredIfaces.clear();
1278 for (String iface : meteredIfaces) {
1279 mMeteredIfaces.add(iface);
1280 }
1281 }
1282 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001283 };
1284
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001285 /**
1286 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1287 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001288 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001289 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001290 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001291
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001292 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001293 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001294 }
1295
1296 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001297 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001298 if (VDBG) {
1299 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001300 }
Wink Savillee7982682010-12-07 10:31:02 -08001301 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001302 }
1303 }
1304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001306 mContext.enforceCallingOrSelfPermission(
1307 android.Manifest.permission.ACCESS_NETWORK_STATE,
1308 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
1310
1311 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001312 mContext.enforceCallingOrSelfPermission(
1313 android.Manifest.permission.CHANGE_NETWORK_STATE,
1314 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001317 // TODO Make this a special check when it goes public
1318 private void enforceTetherChangePermission() {
1319 mContext.enforceCallingOrSelfPermission(
1320 android.Manifest.permission.CHANGE_NETWORK_STATE,
1321 "ConnectivityService");
1322 }
1323
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001324 private void enforceTetherAccessPermission() {
1325 mContext.enforceCallingOrSelfPermission(
1326 android.Manifest.permission.ACCESS_NETWORK_STATE,
1327 "ConnectivityService");
1328 }
1329
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001330 private void enforceConnectivityInternalPermission() {
1331 mContext.enforceCallingOrSelfPermission(
1332 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1333 "ConnectivityService");
1334 }
1335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001337 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1338 * network, we ignore it. If it is for the active network, we send out a
1339 * broadcast. But first, we check whether it might be possible to connect
1340 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 * @param info the {@code NetworkInfo} for the network
1342 */
1343 private void handleDisconnect(NetworkInfo info) {
1344
Robert Greenwalt42acef32009-08-12 16:08:25 -07001345 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346
Robert Greenwalt42acef32009-08-12 16:08:25 -07001347 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 /*
1349 * If the disconnected network is not the active one, then don't report
1350 * this as a loss of connectivity. What probably happened is that we're
1351 * getting the disconnect for a network that we explicitly disabled
1352 * in accordance with network preference policies.
1353 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001354 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001355 List pids = mNetRequestersPids[prevNetType];
1356 for (int i = 0; i<pids.size(); i++) {
1357 Integer pid = (Integer)pids.get(i);
1358 // will remove them because the net's no longer connected
1359 // need to do this now as only now do we know the pids and
1360 // can properly null things that are no longer referenced.
1361 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1366 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1367 if (info.isFailover()) {
1368 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1369 info.setFailover(false);
1370 }
1371 if (info.getReason() != null) {
1372 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1373 }
1374 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001375 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1376 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001378
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001379 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001380 tryFailover(prevNetType);
1381 if (mActiveDefaultNetwork != -1) {
1382 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001383 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1384 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001385 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001386 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1387 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001388 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001389 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001390
1391 // Reset interface if no other connections are using the same interface
1392 boolean doReset = true;
1393 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1394 if (linkProperties != null) {
1395 String oldIface = linkProperties.getInterfaceName();
1396 if (TextUtils.isEmpty(oldIface) == false) {
1397 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1398 if (networkStateTracker == null) continue;
1399 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1400 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1401 LinkProperties l = networkStateTracker.getLinkProperties();
1402 if (l == null) continue;
1403 if (oldIface.equals(l.getInterfaceName())) {
1404 doReset = false;
1405 break;
1406 }
1407 }
1408 }
1409 }
1410 }
1411
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001412 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001413 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001414
1415 sendStickyBroadcast(intent);
1416 /*
1417 * If the failover network is already connected, then immediately send
1418 * out a followup broadcast indicating successful failover
1419 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001420 if (mActiveDefaultNetwork != -1) {
1421 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001422 }
1423 }
1424
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001425 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001426 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001427 * If this is a default network, check if other defaults are available.
1428 * Try to reconnect on all available and let them hash it out when
1429 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001430 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001431 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001432 if (mActiveDefaultNetwork == prevNetType) {
1433 mActiveDefaultNetwork = -1;
1434 }
1435
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001436 // don't signal a reconnect for anything lower or equal priority than our
1437 // current connected default
1438 // TODO - don't filter by priority now - nice optimization but risky
1439// int currentPriority = -1;
1440// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001441// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001442// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001443 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001444 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001445 if (mNetConfigs[checkType] == null) continue;
1446 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001447
1448// Enabling the isAvailable() optimization caused mobile to not get
1449// selected if it was in the middle of error handling. Specifically
1450// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1451// would not be available and we wouldn't get connected to anything.
1452// So removing the isAvailable() optimization below for now. TODO: This
1453// optimization should work and we need to investigate why it doesn't work.
1454// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1455// complete before it is really complete.
1456// if (!mNetTrackers[checkType].isAvailable()) continue;
1457
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001458// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001459
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001460 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1461 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1462 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1463 checkInfo.setFailover(true);
1464 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001465 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001466 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
1470
1471 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001472 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1473 }
1474
1475 private void sendInetConditionBroadcast(NetworkInfo info) {
1476 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1477 }
1478
1479 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1480 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1482 if (info.isFailover()) {
1483 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1484 info.setFailover(false);
1485 }
1486 if (info.getReason() != null) {
1487 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1488 }
1489 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001490 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1491 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001493 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001494 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496
1497 /**
1498 * Called when an attempt to fail over to another network has failed.
1499 * @param info the {@link NetworkInfo} for the failed network
1500 */
1501 private void handleConnectionFailure(NetworkInfo info) {
1502 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
Robert Greenwalt42acef32009-08-12 16:08:25 -07001504 String reason = info.getReason();
1505 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001506
Robert Greenwalt572172b2010-10-08 16:35:52 -07001507 String reasonText;
1508 if (reason == null) {
1509 reasonText = ".";
1510 } else {
1511 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001513 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001514
1515 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1516 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1517 if (getActiveNetworkInfo() == null) {
1518 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1519 }
1520 if (reason != null) {
1521 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1522 }
1523 if (extraInfo != null) {
1524 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1525 }
1526 if (info.isFailover()) {
1527 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1528 info.setFailover(false);
1529 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001530
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001531 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001532 tryFailover(info.getType());
1533 if (mActiveDefaultNetwork != -1) {
1534 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001535 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1536 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001537 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001538 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1539 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001540 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001541
Robert Greenwalt029be812010-09-20 18:01:43 -07001542 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001543 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001544 /*
1545 * If the failover network is already connected, then immediately send
1546 * out a followup broadcast indicating successful failover
1547 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001548 if (mActiveDefaultNetwork != -1) {
1549 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001550 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001551 }
1552
1553 private void sendStickyBroadcast(Intent intent) {
1554 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001555 if (!mSystemReady) {
1556 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001557 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001558 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1559 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001560 }
1561 }
1562
1563 void systemReady() {
1564 synchronized(this) {
1565 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001566 if (mInitialBroadcast != null) {
1567 mContext.sendStickyBroadcast(mInitialBroadcast);
1568 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001569 }
1570 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001571 // load the global proxy at startup
1572 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
1575 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001576 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577
1578 // snapshot isFailover, because sendConnectedBroadcast() resets it
1579 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001580 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581
Robert Greenwalt42acef32009-08-12 16:08:25 -07001582 // if this is a default net and other default is running
1583 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001584 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001585 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1586 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001587 mNetConfigs[mActiveDefaultNetwork].priority >
1588 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001589 mNetworkPreference == mActiveDefaultNetwork) {
1590 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001591 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001592 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001593 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001594 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001595 teardown(thisNet);
1596 return;
1597 } else {
1598 // tear down the other
1599 NetworkStateTracker otherNet =
1600 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001601 if (DBG) {
1602 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001603 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001604 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001605 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001606 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001607 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001608 return;
1609 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001610 }
1611 }
1612 synchronized (ConnectivityService.this) {
1613 // have a new default network, release the transition wakelock in a second
1614 // if it's held. The second pause is to allow apps to reconnect over the
1615 // new network
1616 if (mNetTransitionWakeLock.isHeld()) {
1617 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001618 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001619 mNetTransitionWakeLockSerialNumber, 0),
1620 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001621 }
1622 }
1623 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001624 // this will cause us to come up initially as unconnected and switching
1625 // to connected after our normal pause unless somebody reports us as reall
1626 // disconnected
1627 mDefaultInetConditionPublished = 0;
1628 mDefaultConnectionSequence++;
1629 mInetConditionChangeInFlight = false;
1630 // Don't do this - if we never sign in stay, grey
1631 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001634 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001635 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001636 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001640 * After a change in the connectivity state of a network. We're mainly
1641 * concerned with making sure that the list of DNS servers is set up
1642 * according to which networks are connected, and ensuring that the
1643 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001645 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001646 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001649 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001650 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001652 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001653
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001654 LinkProperties curLp = mCurrentLinkProperties[netType];
1655 LinkProperties newLp = null;
1656
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001657 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001658 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001659 if (VDBG) {
1660 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1661 " doReset=" + doReset + " resetMask=" + resetMask +
1662 "\n curLp=" + curLp +
1663 "\n newLp=" + newLp);
1664 }
1665
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001666 if (curLp != null) {
1667 if (curLp.isIdenticalInterfaceName(newLp)) {
1668 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1669 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1670 for (LinkAddress linkAddr : car.removed) {
1671 if (linkAddr.getAddress() instanceof Inet4Address) {
1672 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1673 }
1674 if (linkAddr.getAddress() instanceof Inet6Address) {
1675 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1676 }
Wink Savillee8222252011-07-13 13:44:13 -07001677 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001678 if (DBG) {
1679 log("handleConnectivityChange: addresses changed" +
1680 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1681 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001682 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001683 } else {
1684 if (DBG) {
1685 log("handleConnectivityChange: address are the same reset per doReset" +
1686 " linkProperty[" + netType + "]:" +
1687 " resetMask=" + resetMask);
1688 }
Wink Savillee8222252011-07-13 13:44:13 -07001689 }
1690 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001691 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001692 if (DBG) {
1693 log("handleConnectivityChange: interface not not equivalent reset both" +
1694 " linkProperty[" + netType + "]:" +
1695 " resetMask=" + resetMask);
1696 }
Wink Savillee8222252011-07-13 13:44:13 -07001697 }
Wink Savillee8222252011-07-13 13:44:13 -07001698 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001699 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001700 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001701 }
1702 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001703 if (VDBG) {
1704 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1705 " doReset=" + doReset + " resetMask=" + resetMask +
1706 "\n curLp=" + curLp +
1707 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001710 mCurrentLinkProperties[netType] = newLp;
1711 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001712
Wink Savillee8222252011-07-13 13:44:13 -07001713 if (doReset || resetMask != 0) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001714 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1715 if (linkProperties != null) {
1716 String iface = linkProperties.getInterfaceName();
1717 if (TextUtils.isEmpty(iface) == false) {
Wink Savillee8222252011-07-13 13:44:13 -07001718 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1719 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001720 }
1721 }
1722 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001723
1724 // TODO: Temporary notifying upstread change to Tethering.
1725 // @see bug/4455071
1726 /** Notify TetheringService if interface name has been changed. */
1727 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1728 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1729 if (isTetheringSupported()) {
1730 mTethering.handleTetherIfaceChange();
1731 }
1732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001735 /**
1736 * Add and remove routes using the old properties (null if not previously connected),
1737 * new properties (null if becoming disconnected). May even be double null, which
1738 * is a noop.
1739 * Uses isLinkDefault to determine if default routes should be set or conversely if
1740 * host routes should be set to the dns servers
1741 */
1742 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1743 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001744 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1745 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001746 if (curLp != null) {
1747 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001748 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001749 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001750 } else if (newLp != null) {
1751 routeDiff.added = newLp.getRoutes();
1752 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001753 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001754
Robert Greenwaltad55d352011-07-22 11:55:33 -07001755 for (RouteInfo r : routeDiff.removed) {
1756 if (isLinkDefault || ! r.isDefaultRoute()) {
1757 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001758 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001759 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001760
Robert Greenwaltad55d352011-07-22 11:55:33 -07001761 for (RouteInfo r : routeDiff.added) {
1762 if (isLinkDefault || ! r.isDefaultRoute()) {
1763 addRoute(newLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001764 }
1765 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001766
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001767 if (!isLinkDefault) {
1768 // handle DNS routes
Robert Greenwaltad55d352011-07-22 11:55:33 -07001769 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1770 // no change in routes, check for change in dns themselves
1771 for (InetAddress oldDns : dnsDiff.removed) {
1772 removeRouteToAddress(curLp, oldDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001773 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001774 for (InetAddress newDns : dnsDiff.added) {
1775 addRouteToAddress(newLp, newDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001776 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001777 } else {
1778 // routes changed - remove all old dns entries and add new
1779 if (curLp != null) {
1780 for (InetAddress oldDns : curLp.getDnses()) {
1781 removeRouteToAddress(curLp, oldDns);
1782 }
1783 }
1784 if (newLp != null) {
1785 for (InetAddress newDns : newLp.getDnses()) {
1786 addRouteToAddress(newLp, newDns);
1787 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001788 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001789 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001790 }
1791 }
1792
1793
Irfan Sheriffd649c122010-06-09 15:39:36 -07001794 /**
1795 * Reads the network specific TCP buffer sizes from SystemProperties
1796 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1797 * wide use
1798 */
1799 public void updateNetworkSettings(NetworkStateTracker nt) {
1800 String key = nt.getTcpBufferSizesPropName();
1801 String bufferSizes = SystemProperties.get(key);
1802
1803 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001804 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001805
1806 // Setting to default values so we won't be stuck to previous values
1807 key = "net.tcp.buffersize.default";
1808 bufferSizes = SystemProperties.get(key);
1809 }
1810
1811 // Set values in kernel
1812 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001813 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001814 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001815 + "] which comes from [" + key + "]");
1816 }
1817 setBufferSize(bufferSizes);
1818 }
1819 }
1820
1821 /**
1822 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1823 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1824 *
1825 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1826 * writeMin, writeInitial, writeMax"
1827 */
1828 private void setBufferSize(String bufferSizes) {
1829 try {
1830 String[] values = bufferSizes.split(",");
1831
1832 if (values.length == 6) {
1833 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001834 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1835 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1836 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1837 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1838 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1839 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001840 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001841 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001842 }
1843 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001844 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001845 }
1846 }
1847
Robert Greenwalt42acef32009-08-12 16:08:25 -07001848 /**
1849 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1850 * on the highest priority active net which this process requested.
1851 * If there aren't any, clear it out
1852 */
1853 private void reassessPidDns(int myPid, boolean doBump)
1854 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001855 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001856 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001857 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001858 continue;
1859 }
1860 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001861 if (nt.getNetworkInfo().isConnected() &&
1862 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001863 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001864 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001865 List pids = mNetRequestersPids[i];
1866 for (int j=0; j<pids.size(); j++) {
1867 Integer pid = (Integer)pids.get(j);
1868 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001869 Collection<InetAddress> dnses = p.getDnses();
1870 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001871 if (doBump) {
1872 bumpDns();
1873 }
1874 return;
1875 }
1876 }
1877 }
1878 }
1879 // nothing found - delete
1880 for (int i = 1; ; i++) {
1881 String prop = "net.dns" + i + "." + myPid;
1882 if (SystemProperties.get(prop).length() == 0) {
1883 if (doBump) {
1884 bumpDns();
1885 }
1886 return;
1887 }
1888 SystemProperties.set(prop, "");
1889 }
1890 }
1891
Robert Greenwalt10398722010-12-17 15:20:36 -08001892 // return true if results in a change
1893 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001894 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001895 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001896 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001897 String dnsString = dns.getHostAddress();
1898 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1899 changed = true;
1900 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1901 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001903 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001904 }
1905
1906 private void bumpDns() {
1907 /*
1908 * Bump the property that tells the name resolver library to reread
1909 * the DNS server list from the properties.
1910 */
1911 String propVal = SystemProperties.get("net.dnschange");
1912 int n = 0;
1913 if (propVal.length() != 0) {
1914 try {
1915 n = Integer.parseInt(propVal);
1916 } catch (NumberFormatException e) {}
1917 }
1918 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001919 /*
1920 * Tell the VMs to toss their DNS caches
1921 */
1922 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1923 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001924 /*
1925 * Connectivity events can happen before boot has completed ...
1926 */
1927 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001928 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001929 }
1930
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001931 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001932 private boolean updateDns(String network, String iface,
1933 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001934 boolean changed = false;
1935 int last = 0;
1936 if (dnses.size() == 0 && mDefaultDns != null) {
1937 ++last;
1938 String value = mDefaultDns.getHostAddress();
1939 if (!value.equals(SystemProperties.get("net.dns1"))) {
1940 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001941 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001942 }
1943 changed = true;
1944 SystemProperties.set("net.dns1", value);
1945 }
1946 } else {
1947 for (InetAddress dns : dnses) {
1948 ++last;
1949 String key = "net.dns" + last;
1950 String value = dns.getHostAddress();
1951 if (!changed && value.equals(SystemProperties.get(key))) {
1952 continue;
1953 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001954 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001955 log("adding dns " + value + " for " + network);
1956 }
1957 changed = true;
1958 SystemProperties.set(key, value);
1959 }
1960 }
1961 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
1962 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001963 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001964 changed = true;
1965 SystemProperties.set(key, "");
1966 }
1967 mNumDnsEntries = last;
1968
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001969 if (changed) {
1970 try {
1971 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
1972 mNetd.setDefaultInterfaceForDns(iface);
1973 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001974 loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001975 }
1976 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001977 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
1978 SystemProperties.set("net.dns.search", domains);
1979 changed = true;
1980 }
1981 return changed;
1982 }
1983
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001984 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001985 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001986 NetworkStateTracker nt = mNetTrackers[netType];
1987 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001988 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001989 if (p == null) return;
1990 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08001991 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001992 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001993 String network = nt.getNetworkInfo().getTypeName();
1994 synchronized (mDnsLock) {
1995 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001996 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001997 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001998 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001999 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002000 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002001 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002002 NetworkUtils.makeStrings(dnses));
2003 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002004 loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002005 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002006 // set per-pid dns for attached secondary nets
2007 List pids = mNetRequestersPids[netType];
2008 for (int y=0; y< pids.size(); y++) {
2009 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002010 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 }
2012 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002013 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002015 }
2016
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002017 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002018 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2019 NETWORK_RESTORE_DELAY_PROP_NAME);
2020 if(restoreDefaultNetworkDelayStr != null &&
2021 restoreDefaultNetworkDelayStr.length() != 0) {
2022 try {
2023 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2024 } catch (NumberFormatException e) {
2025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002027 // if the system property isn't set, use the value for the apn type
2028 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2029
2030 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2031 (mNetConfigs[networkType] != null)) {
2032 ret = mNetConfigs[networkType].restoreTime;
2033 }
2034 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
2036
2037 @Override
2038 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002039 if (mContext.checkCallingOrSelfPermission(
2040 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002042 pw.println("Permission Denial: can't dump ConnectivityService " +
2043 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2044 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 return;
2046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 pw.println();
2048 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002049 if (nst != null) {
2050 if (nst.getNetworkInfo().isConnected()) {
2051 pw.println("Active network: " + nst.getNetworkInfo().
2052 getTypeName());
2053 }
2054 pw.println(nst.getNetworkInfo());
2055 pw.println(nst);
2056 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002059
2060 pw.println("Network Requester Pids:");
2061 for (int net : mPriorityList) {
2062 String pidString = net + ": ";
2063 for (Object pid : mNetRequestersPids[net]) {
2064 pidString = pidString + pid.toString() + ", ";
2065 }
2066 pw.println(pidString);
2067 }
2068 pw.println();
2069
2070 pw.println("FeatureUsers:");
2071 for (Object requester : mFeatureUsers) {
2072 pw.println(requester.toString());
2073 }
2074 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002075
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002076 synchronized (this) {
2077 pw.println("NetworkTranstionWakeLock is currently " +
2078 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2079 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2080 }
2081 pw.println();
2082
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002083 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002084
2085 if (mInetLog != null) {
2086 pw.println();
2087 pw.println("Inet condition reports:");
2088 for(int i = 0; i < mInetLog.size(); i++) {
2089 pw.println(mInetLog.get(i));
2090 }
2091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093
Robert Greenwalt42acef32009-08-12 16:08:25 -07002094 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002096 public MyHandler(Looper looper) {
2097 super(looper);
2098 }
2099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 @Override
2101 public void handleMessage(Message msg) {
2102 NetworkInfo info;
2103 switch (msg.what) {
2104 case NetworkStateTracker.EVENT_STATE_CHANGED:
2105 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002106 int type = info.getType();
2107 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002108
Wink Savilleed9c02b2010-12-03 12:01:38 -08002109 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002110 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002111 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112
2113 // Connectivity state changed:
2114 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002115 // [12-9] Network subtype (for mobile network, as defined
2116 // by TelephonyManager)
2117 // [8-3] Detailed state ordinal (as defined by
2118 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 // [2-0] Network type (as defined by ConnectivityManager)
2120 int eventLogParam = (info.getType() & 0x7) |
2121 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2122 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002123 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002124 eventLogParam);
2125
2126 if (info.getDetailedState() ==
2127 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002129 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002131 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002133 // the logic here is, handle SUSPENDED the same as
2134 // DISCONNECTED. The only difference being we are
2135 // broadcasting an intent with NetworkInfo that's
2136 // suspended. This allows the applications an
2137 // opportunity to handle DISCONNECTED and SUSPENDED
2138 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002140 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 handleConnect(info);
2142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002145 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002146 // TODO: Temporary allowing network configuration
2147 // change not resetting sockets.
2148 // @see bug/4455071
2149 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002151 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002152 String causedBy = null;
2153 synchronized (ConnectivityService.this) {
2154 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2155 mNetTransitionWakeLock.isHeld()) {
2156 mNetTransitionWakeLock.release();
2157 causedBy = mNetTransitionWakeLockCausedBy;
2158 }
2159 }
2160 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002161 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002162 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002163 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002164 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002165 FeatureUser u = (FeatureUser)msg.obj;
2166 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002167 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002168 case EVENT_INET_CONDITION_CHANGE:
2169 {
2170 int netType = msg.arg1;
2171 int condition = msg.arg2;
2172 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002173 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002174 }
2175 case EVENT_INET_CONDITION_HOLD_END:
2176 {
2177 int netType = msg.arg1;
2178 int sequence = msg.arg2;
2179 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002180 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002181 }
2182 case EVENT_SET_NETWORK_PREFERENCE:
2183 {
2184 int preference = msg.arg1;
2185 handleSetNetworkPreference(preference);
2186 break;
2187 }
2188 case EVENT_SET_BACKGROUND_DATA:
2189 {
2190 boolean enabled = (msg.arg1 == ENABLED);
2191 handleSetBackgroundData(enabled);
2192 break;
2193 }
2194 case EVENT_SET_MOBILE_DATA:
2195 {
2196 boolean enabled = (msg.arg1 == ENABLED);
2197 handleSetMobileData(enabled);
2198 break;
2199 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002200 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2201 {
2202 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002203 break;
2204 }
2205 case EVENT_SET_DEPENDENCY_MET:
2206 {
2207 boolean met = (msg.arg1 == ENABLED);
2208 handleSetDependencyMet(msg.arg2, met);
2209 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002210 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002211 case EVENT_RESTORE_DNS:
2212 {
2213 if (mActiveDefaultNetwork != -1) {
2214 handleDnsConfigurationChange(mActiveDefaultNetwork);
2215 }
2216 break;
2217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
2219 }
2220 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002221
2222 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002223 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002224 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002225
2226 if (isTetheringSupported()) {
2227 return mTethering.tether(iface);
2228 } else {
2229 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2230 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002231 }
2232
2233 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002234 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002235 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002236
2237 if (isTetheringSupported()) {
2238 return mTethering.untether(iface);
2239 } else {
2240 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2241 }
2242 }
2243
2244 // javadoc from interface
2245 public int getLastTetherError(String iface) {
2246 enforceTetherAccessPermission();
2247
2248 if (isTetheringSupported()) {
2249 return mTethering.getLastTetherError(iface);
2250 } else {
2251 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2252 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002253 }
2254
2255 // TODO - proper iface API for selection by property, inspection, etc
2256 public String[] getTetherableUsbRegexs() {
2257 enforceTetherAccessPermission();
2258 if (isTetheringSupported()) {
2259 return mTethering.getTetherableUsbRegexs();
2260 } else {
2261 return new String[0];
2262 }
2263 }
2264
2265 public String[] getTetherableWifiRegexs() {
2266 enforceTetherAccessPermission();
2267 if (isTetheringSupported()) {
2268 return mTethering.getTetherableWifiRegexs();
2269 } else {
2270 return new String[0];
2271 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002272 }
2273
Danica Chang6fdd0c62010-08-11 14:54:43 -07002274 public String[] getTetherableBluetoothRegexs() {
2275 enforceTetherAccessPermission();
2276 if (isTetheringSupported()) {
2277 return mTethering.getTetherableBluetoothRegexs();
2278 } else {
2279 return new String[0];
2280 }
2281 }
2282
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002283 public int setUsbTethering(boolean enable) {
2284 enforceTetherAccessPermission();
2285 if (isTetheringSupported()) {
2286 return mTethering.setUsbTethering(enable);
2287 } else {
2288 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2289 }
2290 }
2291
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002292 // TODO - move iface listing, queries, etc to new module
2293 // javadoc from interface
2294 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002295 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002296 return mTethering.getTetherableIfaces();
2297 }
2298
2299 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002300 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002301 return mTethering.getTetheredIfaces();
2302 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002303
Robert Greenwalt5a735062010-03-02 17:25:02 -08002304 public String[] getTetheringErroredIfaces() {
2305 enforceTetherAccessPermission();
2306 return mTethering.getErroredIfaces();
2307 }
2308
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002309 // if ro.tether.denied = true we default to no tethering
2310 // gservices could set the secure setting to 1 though to enable it on a build where it
2311 // had previously been turned off.
2312 public boolean isTetheringSupported() {
2313 enforceTetherAccessPermission();
2314 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002315 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2316 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2317 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002318 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002319
2320 // An API NetworkStateTrackers can call when they lose their network.
2321 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2322 // whichever happens first. The timer is started by the first caller and not
2323 // restarted by subsequent callers.
2324 public void requestNetworkTransitionWakelock(String forWhom) {
2325 enforceConnectivityInternalPermission();
2326 synchronized (this) {
2327 if (mNetTransitionWakeLock.isHeld()) return;
2328 mNetTransitionWakeLockSerialNumber++;
2329 mNetTransitionWakeLock.acquire();
2330 mNetTransitionWakeLockCausedBy = forWhom;
2331 }
2332 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002333 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002334 mNetTransitionWakeLockSerialNumber, 0),
2335 mNetTransitionWakeLockTimeout);
2336 return;
2337 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002338
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002339 // 100 percent is full good, 0 is full bad.
2340 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002341 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002342 mContext.enforceCallingOrSelfPermission(
2343 android.Manifest.permission.STATUS_BAR,
2344 "ConnectivityService");
2345
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002346 if (DBG) {
2347 int pid = getCallingPid();
2348 int uid = getCallingUid();
2349 String s = pid + "(" + uid + ") reports inet is " +
2350 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2351 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2352 mInetLog.add(s);
2353 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2354 mInetLog.remove(0);
2355 }
2356 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002357 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002358 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2359 }
2360
2361 private void handleInetConditionChange(int netType, int condition) {
2362 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002363 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002364 netType + ", condition=" + condition +
2365 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2366 }
2367 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002368 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002369 return;
2370 }
2371 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002372 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002373 return;
2374 }
2375 mDefaultInetCondition = condition;
2376 int delay;
2377 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002378 if (VDBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002379 // setup a new hold to debounce this
2380 if (mDefaultInetCondition > 50) {
2381 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2382 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2383 } else {
2384 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2385 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2386 }
2387 mInetConditionChangeInFlight = true;
2388 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2389 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2390 } else {
2391 // we've set the new condition, when this hold ends that will get
2392 // picked up
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002393 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002394 }
2395 }
2396
2397 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002398 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002399 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002400 ", condition =" + mDefaultInetCondition +
2401 ", published condition =" + mDefaultInetConditionPublished);
2402 }
2403 mInetConditionChangeInFlight = false;
2404
2405 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002406 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002407 return;
2408 }
2409 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002410 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002411 return;
2412 }
2413 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002414 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002415 return;
2416 }
2417 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2418 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002419 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002420 return;
2421 }
2422 mDefaultInetConditionPublished = mDefaultInetCondition;
2423 sendInetConditionBroadcast(networkInfo);
2424 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002425 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002426
2427 public synchronized ProxyProperties getProxy() {
2428 if (mGlobalProxy != null) return mGlobalProxy;
2429 if (mDefaultProxy != null) return mDefaultProxy;
2430 return null;
2431 }
2432
2433 public void setGlobalProxy(ProxyProperties proxyProperties) {
2434 enforceChangePermission();
2435 synchronized (mGlobalProxyLock) {
2436 if (proxyProperties == mGlobalProxy) return;
2437 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2438 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2439
2440 String host = "";
2441 int port = 0;
2442 String exclList = "";
2443 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2444 mGlobalProxy = new ProxyProperties(proxyProperties);
2445 host = mGlobalProxy.getHost();
2446 port = mGlobalProxy.getPort();
2447 exclList = mGlobalProxy.getExclusionList();
2448 } else {
2449 mGlobalProxy = null;
2450 }
2451 ContentResolver res = mContext.getContentResolver();
2452 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2453 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002454 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002455 exclList);
2456 }
2457
2458 if (mGlobalProxy == null) {
2459 proxyProperties = mDefaultProxy;
2460 }
2461 sendProxyBroadcast(proxyProperties);
2462 }
2463
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002464 private void loadGlobalProxy() {
2465 ContentResolver res = mContext.getContentResolver();
2466 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2467 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2468 String exclList = Settings.Secure.getString(res,
2469 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2470 if (!TextUtils.isEmpty(host)) {
2471 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2472 synchronized (mGlobalProxyLock) {
2473 mGlobalProxy = proxyProperties;
2474 }
2475 }
2476 }
2477
Robert Greenwalt434203a2010-10-11 16:00:27 -07002478 public ProxyProperties getGlobalProxy() {
2479 synchronized (mGlobalProxyLock) {
2480 return mGlobalProxy;
2481 }
2482 }
2483
2484 private void handleApplyDefaultProxy(int type) {
2485 // check if new default - push it out to all VM if so
2486 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2487 synchronized (this) {
2488 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2489 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002490 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002491 mDefaultProxy = proxy;
2492 } else {
2493 mDefaultProxy = null;
2494 }
2495 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002496 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002497 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2498 if (mGlobalProxy != null) return;
2499 sendProxyBroadcast(proxy);
2500 }
2501
2502 private void handleDeprecatedGlobalHttpProxy() {
2503 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2504 Settings.Secure.HTTP_PROXY);
2505 if (!TextUtils.isEmpty(proxy)) {
2506 String data[] = proxy.split(":");
2507 String proxyHost = data[0];
2508 int proxyPort = 8080;
2509 if (data.length > 1) {
2510 try {
2511 proxyPort = Integer.parseInt(data[1]);
2512 } catch (NumberFormatException e) {
2513 return;
2514 }
2515 }
2516 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2517 setGlobalProxy(p);
2518 }
2519 }
2520
2521 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002522 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002523 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002524 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002525 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2526 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002527 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002528 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002529 }
2530
2531 private static class SettingsObserver extends ContentObserver {
2532 private int mWhat;
2533 private Handler mHandler;
2534 SettingsObserver(Handler handler, int what) {
2535 super(handler);
2536 mHandler = handler;
2537 mWhat = what;
2538 }
2539
2540 void observe(Context context) {
2541 ContentResolver resolver = context.getContentResolver();
2542 resolver.registerContentObserver(Settings.Secure.getUriFor(
2543 Settings.Secure.HTTP_PROXY), false, this);
2544 }
2545
2546 @Override
2547 public void onChange(boolean selfChange) {
2548 mHandler.obtainMessage(mWhat).sendToTarget();
2549 }
2550 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002551
2552 private void log(String s) {
2553 Slog.d(TAG, s);
2554 }
2555
2556 private void loge(String s) {
2557 Slog.e(TAG, s);
2558 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002559
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002560 int convertFeatureToNetworkType(String feature){
2561 int networkType = -1;
2562 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2563 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2564 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2565 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2566 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2567 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2568 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2569 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2570 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2571 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2572 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2573 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2574 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2575 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2576 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2577 }
2578 return networkType;
2579 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002580
2581 private static <T> T checkNotNull(T value, String message) {
2582 if (value == null) {
2583 throw new NullPointerException(message);
2584 }
2585 return value;
2586 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002587
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002588 /**
2589 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002590 * VpnBuilder and not available in ConnectivityManager. Permissions
2591 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002592 * @hide
2593 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002594 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002595 public boolean protectVpn(ParcelFileDescriptor socket) {
2596 try {
2597 int type = mActiveDefaultNetwork;
2598 if (ConnectivityManager.isNetworkTypeValid(type)) {
2599 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2600 return true;
2601 }
2602 } catch (Exception e) {
2603 // ignore
2604 } finally {
2605 try {
2606 socket.close();
2607 } catch (Exception e) {
2608 // ignore
2609 }
2610 }
2611 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002612 }
2613
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002614 /**
2615 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002616 * and not available in ConnectivityManager. Permissions are checked
2617 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002618 * @hide
2619 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002620 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002621 public boolean prepareVpn(String oldPackage, String newPackage) {
2622 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002623 }
2624
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002625 /**
2626 * Configure a TUN interface and return its file descriptor. Parameters
2627 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002628 * and not available in ConnectivityManager. Permissions are checked in
2629 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002630 * @hide
2631 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002632 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002633 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002634 return mVpn.establish(config);
2635 }
2636
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002637 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002638 * Start legacy VPN and return an intent to VpnDialogs. This method is
2639 * used by VpnSettings and not available in ConnectivityManager.
2640 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002641 * @hide
2642 */
2643 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002644 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2645 mVpn.startLegacyVpn(config, racoon, mtpd);
2646 }
2647
2648 /**
2649 * Return the information of the ongoing legacy VPN. This method is used
2650 * by VpnSettings and not available in ConnectivityManager. Permissions
2651 * are checked in Vpn class.
2652 * @hide
2653 */
2654 @Override
2655 public LegacyVpnInfo getLegacyVpnInfo() {
2656 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002657 }
2658
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002659 /**
2660 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2661 * through NetworkStateTracker since it works differently. For example, it
2662 * needs to override DNS servers but never takes the default routes. It
2663 * relies on another data network, and it could keep existing connections
2664 * alive after reconnecting, switching between networks, or even resuming
2665 * from deep sleep. Calls from applications should be done synchronously
2666 * to avoid race conditions. As these are all hidden APIs, refactoring can
2667 * be done whenever a better abstraction is developed.
2668 */
2669 public class VpnCallback {
2670
2671 private VpnCallback() {
2672 }
2673
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002674 public void override(List<String> dnsServers, List<String> searchDomains) {
2675 if (dnsServers == null) {
2676 restore();
2677 return;
2678 }
2679
2680 // Convert DNS servers into addresses.
2681 List<InetAddress> addresses = new ArrayList<InetAddress>();
2682 for (String address : dnsServers) {
2683 // Double check the addresses and remove invalid ones.
2684 try {
2685 addresses.add(InetAddress.parseNumericAddress(address));
2686 } catch (Exception e) {
2687 // ignore
2688 }
2689 }
2690 if (addresses.isEmpty()) {
2691 restore();
2692 return;
2693 }
2694
2695 // Concatenate search domains into a string.
2696 StringBuilder buffer = new StringBuilder();
2697 if (searchDomains != null) {
2698 for (String domain : searchDomains) {
2699 buffer.append(domain).append(' ');
2700 }
2701 }
2702 String domains = buffer.toString().trim();
2703
2704 // Apply DNS changes.
2705 boolean changed = false;
2706 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002707 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002708 mDnsOverridden = true;
2709 }
2710 if (changed) {
2711 bumpDns();
2712 }
2713
2714 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002715 }
2716
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002717 public void restore() {
2718 synchronized (mDnsLock) {
2719 if (!mDnsOverridden) {
2720 return;
2721 }
2722 mDnsOverridden = false;
2723 }
2724 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002725 }
2726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727}