blob: 9a9cc8ffba27e845c2d2a4942f8b456ee3a2c140 [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
347 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
348 }
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() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800801 log("ConnectivityService FeatureUser expire(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800802 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
803 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700804 stopUsingNetworkFeature(this, false);
805 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800806
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500807 public boolean isSameUser(FeatureUser u) {
808 if (u == null) return false;
809
810 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
811 }
812
813 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
814 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
815 TextUtils.equals(mFeature, feature)) {
816 return true;
817 }
818 return false;
819 }
820
Robert Greenwaltb9285352009-12-21 18:24:07 -0800821 public String toString() {
822 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
823 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
824 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700825 }
826
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700827 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700828 public int startUsingNetworkFeature(int networkType, String feature,
829 IBinder binder) {
830 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800831 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700834 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700835 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700836 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700838
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700839 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700840
841 // TODO - move this into the MobileDataStateTracker
842 int usedNetworkType = networkType;
843 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800844 usedNetworkType = convertFeatureToNetworkType(feature);
845 if (usedNetworkType < 0) {
846 Slog.e(TAG, "Can't match any netTracker!");
847 usedNetworkType = networkType;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700848 }
849 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700850
851 if (mProtectedNetworks.contains(usedNetworkType)) {
852 enforceConnectivityInternalPermission();
853 }
854
Robert Greenwalt42acef32009-08-12 16:08:25 -0700855 NetworkStateTracker network = mNetTrackers[usedNetworkType];
856 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800857 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700858 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700859 NetworkStateTracker radio = mNetTrackers[networkType];
860 NetworkInfo ni = network.getNetworkInfo();
861
862 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800863 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800864 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
865 return Phone.APN_TYPE_NOT_AVAILABLE;
866 } else {
867 // else make the attempt anyway - probably giving REQUEST_STARTED below
868 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700869 }
870
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500871 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
872
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700873 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500874 boolean addToList = true;
875 if (restoreTimer < 0) {
876 // In case there is no timer is specified for the feature,
877 // make sure we don't add duplicate entry with the same request.
878 for (FeatureUser u : mFeatureUsers) {
879 if (u.isSameUser(f)) {
880 // Duplicate user is found. Do not add.
881 addToList = false;
882 break;
883 }
884 }
885 }
886
887 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700888 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
889 // this gets used for per-pid dns when connected
890 mNetRequestersPids[usedNetworkType].add(currentPid);
891 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700893
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700894 if (restoreTimer >= 0) {
895 mHandler.sendMessageDelayed(
896 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
897 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700898
Robert Greenwalta64bf832009-08-19 20:19:33 -0700899 if ((ni.isConnectedOrConnecting() == true) &&
900 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700901 if (ni.isConnected() == true) {
902 // add the pid-specific dns
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -0700903 handleDnsConfigurationChange(networkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800904 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700905 return Phone.APN_ALREADY_ACTIVE;
906 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800907 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700908 return Phone.APN_REQUEST_STARTED;
909 }
910
911 // check if the radio in play can make another contact
912 // assume if cannot for now
913
Wink Savilleed9c02b2010-12-03 12:01:38 -0800914 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700915 network.reconnect();
916 return Phone.APN_REQUEST_STARTED;
917 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800918 // need to remember this unsupported request so we respond appropriately on stop
919 synchronized(this) {
920 mFeatureUsers.add(f);
921 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
922 // this gets used for per-pid dns when connected
923 mNetRequestersPids[usedNetworkType].add(currentPid);
924 }
925 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700926 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700927 }
928 }
929 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 }
931
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700932 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700934 enforceChangePermission();
935
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700936 int pid = getCallingPid();
937 int uid = getCallingUid();
938
939 FeatureUser u = null;
940 boolean found = false;
941
942 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500943 for (FeatureUser x : mFeatureUsers) {
944 if (x.isSameUser(pid, uid, networkType, feature)) {
945 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700946 found = true;
947 break;
948 }
949 }
950 }
951 if (found && u != null) {
952 // stop regardless of how many other time this proc had called start
953 return stopUsingNetworkFeature(u, true);
954 } else {
955 // none found!
Wink Savilleed9c02b2010-12-03 12:01:38 -0800956 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700957 return 1;
958 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700959 }
960
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700961 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
962 int networkType = u.mNetworkType;
963 String feature = u.mFeature;
964 int pid = u.mPid;
965 int uid = u.mUid;
966
967 NetworkStateTracker tracker = null;
968 boolean callTeardown = false; // used to carry our decision outside of sync block
969
Robert Greenwalt42acef32009-08-12 16:08:25 -0700970 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800971 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700972 ": " + feature);
973 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
976 return -1;
977 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700978
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700979 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
980 // sync block
981 synchronized(this) {
982 // check if this process still has an outstanding start request
983 if (!mFeatureUsers.contains(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800984 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700985 return 1;
986 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700987 u.unlinkDeathRecipient();
988 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
989 // If we care about duplicate requests, check for that here.
990 //
991 // This is done to support the extension of a request - the app
992 // can request we start the network feature again and renew the
993 // auto-shutoff delay. Normal "stop" calls from the app though
994 // do not pay attention to duplicate requests - in effect the
995 // API does not refcount and a single stop will counter multiple starts.
996 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500997 for (FeatureUser x : mFeatureUsers) {
998 if (x.isSameUser(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800999 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001000 return 1;
1001 }
1002 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001003 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001004
1005 // TODO - move to MobileDataStateTracker
1006 int usedNetworkType = networkType;
1007 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -08001008 usedNetworkType = convertFeatureToNetworkType(feature);
1009 if (usedNetworkType < 0) {
1010 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001011 }
1012 }
1013 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001014 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001015 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001016 return -1;
1017 }
1018 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001019 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001020 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001021 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001022 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001023 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001024 "others still using it");
1025 return 1;
1026 }
1027 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001028 } else {
1029 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001030 }
1031 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001032 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001033 if (callTeardown) {
1034 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001035 return 1;
1036 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001037 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040
1041 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001042 * @deprecated use requestRouteToHostAddress instead
1043 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 * Ensure that a network route exists to deliver traffic to the specified
1045 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001046 * @param networkType the type of the network over which traffic to the
1047 * specified host is to be routed
1048 * @param hostAddress the IP address of the host to which the route is
1049 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 * @return {@code true} on success, {@code false} on failure
1051 */
1052 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001053 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1054
1055 if (inetAddress == null) {
1056 return false;
1057 }
1058
1059 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1060 }
1061
1062 /**
1063 * Ensure that a network route exists to deliver traffic to the specified
1064 * host via the specified network interface.
1065 * @param networkType the type of the network over which traffic to the
1066 * specified host is to be routed
1067 * @param hostAddress the IP address of the host to which the route is
1068 * desired
1069 * @return {@code true} on success, {@code false} on failure
1070 */
1071 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001073 if (mProtectedNetworks.contains(networkType)) {
1074 enforceConnectivityInternalPermission();
1075 }
1076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1078 return false;
1079 }
1080 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001081
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001082 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1083 tracker.isTeardownRequested()) {
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001084 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001085 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001086 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001087 }
1088 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001090 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001091 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001092 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001093 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001094 } catch (UnknownHostException e) {}
1095 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001096 }
1097
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001098 private boolean addRoute(LinkProperties p, RouteInfo r) {
1099 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001100 }
1101
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001102 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1103 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1104 }
1105
Robert Greenwaltad55d352011-07-22 11:55:33 -07001106 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1107 return modifyRouteToAddress(lp, addr, true);
1108 }
1109
1110 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1111 return modifyRouteToAddress(lp, addr, false);
1112 }
1113
1114 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1115 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1116 if (bestRoute == null) {
1117 bestRoute = RouteInfo.makeHostRoute(addr);
1118 } else {
1119 if (bestRoute.getGateway().equals(addr)) {
1120 // if there is no better route, add the implied hostroute for our gateway
1121 bestRoute = RouteInfo.makeHostRoute(addr);
1122 } else {
1123 // if we will connect to this through another route, add a direct route
1124 // to it's gateway
1125 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1126 }
1127 }
1128 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1129 }
1130
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001131 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1132 boolean doAdd) {
1133 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1134
1135 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1136 loge("Error adding route - too much recursion");
1137 return false;
1138 }
1139
1140 if (r.isHostRoute() == false) {
1141 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1142 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001143 if (bestRoute.getGateway().equals(r.getGateway())) {
1144 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001145 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001146 } else {
1147 // if we will connect to our gateway through another route, add a direct
1148 // route to it's gateway
1149 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001150 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001151 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001152 }
1153 }
1154 if (doAdd) {
1155 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1156 mAddedRoutes.add(r);
1157 try {
1158 mNetd.addRoute(ifaceName, r);
1159 } catch (Exception e) {
1160 // never crash - catch them all
1161 loge("Exception trying to add a route: " + e);
1162 return false;
1163 }
1164 } else {
1165 // if we remove this one and there are no more like it, then refcount==0 and
1166 // we can remove it from the table
1167 mAddedRoutes.remove(r);
1168 if (mAddedRoutes.contains(r) == false) {
1169 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1170 try {
1171 mNetd.removeRoute(ifaceName, r);
1172 } catch (Exception e) {
1173 // never crash - catch them all
1174 loge("Exception trying to remove a route: " + e);
1175 return false;
1176 }
1177 } else {
1178 if (DBG) log("not removing " + r + " as it's still in use");
1179 }
1180 }
1181 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183
1184 /**
1185 * @see ConnectivityManager#getBackgroundDataSetting()
1186 */
1187 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001188 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 /**
1192 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1193 */
1194 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1195 mContext.enforceCallingOrSelfPermission(
1196 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1197 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001198
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001199 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1200
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001201 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1202 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001205 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-02-25 13:44:09 -08001206 Settings.Secure.putInt(mContext.getContentResolver(),
1207 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1208 Intent broadcast = new Intent(
1209 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1210 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001211 }
1212
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001213 /**
1214 * @see ConnectivityManager#getMobileDataEnabled()
1215 */
1216 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001217 // TODO: This detail should probably be in DataConnectionTracker's
1218 // which is where we store the value and maybe make this
1219 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001220 enforceAccessPermission();
1221 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1222 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savilleed9c02b2010-12-03 12:01:38 -08001223 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001224 return retVal;
1225 }
1226
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001227 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001228 enforceConnectivityInternalPermission();
1229
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001230 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1231 (met ? ENABLED : DISABLED), networkType));
1232 }
1233
1234 private void handleSetDependencyMet(int networkType, boolean met) {
1235 if (mNetTrackers[networkType] != null) {
1236 if (DBG) {
1237 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1238 }
1239 mNetTrackers[networkType].setDependencyMet(met);
1240 }
1241 }
1242
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001243 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1244 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001245 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001246 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001247 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001248
1249 if (LOGD_RULES) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001250 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001251 }
1252
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001253 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001254 // skip update when we've already applied rules
1255 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1256 if (oldRules == uidRules) return;
1257
1258 mUidRules.put(uid, uidRules);
1259 }
1260
1261 // TODO: dispatch into NMS to push rules towards kernel module
1262 // TODO: notify UID when it has requested targeted updates
1263 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001264
1265 @Override
1266 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1267 // only someone like NPMS should only be calling us
1268 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1269
1270 if (LOGD_RULES) {
1271 Slog.d(TAG,
1272 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1273 }
1274
1275 synchronized (mRulesLock) {
1276 mMeteredIfaces.clear();
1277 for (String iface : meteredIfaces) {
1278 mMeteredIfaces.add(iface);
1279 }
1280 }
1281 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001282 };
1283
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001284 /**
1285 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1286 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001287 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001288 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001289 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001290
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001291 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001292 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001293 }
1294
1295 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001296 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1297 if (DBG) {
1298 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001299 }
Wink Savillee7982682010-12-07 10:31:02 -08001300 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001301 }
1302 }
1303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001305 mContext.enforceCallingOrSelfPermission(
1306 android.Manifest.permission.ACCESS_NETWORK_STATE,
1307 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309
1310 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001311 mContext.enforceCallingOrSelfPermission(
1312 android.Manifest.permission.CHANGE_NETWORK_STATE,
1313 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001316 // TODO Make this a special check when it goes public
1317 private void enforceTetherChangePermission() {
1318 mContext.enforceCallingOrSelfPermission(
1319 android.Manifest.permission.CHANGE_NETWORK_STATE,
1320 "ConnectivityService");
1321 }
1322
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001323 private void enforceTetherAccessPermission() {
1324 mContext.enforceCallingOrSelfPermission(
1325 android.Manifest.permission.ACCESS_NETWORK_STATE,
1326 "ConnectivityService");
1327 }
1328
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001329 private void enforceConnectivityInternalPermission() {
1330 mContext.enforceCallingOrSelfPermission(
1331 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1332 "ConnectivityService");
1333 }
1334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001336 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1337 * network, we ignore it. If it is for the active network, we send out a
1338 * broadcast. But first, we check whether it might be possible to connect
1339 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 * @param info the {@code NetworkInfo} for the network
1341 */
1342 private void handleDisconnect(NetworkInfo info) {
1343
Robert Greenwalt42acef32009-08-12 16:08:25 -07001344 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345
Robert Greenwalt42acef32009-08-12 16:08:25 -07001346 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 /*
1348 * If the disconnected network is not the active one, then don't report
1349 * this as a loss of connectivity. What probably happened is that we're
1350 * getting the disconnect for a network that we explicitly disabled
1351 * in accordance with network preference policies.
1352 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001353 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001354 List pids = mNetRequestersPids[prevNetType];
1355 for (int i = 0; i<pids.size(); i++) {
1356 Integer pid = (Integer)pids.get(i);
1357 // will remove them because the net's no longer connected
1358 // need to do this now as only now do we know the pids and
1359 // can properly null things that are no longer referenced.
1360 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1365 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1366 if (info.isFailover()) {
1367 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1368 info.setFailover(false);
1369 }
1370 if (info.getReason() != null) {
1371 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1372 }
1373 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001374 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1375 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001377
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001378 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001379 tryFailover(prevNetType);
1380 if (mActiveDefaultNetwork != -1) {
1381 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001382 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1383 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001384 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001385 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1386 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001387 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001388 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001389
1390 // Reset interface if no other connections are using the same interface
1391 boolean doReset = true;
1392 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1393 if (linkProperties != null) {
1394 String oldIface = linkProperties.getInterfaceName();
1395 if (TextUtils.isEmpty(oldIface) == false) {
1396 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1397 if (networkStateTracker == null) continue;
1398 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1399 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1400 LinkProperties l = networkStateTracker.getLinkProperties();
1401 if (l == null) continue;
1402 if (oldIface.equals(l.getInterfaceName())) {
1403 doReset = false;
1404 break;
1405 }
1406 }
1407 }
1408 }
1409 }
1410
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001411 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001412 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001413
1414 sendStickyBroadcast(intent);
1415 /*
1416 * If the failover network is already connected, then immediately send
1417 * out a followup broadcast indicating successful failover
1418 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001419 if (mActiveDefaultNetwork != -1) {
1420 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001421 }
1422 }
1423
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001424 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001425 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001426 * If this is a default network, check if other defaults are available.
1427 * Try to reconnect on all available and let them hash it out when
1428 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001429 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001430 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001431 if (mActiveDefaultNetwork == prevNetType) {
1432 mActiveDefaultNetwork = -1;
1433 }
1434
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001435 // don't signal a reconnect for anything lower or equal priority than our
1436 // current connected default
1437 // TODO - don't filter by priority now - nice optimization but risky
1438// int currentPriority = -1;
1439// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001440// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001441// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001442 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001443 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001444 if (mNetConfigs[checkType] == null) continue;
1445 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001446
1447// Enabling the isAvailable() optimization caused mobile to not get
1448// selected if it was in the middle of error handling. Specifically
1449// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1450// would not be available and we wouldn't get connected to anything.
1451// So removing the isAvailable() optimization below for now. TODO: This
1452// optimization should work and we need to investigate why it doesn't work.
1453// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1454// complete before it is really complete.
1455// if (!mNetTrackers[checkType].isAvailable()) continue;
1456
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001457// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001458
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001459 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1460 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1461 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1462 checkInfo.setFailover(true);
1463 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001464 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001465 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
1469
1470 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001471 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1472 }
1473
1474 private void sendInetConditionBroadcast(NetworkInfo info) {
1475 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1476 }
1477
1478 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1479 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1481 if (info.isFailover()) {
1482 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1483 info.setFailover(false);
1484 }
1485 if (info.getReason() != null) {
1486 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1487 }
1488 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001489 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1490 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001492 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001493 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
1496 /**
1497 * Called when an attempt to fail over to another network has failed.
1498 * @param info the {@link NetworkInfo} for the failed network
1499 */
1500 private void handleConnectionFailure(NetworkInfo info) {
1501 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
Robert Greenwalt42acef32009-08-12 16:08:25 -07001503 String reason = info.getReason();
1504 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001505
Robert Greenwalt572172b2010-10-08 16:35:52 -07001506 String reasonText;
1507 if (reason == null) {
1508 reasonText = ".";
1509 } else {
1510 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001512 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001513
1514 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1515 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1516 if (getActiveNetworkInfo() == null) {
1517 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1518 }
1519 if (reason != null) {
1520 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1521 }
1522 if (extraInfo != null) {
1523 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1524 }
1525 if (info.isFailover()) {
1526 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1527 info.setFailover(false);
1528 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001529
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001530 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001531 tryFailover(info.getType());
1532 if (mActiveDefaultNetwork != -1) {
1533 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001534 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1535 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001536 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001537 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1538 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001539 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001540
Robert Greenwalt029be812010-09-20 18:01:43 -07001541 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001542 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001543 /*
1544 * If the failover network is already connected, then immediately send
1545 * out a followup broadcast indicating successful failover
1546 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001547 if (mActiveDefaultNetwork != -1) {
1548 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001549 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001550 }
1551
1552 private void sendStickyBroadcast(Intent intent) {
1553 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001554 if (!mSystemReady) {
1555 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001556 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001557 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1558 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001559 }
1560 }
1561
1562 void systemReady() {
1563 synchronized(this) {
1564 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001565 if (mInitialBroadcast != null) {
1566 mContext.sendStickyBroadcast(mInitialBroadcast);
1567 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001568 }
1569 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001570 // load the global proxy at startup
1571 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573
1574 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001575 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576
1577 // snapshot isFailover, because sendConnectedBroadcast() resets it
1578 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001579 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580
Robert Greenwalt42acef32009-08-12 16:08:25 -07001581 // if this is a default net and other default is running
1582 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001583 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001584 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1585 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001586 mNetConfigs[mActiveDefaultNetwork].priority >
1587 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001588 mNetworkPreference == mActiveDefaultNetwork) {
1589 // don't accept this one
Wink Savilleed9c02b2010-12-03 12:01:38 -08001590 if (DBG) {
1591 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001592 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001593 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001594 teardown(thisNet);
1595 return;
1596 } else {
1597 // tear down the other
1598 NetworkStateTracker otherNet =
1599 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001600 if (DBG) {
1601 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001602 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001603 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001604 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001605 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001606 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001607 return;
1608 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001609 }
1610 }
1611 synchronized (ConnectivityService.this) {
1612 // have a new default network, release the transition wakelock in a second
1613 // if it's held. The second pause is to allow apps to reconnect over the
1614 // new network
1615 if (mNetTransitionWakeLock.isHeld()) {
1616 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001617 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001618 mNetTransitionWakeLockSerialNumber, 0),
1619 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001620 }
1621 }
1622 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001623 // this will cause us to come up initially as unconnected and switching
1624 // to connected after our normal pause unless somebody reports us as reall
1625 // disconnected
1626 mDefaultInetConditionPublished = 0;
1627 mDefaultConnectionSequence++;
1628 mInetConditionChangeInFlight = false;
1629 // Don't do this - if we never sign in stay, grey
1630 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001633 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001634 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001635 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
1637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001639 * After a change in the connectivity state of a network. We're mainly
1640 * concerned with making sure that the list of DNS servers is set up
1641 * according to which networks are connected, and ensuring that the
1642 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001644 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001645 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001648 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001649 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001651 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001652
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001653 LinkProperties curLp = mCurrentLinkProperties[netType];
1654 LinkProperties newLp = null;
1655
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001656 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001657 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001658 if (VDBG) {
1659 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1660 " doReset=" + doReset + " resetMask=" + resetMask +
1661 "\n curLp=" + curLp +
1662 "\n newLp=" + newLp);
1663 }
1664
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001665 if (curLp != null) {
1666 if (curLp.isIdenticalInterfaceName(newLp)) {
1667 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1668 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1669 for (LinkAddress linkAddr : car.removed) {
1670 if (linkAddr.getAddress() instanceof Inet4Address) {
1671 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1672 }
1673 if (linkAddr.getAddress() instanceof Inet6Address) {
1674 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1675 }
Wink Savillee8222252011-07-13 13:44:13 -07001676 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001677 if (DBG) {
1678 log("handleConnectivityChange: addresses changed" +
1679 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1680 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001681 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001682 } else {
1683 if (DBG) {
1684 log("handleConnectivityChange: address are the same reset per doReset" +
1685 " linkProperty[" + netType + "]:" +
1686 " resetMask=" + resetMask);
1687 }
Wink Savillee8222252011-07-13 13:44:13 -07001688 }
1689 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001690 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1691 log("handleConnectivityChange: interface not not equivalent reset both" +
1692 " linkProperty[" + netType + "]:" +
1693 " resetMask=" + resetMask);
Wink Savillee8222252011-07-13 13:44:13 -07001694 }
Wink Savillee8222252011-07-13 13:44:13 -07001695 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001696 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001697 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001698 }
1699 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001700 if (VDBG) {
1701 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1702 " doReset=" + doReset + " resetMask=" + resetMask +
1703 "\n curLp=" + curLp +
1704 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001707 mCurrentLinkProperties[netType] = newLp;
1708 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001709
Wink Savillee8222252011-07-13 13:44:13 -07001710 if (doReset || resetMask != 0) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001711 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1712 if (linkProperties != null) {
1713 String iface = linkProperties.getInterfaceName();
1714 if (TextUtils.isEmpty(iface) == false) {
Wink Savillee8222252011-07-13 13:44:13 -07001715 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1716 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001717 }
1718 }
1719 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001720
1721 // TODO: Temporary notifying upstread change to Tethering.
1722 // @see bug/4455071
1723 /** Notify TetheringService if interface name has been changed. */
1724 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1725 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1726 if (isTetheringSupported()) {
1727 mTethering.handleTetherIfaceChange();
1728 }
1729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
1731
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001732 /**
1733 * Add and remove routes using the old properties (null if not previously connected),
1734 * new properties (null if becoming disconnected). May even be double null, which
1735 * is a noop.
1736 * Uses isLinkDefault to determine if default routes should be set or conversely if
1737 * host routes should be set to the dns servers
1738 */
1739 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1740 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001741 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1742 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001743 if (curLp != null) {
1744 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001745 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001746 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001747 } else if (newLp != null) {
1748 routeDiff.added = newLp.getRoutes();
1749 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001750 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001751
Robert Greenwaltad55d352011-07-22 11:55:33 -07001752 for (RouteInfo r : routeDiff.removed) {
1753 if (isLinkDefault || ! r.isDefaultRoute()) {
1754 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001755 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001756 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001757
Robert Greenwaltad55d352011-07-22 11:55:33 -07001758 for (RouteInfo r : routeDiff.added) {
1759 if (isLinkDefault || ! r.isDefaultRoute()) {
1760 addRoute(newLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001761 }
1762 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001763
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001764 if (!isLinkDefault) {
1765 // handle DNS routes
Robert Greenwaltad55d352011-07-22 11:55:33 -07001766 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1767 // no change in routes, check for change in dns themselves
1768 for (InetAddress oldDns : dnsDiff.removed) {
1769 removeRouteToAddress(curLp, oldDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001770 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001771 for (InetAddress newDns : dnsDiff.added) {
1772 addRouteToAddress(newLp, newDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001773 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001774 } else {
1775 // routes changed - remove all old dns entries and add new
1776 if (curLp != null) {
1777 for (InetAddress oldDns : curLp.getDnses()) {
1778 removeRouteToAddress(curLp, oldDns);
1779 }
1780 }
1781 if (newLp != null) {
1782 for (InetAddress newDns : newLp.getDnses()) {
1783 addRouteToAddress(newLp, newDns);
1784 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001785 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001786 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001787 }
1788 }
1789
1790
Irfan Sheriffd649c122010-06-09 15:39:36 -07001791 /**
1792 * Reads the network specific TCP buffer sizes from SystemProperties
1793 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1794 * wide use
1795 */
1796 public void updateNetworkSettings(NetworkStateTracker nt) {
1797 String key = nt.getTcpBufferSizesPropName();
1798 String bufferSizes = SystemProperties.get(key);
1799
1800 if (bufferSizes.length() == 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001801 loge(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001802
1803 // Setting to default values so we won't be stuck to previous values
1804 key = "net.tcp.buffersize.default";
1805 bufferSizes = SystemProperties.get(key);
1806 }
1807
1808 // Set values in kernel
1809 if (bufferSizes.length() != 0) {
1810 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001811 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001812 + "] which comes from [" + key + "]");
1813 }
1814 setBufferSize(bufferSizes);
1815 }
1816 }
1817
1818 /**
1819 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1820 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1821 *
1822 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1823 * writeMin, writeInitial, writeMax"
1824 */
1825 private void setBufferSize(String bufferSizes) {
1826 try {
1827 String[] values = bufferSizes.split(",");
1828
1829 if (values.length == 6) {
1830 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001831 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1832 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1833 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1834 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1835 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1836 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001837 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001838 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001839 }
1840 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001841 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001842 }
1843 }
1844
Robert Greenwalt42acef32009-08-12 16:08:25 -07001845 /**
1846 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1847 * on the highest priority active net which this process requested.
1848 * If there aren't any, clear it out
1849 */
1850 private void reassessPidDns(int myPid, boolean doBump)
1851 {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001852 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001853 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001854 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001855 continue;
1856 }
1857 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001858 if (nt.getNetworkInfo().isConnected() &&
1859 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001860 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001861 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001862 List pids = mNetRequestersPids[i];
1863 for (int j=0; j<pids.size(); j++) {
1864 Integer pid = (Integer)pids.get(j);
1865 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001866 Collection<InetAddress> dnses = p.getDnses();
1867 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001868 if (doBump) {
1869 bumpDns();
1870 }
1871 return;
1872 }
1873 }
1874 }
1875 }
1876 // nothing found - delete
1877 for (int i = 1; ; i++) {
1878 String prop = "net.dns" + i + "." + myPid;
1879 if (SystemProperties.get(prop).length() == 0) {
1880 if (doBump) {
1881 bumpDns();
1882 }
1883 return;
1884 }
1885 SystemProperties.set(prop, "");
1886 }
1887 }
1888
Robert Greenwalt10398722010-12-17 15:20:36 -08001889 // return true if results in a change
1890 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001892 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001893 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001894 String dnsString = dns.getHostAddress();
1895 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1896 changed = true;
1897 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1898 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001899 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001900 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001901 }
1902
1903 private void bumpDns() {
1904 /*
1905 * Bump the property that tells the name resolver library to reread
1906 * the DNS server list from the properties.
1907 */
1908 String propVal = SystemProperties.get("net.dnschange");
1909 int n = 0;
1910 if (propVal.length() != 0) {
1911 try {
1912 n = Integer.parseInt(propVal);
1913 } catch (NumberFormatException e) {}
1914 }
1915 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001916 /*
1917 * Tell the VMs to toss their DNS caches
1918 */
1919 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1920 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001921 /*
1922 * Connectivity events can happen before boot has completed ...
1923 */
1924 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001925 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001926 }
1927
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001928 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001929 private boolean updateDns(String network, String iface,
1930 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001931 boolean changed = false;
1932 int last = 0;
1933 if (dnses.size() == 0 && mDefaultDns != null) {
1934 ++last;
1935 String value = mDefaultDns.getHostAddress();
1936 if (!value.equals(SystemProperties.get("net.dns1"))) {
1937 if (DBG) {
1938 log("no dns provided for " + network + " - using " + value);
1939 }
1940 changed = true;
1941 SystemProperties.set("net.dns1", value);
1942 }
1943 } else {
1944 for (InetAddress dns : dnses) {
1945 ++last;
1946 String key = "net.dns" + last;
1947 String value = dns.getHostAddress();
1948 if (!changed && value.equals(SystemProperties.get(key))) {
1949 continue;
1950 }
1951 if (DBG) {
1952 log("adding dns " + value + " for " + network);
1953 }
1954 changed = true;
1955 SystemProperties.set(key, value);
1956 }
1957 }
1958 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
1959 String key = "net.dns" + i;
1960 if (DBG) log("erasing " + key);
1961 changed = true;
1962 SystemProperties.set(key, "");
1963 }
1964 mNumDnsEntries = last;
1965
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001966 if (changed) {
1967 try {
1968 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
1969 mNetd.setDefaultInterfaceForDns(iface);
1970 } catch (Exception e) {
1971 Slog.e(TAG, "exception setting default dns interface: " + e);
1972 }
1973 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001974 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
1975 SystemProperties.set("net.dns.search", domains);
1976 changed = true;
1977 }
1978 return changed;
1979 }
1980
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001981 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001982 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001983 NetworkStateTracker nt = mNetTrackers[netType];
1984 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001985 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001986 if (p == null) return;
1987 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08001988 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001989 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001990 String network = nt.getNetworkInfo().getTypeName();
1991 synchronized (mDnsLock) {
1992 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001993 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001994 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001995 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001996 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001997 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07001998 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001999 NetworkUtils.makeStrings(dnses));
2000 } catch (Exception e) {
2001 Slog.e(TAG, "exception setting dns servers: " + e);
2002 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002003 // set per-pid dns for attached secondary nets
2004 List pids = mNetRequestersPids[netType];
2005 for (int y=0; y< pids.size(); y++) {
2006 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002007 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002010 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002012 }
2013
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002014 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002015 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2016 NETWORK_RESTORE_DELAY_PROP_NAME);
2017 if(restoreDefaultNetworkDelayStr != null &&
2018 restoreDefaultNetworkDelayStr.length() != 0) {
2019 try {
2020 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2021 } catch (NumberFormatException e) {
2022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002024 // if the system property isn't set, use the value for the apn type
2025 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2026
2027 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2028 (mNetConfigs[networkType] != null)) {
2029 ret = mNetConfigs[networkType].restoreTime;
2030 }
2031 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
2034 @Override
2035 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002036 if (mContext.checkCallingOrSelfPermission(
2037 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002039 pw.println("Permission Denial: can't dump ConnectivityService " +
2040 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2041 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 return;
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 pw.println();
2045 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002046 if (nst != null) {
2047 if (nst.getNetworkInfo().isConnected()) {
2048 pw.println("Active network: " + nst.getNetworkInfo().
2049 getTypeName());
2050 }
2051 pw.println(nst.getNetworkInfo());
2052 pw.println(nst);
2053 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002056
2057 pw.println("Network Requester Pids:");
2058 for (int net : mPriorityList) {
2059 String pidString = net + ": ";
2060 for (Object pid : mNetRequestersPids[net]) {
2061 pidString = pidString + pid.toString() + ", ";
2062 }
2063 pw.println(pidString);
2064 }
2065 pw.println();
2066
2067 pw.println("FeatureUsers:");
2068 for (Object requester : mFeatureUsers) {
2069 pw.println(requester.toString());
2070 }
2071 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002072
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002073 synchronized (this) {
2074 pw.println("NetworkTranstionWakeLock is currently " +
2075 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2076 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2077 }
2078 pw.println();
2079
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002080 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002081
2082 if (mInetLog != null) {
2083 pw.println();
2084 pw.println("Inet condition reports:");
2085 for(int i = 0; i < mInetLog.size(); i++) {
2086 pw.println(mInetLog.get(i));
2087 }
2088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
Robert Greenwalt42acef32009-08-12 16:08:25 -07002091 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002093 public MyHandler(Looper looper) {
2094 super(looper);
2095 }
2096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 @Override
2098 public void handleMessage(Message msg) {
2099 NetworkInfo info;
2100 switch (msg.what) {
2101 case NetworkStateTracker.EVENT_STATE_CHANGED:
2102 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002103 int type = info.getType();
2104 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002105
Wink Savilleed9c02b2010-12-03 12:01:38 -08002106 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002107 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002108 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109
2110 // Connectivity state changed:
2111 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002112 // [12-9] Network subtype (for mobile network, as defined
2113 // by TelephonyManager)
2114 // [8-3] Detailed state ordinal (as defined by
2115 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 // [2-0] Network type (as defined by ConnectivityManager)
2117 int eventLogParam = (info.getType() & 0x7) |
2118 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2119 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002120 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002121 eventLogParam);
2122
2123 if (info.getDetailedState() ==
2124 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002126 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002128 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002130 // the logic here is, handle SUSPENDED the same as
2131 // DISCONNECTED. The only difference being we are
2132 // broadcasting an intent with NetworkInfo that's
2133 // suspended. This allows the applications an
2134 // opportunity to handle DISCONNECTED and SUSPENDED
2135 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002137 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 handleConnect(info);
2139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002142 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002143 // TODO: Temporary allowing network configuration
2144 // change not resetting sockets.
2145 // @see bug/4455071
2146 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002148 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002149 String causedBy = null;
2150 synchronized (ConnectivityService.this) {
2151 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2152 mNetTransitionWakeLock.isHeld()) {
2153 mNetTransitionWakeLock.release();
2154 causedBy = mNetTransitionWakeLockCausedBy;
2155 }
2156 }
2157 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002158 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002159 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002160 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002161 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002162 FeatureUser u = (FeatureUser)msg.obj;
2163 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002164 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002165 case EVENT_INET_CONDITION_CHANGE:
2166 {
2167 int netType = msg.arg1;
2168 int condition = msg.arg2;
2169 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002170 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002171 }
2172 case EVENT_INET_CONDITION_HOLD_END:
2173 {
2174 int netType = msg.arg1;
2175 int sequence = msg.arg2;
2176 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002177 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002178 }
2179 case EVENT_SET_NETWORK_PREFERENCE:
2180 {
2181 int preference = msg.arg1;
2182 handleSetNetworkPreference(preference);
2183 break;
2184 }
2185 case EVENT_SET_BACKGROUND_DATA:
2186 {
2187 boolean enabled = (msg.arg1 == ENABLED);
2188 handleSetBackgroundData(enabled);
2189 break;
2190 }
2191 case EVENT_SET_MOBILE_DATA:
2192 {
2193 boolean enabled = (msg.arg1 == ENABLED);
2194 handleSetMobileData(enabled);
2195 break;
2196 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002197 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2198 {
2199 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002200 break;
2201 }
2202 case EVENT_SET_DEPENDENCY_MET:
2203 {
2204 boolean met = (msg.arg1 == ENABLED);
2205 handleSetDependencyMet(msg.arg2, met);
2206 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002207 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002208 case EVENT_RESTORE_DNS:
2209 {
2210 if (mActiveDefaultNetwork != -1) {
2211 handleDnsConfigurationChange(mActiveDefaultNetwork);
2212 }
2213 break;
2214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 }
2216 }
2217 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002218
2219 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002220 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002221 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002222
2223 if (isTetheringSupported()) {
2224 return mTethering.tether(iface);
2225 } else {
2226 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2227 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002228 }
2229
2230 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002231 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002232 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002233
2234 if (isTetheringSupported()) {
2235 return mTethering.untether(iface);
2236 } else {
2237 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2238 }
2239 }
2240
2241 // javadoc from interface
2242 public int getLastTetherError(String iface) {
2243 enforceTetherAccessPermission();
2244
2245 if (isTetheringSupported()) {
2246 return mTethering.getLastTetherError(iface);
2247 } else {
2248 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2249 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002250 }
2251
2252 // TODO - proper iface API for selection by property, inspection, etc
2253 public String[] getTetherableUsbRegexs() {
2254 enforceTetherAccessPermission();
2255 if (isTetheringSupported()) {
2256 return mTethering.getTetherableUsbRegexs();
2257 } else {
2258 return new String[0];
2259 }
2260 }
2261
2262 public String[] getTetherableWifiRegexs() {
2263 enforceTetherAccessPermission();
2264 if (isTetheringSupported()) {
2265 return mTethering.getTetherableWifiRegexs();
2266 } else {
2267 return new String[0];
2268 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002269 }
2270
Danica Chang6fdd0c62010-08-11 14:54:43 -07002271 public String[] getTetherableBluetoothRegexs() {
2272 enforceTetherAccessPermission();
2273 if (isTetheringSupported()) {
2274 return mTethering.getTetherableBluetoothRegexs();
2275 } else {
2276 return new String[0];
2277 }
2278 }
2279
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002280 public int setUsbTethering(boolean enable) {
2281 enforceTetherAccessPermission();
2282 if (isTetheringSupported()) {
2283 return mTethering.setUsbTethering(enable);
2284 } else {
2285 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2286 }
2287 }
2288
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002289 // TODO - move iface listing, queries, etc to new module
2290 // javadoc from interface
2291 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002292 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002293 return mTethering.getTetherableIfaces();
2294 }
2295
2296 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002297 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002298 return mTethering.getTetheredIfaces();
2299 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002300
Robert Greenwalt5a735062010-03-02 17:25:02 -08002301 public String[] getTetheringErroredIfaces() {
2302 enforceTetherAccessPermission();
2303 return mTethering.getErroredIfaces();
2304 }
2305
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002306 // if ro.tether.denied = true we default to no tethering
2307 // gservices could set the secure setting to 1 though to enable it on a build where it
2308 // had previously been turned off.
2309 public boolean isTetheringSupported() {
2310 enforceTetherAccessPermission();
2311 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002312 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2313 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2314 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002315 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002316
2317 // An API NetworkStateTrackers can call when they lose their network.
2318 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2319 // whichever happens first. The timer is started by the first caller and not
2320 // restarted by subsequent callers.
2321 public void requestNetworkTransitionWakelock(String forWhom) {
2322 enforceConnectivityInternalPermission();
2323 synchronized (this) {
2324 if (mNetTransitionWakeLock.isHeld()) return;
2325 mNetTransitionWakeLockSerialNumber++;
2326 mNetTransitionWakeLock.acquire();
2327 mNetTransitionWakeLockCausedBy = forWhom;
2328 }
2329 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002330 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002331 mNetTransitionWakeLockSerialNumber, 0),
2332 mNetTransitionWakeLockTimeout);
2333 return;
2334 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002335
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002336 // 100 percent is full good, 0 is full bad.
2337 public void reportInetCondition(int networkType, int percentage) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002338 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002339 mContext.enforceCallingOrSelfPermission(
2340 android.Manifest.permission.STATUS_BAR,
2341 "ConnectivityService");
2342
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002343 if (DBG) {
2344 int pid = getCallingPid();
2345 int uid = getCallingUid();
2346 String s = pid + "(" + uid + ") reports inet is " +
2347 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2348 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2349 mInetLog.add(s);
2350 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2351 mInetLog.remove(0);
2352 }
2353 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002354 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002355 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2356 }
2357
2358 private void handleInetConditionChange(int netType, int condition) {
2359 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002360 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002361 netType + ", condition=" + condition +
2362 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2363 }
2364 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002365 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002366 return;
2367 }
2368 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002369 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002370 return;
2371 }
2372 mDefaultInetCondition = condition;
2373 int delay;
2374 if (mInetConditionChangeInFlight == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002375 if (DBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002376 // setup a new hold to debounce this
2377 if (mDefaultInetCondition > 50) {
2378 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2379 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2380 } else {
2381 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2382 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2383 }
2384 mInetConditionChangeInFlight = true;
2385 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2386 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2387 } else {
2388 // we've set the new condition, when this hold ends that will get
2389 // picked up
Wink Savilleed9c02b2010-12-03 12:01:38 -08002390 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002391 }
2392 }
2393
2394 private void handleInetConditionHoldEnd(int netType, int sequence) {
2395 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002396 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002397 ", condition =" + mDefaultInetCondition +
2398 ", published condition =" + mDefaultInetConditionPublished);
2399 }
2400 mInetConditionChangeInFlight = false;
2401
2402 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002403 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002404 return;
2405 }
2406 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002407 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002408 return;
2409 }
2410 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002411 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002412 return;
2413 }
2414 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2415 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002416 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002417 return;
2418 }
2419 mDefaultInetConditionPublished = mDefaultInetCondition;
2420 sendInetConditionBroadcast(networkInfo);
2421 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002422 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002423
2424 public synchronized ProxyProperties getProxy() {
2425 if (mGlobalProxy != null) return mGlobalProxy;
2426 if (mDefaultProxy != null) return mDefaultProxy;
2427 return null;
2428 }
2429
2430 public void setGlobalProxy(ProxyProperties proxyProperties) {
2431 enforceChangePermission();
2432 synchronized (mGlobalProxyLock) {
2433 if (proxyProperties == mGlobalProxy) return;
2434 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2435 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2436
2437 String host = "";
2438 int port = 0;
2439 String exclList = "";
2440 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2441 mGlobalProxy = new ProxyProperties(proxyProperties);
2442 host = mGlobalProxy.getHost();
2443 port = mGlobalProxy.getPort();
2444 exclList = mGlobalProxy.getExclusionList();
2445 } else {
2446 mGlobalProxy = null;
2447 }
2448 ContentResolver res = mContext.getContentResolver();
2449 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2450 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002451 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002452 exclList);
2453 }
2454
2455 if (mGlobalProxy == null) {
2456 proxyProperties = mDefaultProxy;
2457 }
2458 sendProxyBroadcast(proxyProperties);
2459 }
2460
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002461 private void loadGlobalProxy() {
2462 ContentResolver res = mContext.getContentResolver();
2463 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2464 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2465 String exclList = Settings.Secure.getString(res,
2466 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2467 if (!TextUtils.isEmpty(host)) {
2468 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2469 synchronized (mGlobalProxyLock) {
2470 mGlobalProxy = proxyProperties;
2471 }
2472 }
2473 }
2474
Robert Greenwalt434203a2010-10-11 16:00:27 -07002475 public ProxyProperties getGlobalProxy() {
2476 synchronized (mGlobalProxyLock) {
2477 return mGlobalProxy;
2478 }
2479 }
2480
2481 private void handleApplyDefaultProxy(int type) {
2482 // check if new default - push it out to all VM if so
2483 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2484 synchronized (this) {
2485 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2486 if (mDefaultProxy == proxy) return;
2487 if (!TextUtils.isEmpty(proxy.getHost())) {
2488 mDefaultProxy = proxy;
2489 } else {
2490 mDefaultProxy = null;
2491 }
2492 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002493 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002494 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2495 if (mGlobalProxy != null) return;
2496 sendProxyBroadcast(proxy);
2497 }
2498
2499 private void handleDeprecatedGlobalHttpProxy() {
2500 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2501 Settings.Secure.HTTP_PROXY);
2502 if (!TextUtils.isEmpty(proxy)) {
2503 String data[] = proxy.split(":");
2504 String proxyHost = data[0];
2505 int proxyPort = 8080;
2506 if (data.length > 1) {
2507 try {
2508 proxyPort = Integer.parseInt(data[1]);
2509 } catch (NumberFormatException e) {
2510 return;
2511 }
2512 }
2513 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2514 setGlobalProxy(p);
2515 }
2516 }
2517
2518 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002519 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002520 log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002521 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002522 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2523 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002524 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002525 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002526 }
2527
2528 private static class SettingsObserver extends ContentObserver {
2529 private int mWhat;
2530 private Handler mHandler;
2531 SettingsObserver(Handler handler, int what) {
2532 super(handler);
2533 mHandler = handler;
2534 mWhat = what;
2535 }
2536
2537 void observe(Context context) {
2538 ContentResolver resolver = context.getContentResolver();
2539 resolver.registerContentObserver(Settings.Secure.getUriFor(
2540 Settings.Secure.HTTP_PROXY), false, this);
2541 }
2542
2543 @Override
2544 public void onChange(boolean selfChange) {
2545 mHandler.obtainMessage(mWhat).sendToTarget();
2546 }
2547 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002548
2549 private void log(String s) {
2550 Slog.d(TAG, s);
2551 }
2552
2553 private void loge(String s) {
2554 Slog.e(TAG, s);
2555 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002556
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002557 int convertFeatureToNetworkType(String feature){
2558 int networkType = -1;
2559 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2560 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2561 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2562 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2563 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2564 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2565 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2566 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2567 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2568 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2569 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2570 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2571 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2572 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2573 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2574 }
2575 return networkType;
2576 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002577
2578 private static <T> T checkNotNull(T value, String message) {
2579 if (value == null) {
2580 throw new NullPointerException(message);
2581 }
2582 return value;
2583 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002584
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002585 /**
2586 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002587 * VpnBuilder and not available in ConnectivityManager. Permissions
2588 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002589 * @hide
2590 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002591 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002592 public boolean protectVpn(ParcelFileDescriptor socket) {
2593 try {
2594 int type = mActiveDefaultNetwork;
2595 if (ConnectivityManager.isNetworkTypeValid(type)) {
2596 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2597 return true;
2598 }
2599 } catch (Exception e) {
2600 // ignore
2601 } finally {
2602 try {
2603 socket.close();
2604 } catch (Exception e) {
2605 // ignore
2606 }
2607 }
2608 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002609 }
2610
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002611 /**
2612 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002613 * and not available in ConnectivityManager. Permissions are checked
2614 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002615 * @hide
2616 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002617 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002618 public boolean prepareVpn(String oldPackage, String newPackage) {
2619 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002620 }
2621
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002622 /**
2623 * Configure a TUN interface and return its file descriptor. Parameters
2624 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002625 * and not available in ConnectivityManager. Permissions are checked in
2626 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002627 * @hide
2628 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002629 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002630 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002631 return mVpn.establish(config);
2632 }
2633
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002634 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002635 * Start legacy VPN and return an intent to VpnDialogs. This method is
2636 * used by VpnSettings and not available in ConnectivityManager.
2637 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002638 * @hide
2639 */
2640 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002641 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2642 mVpn.startLegacyVpn(config, racoon, mtpd);
2643 }
2644
2645 /**
2646 * Return the information of the ongoing legacy VPN. This method is used
2647 * by VpnSettings and not available in ConnectivityManager. Permissions
2648 * are checked in Vpn class.
2649 * @hide
2650 */
2651 @Override
2652 public LegacyVpnInfo getLegacyVpnInfo() {
2653 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002654 }
2655
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002656 /**
2657 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2658 * through NetworkStateTracker since it works differently. For example, it
2659 * needs to override DNS servers but never takes the default routes. It
2660 * relies on another data network, and it could keep existing connections
2661 * alive after reconnecting, switching between networks, or even resuming
2662 * from deep sleep. Calls from applications should be done synchronously
2663 * to avoid race conditions. As these are all hidden APIs, refactoring can
2664 * be done whenever a better abstraction is developed.
2665 */
2666 public class VpnCallback {
2667
2668 private VpnCallback() {
2669 }
2670
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002671 public void override(List<String> dnsServers, List<String> searchDomains) {
2672 if (dnsServers == null) {
2673 restore();
2674 return;
2675 }
2676
2677 // Convert DNS servers into addresses.
2678 List<InetAddress> addresses = new ArrayList<InetAddress>();
2679 for (String address : dnsServers) {
2680 // Double check the addresses and remove invalid ones.
2681 try {
2682 addresses.add(InetAddress.parseNumericAddress(address));
2683 } catch (Exception e) {
2684 // ignore
2685 }
2686 }
2687 if (addresses.isEmpty()) {
2688 restore();
2689 return;
2690 }
2691
2692 // Concatenate search domains into a string.
2693 StringBuilder buffer = new StringBuilder();
2694 if (searchDomains != null) {
2695 for (String domain : searchDomains) {
2696 buffer.append(domain).append(' ');
2697 }
2698 }
2699 String domains = buffer.toString().trim();
2700
2701 // Apply DNS changes.
2702 boolean changed = false;
2703 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002704 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002705 mDnsOverridden = true;
2706 }
2707 if (changed) {
2708 bumpDns();
2709 }
2710
2711 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002712 }
2713
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002714 public void restore() {
2715 synchronized (mDnsLock) {
2716 if (!mDnsOverridden) {
2717 return;
2718 }
2719 mDnsOverridden = false;
2720 }
2721 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002722 }
2723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724}