blob: bf9e0149680d5cbcabd088aabb83c4492a0c6959 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070023
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Wink Savillec9822c52011-07-14 12:23:28 -070036import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080037import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070038import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070040import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070042import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070043import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070044import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070046import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.net.Proxy;
48import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070049import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.wifi.WifiStateTracker;
51import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040052import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070054import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070055import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070056import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Looper;
58import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070059import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070060import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070061import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.ServiceManager;
63import android.os.SystemProperties;
64import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070065import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070068import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Chia-chi Yeh2e467642011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070072import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080073import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074import com.android.server.connectivity.Vpn;
75
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070076import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070077import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070080import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -070082import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070083import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070084import java.net.InetAddress;
85import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070087import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070088import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070089import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070090import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070091import java.util.List;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94/**
95 * @hide
96 */
97public class ConnectivityService extends IConnectivityManager.Stub {
98
Robert Greenwaltba175a52010-10-05 19:12:26 -070099 private static final boolean DBG = true;
Wink Savillee8222252011-07-13 13:44:13 -0700100 private static final boolean VDBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final String TAG = "ConnectivityService";
102
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103 private static final boolean LOGD_RULES = false;
104
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105 // how long to wait before switching back to a radio's default network
106 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
107 // system property that can override the above value
108 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
109 "android.telephony.apn-restore";
110
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700111 // used in recursive route setting to add gateways for the host for which
112 // a host route was requested.
113 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
114
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800115 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800116 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800117
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700118 private Vpn mVpn;
119
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
121 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122 /** Currently active network rules by UID. */
123 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700124 /** Set of ifaces that are costly. */
125 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 /**
128 * Sometimes we want to refer to the individual network state
129 * trackers separately, and sometimes we just want to treat them
130 * abstractly.
131 */
132 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700133
134 /**
Wink Savillee8222252011-07-13 13:44:13 -0700135 * The link properties that define the current links
136 */
137 private LinkProperties mCurrentLinkProperties[];
138
139 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700140 * A per Net list of the PID's that requested access to the net
141 * used both as a refcount and for per-PID DNS selection
142 */
143 private List mNetRequestersPids[];
144
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145 // priority order of the nettrackers
146 // (excluding dynamically set mNetworkPreference)
147 // TODO - move mNetworkTypePreference into this
148 private int[] mPriorityList;
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private Context mContext;
151 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700153 // 0 is full bad, 100 is full good
154 private int mDefaultInetCondition = 0;
155 private int mDefaultInetConditionPublished = 0;
156 private boolean mInetConditionChangeInFlight = false;
157 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700159 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700161 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700164 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800166 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
167
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700168 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700169 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700170
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700171 private static final int ENABLED = 1;
172 private static final int DISABLED = 0;
173
174 // Share the event space with NetworkStateTracker (which can't see this
175 // internal class but sends us events). If you change these, change
176 // NetworkStateTracker.java too.
177 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
178 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
179
180 /**
181 * used internally as a delayed event to make us switch back to the
182 * default network
183 */
184 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
185 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
186
187 /**
188 * used internally to change our mobile data enabled flag
189 */
190 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
191 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
192
193 /**
194 * used internally to change our network preference setting
195 * arg1 = networkType to prefer
196 */
197 private static final int EVENT_SET_NETWORK_PREFERENCE =
198 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
199
200 /**
201 * used internally to synchronize inet condition reports
202 * arg1 = networkType
203 * arg2 = condition (0 bad, 100 good)
204 */
205 private static final int EVENT_INET_CONDITION_CHANGE =
206 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
207
208 /**
209 * used internally to mark the end of inet condition hold periods
210 * arg1 = networkType
211 */
212 private static final int EVENT_INET_CONDITION_HOLD_END =
213 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
214
215 /**
216 * used internally to set the background data preference
217 * arg1 = TRUE for enabled, FALSE for disabled
218 */
219 private static final int EVENT_SET_BACKGROUND_DATA =
220 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
221
222 /**
223 * used internally to set enable/disable cellular data
224 * arg1 = ENBALED or DISABLED
225 */
226 private static final int EVENT_SET_MOBILE_DATA =
227 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
228
Robert Greenwaltf3331232010-09-24 14:32:21 -0700229 /**
230 * used internally to clear a wakelock when transitioning
231 * from one net to another
232 */
233 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
234 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
235
Robert Greenwalt434203a2010-10-11 16:00:27 -0700236 /**
237 * used internally to reload global proxy settings
238 */
239 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
240 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
241
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700242 /**
243 * used internally to set external dependency met/unmet
244 * arg1 = ENABLED (met) or DISABLED (unmet)
245 * arg2 = NetworkType
246 */
247 private static final int EVENT_SET_DEPENDENCY_MET =
248 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
249
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700250 /**
251 * used internally to restore DNS properties back to the
252 * default network
253 */
254 private static final int EVENT_RESTORE_DNS =
255 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
256
Robert Greenwalt42acef32009-08-12 16:08:25 -0700257 private Handler mHandler;
258
259 // list of DeathRecipients used to make sure features are turned off when
260 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500261 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700262
Mike Lockwood0f79b542009-08-14 14:18:49 -0400263 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800264 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400265
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700266 private PowerManager.WakeLock mNetTransitionWakeLock;
267 private String mNetTransitionWakeLockCausedBy = "";
268 private int mNetTransitionWakeLockSerialNumber;
269 private int mNetTransitionWakeLockTimeout;
270
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700271 private InetAddress mDefaultDns;
272
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700273 // this collection is used to refcount the added routes - if there are none left
274 // it's time to remove the route from the route table
275 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
276
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700277 // used in DBG mode to track inet condition reports
278 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
279 private ArrayList mInetLog;
280
Robert Greenwalt434203a2010-10-11 16:00:27 -0700281 // track the current default http proxy - tell the world if we get a new one (real change)
282 private ProxyProperties mDefaultProxy = null;
283 // track the global proxy.
284 private ProxyProperties mGlobalProxy = null;
285 private final Object mGlobalProxyLock = new Object();
286
287 private SettingsObserver mSettingsObserver;
288
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700289 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700290 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700291
Robert Greenwalt511288a2009-12-07 11:33:18 -0800292 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700293 public int mSimultaneity;
294 public int mType;
295 public RadioAttributes(String init) {
296 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700297 mType = Integer.parseInt(fragments[0]);
298 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700299 }
300 }
301 RadioAttributes[] mRadioAttributes;
302
Robert Greenwalt50393202011-06-21 17:26:14 -0700303 // the set of network types that can only be enabled by system/sig apps
304 List mProtectedNetworks;
305
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700306 public ConnectivityService(
307 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800308 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800309
Wink Savillebb08caf2010-09-02 19:23:52 -0700310 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
311 handlerThread.start();
312 mHandler = new MyHandler(handlerThread.getLooper());
313
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800314 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
315 Settings.Secure.BACKGROUND_DATA, 1) == 1);
316
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800317 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800318 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
319 String id = Settings.Secure.getString(context.getContentResolver(),
320 Settings.Secure.ANDROID_ID);
321 if (id != null && id.length() > 0) {
322 String name = new String("android_").concat(id);
323 SystemProperties.set("net.hostname", name);
324 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800325 }
326
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700327 // read our default dns server ip
328 String dns = Settings.Secure.getString(context.getContentResolver(),
329 Settings.Secure.DEFAULT_DNS_SERVER);
330 if (dns == null || dns.length() == 0) {
331 dns = context.getResources().getString(
332 com.android.internal.R.string.config_default_dns_server);
333 }
334 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800335 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
336 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800337 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700338 }
339
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700340 mContext = checkNotNull(context, "missing Context");
341 mNetd = checkNotNull(netd, "missing INetworkManagementService");
342 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700343
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700344 try {
345 mPolicyManager.registerListener(mPolicyListener);
346 } catch (RemoteException e) {
347 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700348 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700349 }
350
351 final PowerManager powerManager = (PowerManager) context.getSystemService(
352 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700353 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
354 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
355 com.android.internal.R.integer.config_networkTransitionTimeout);
356
Robert Greenwalt42acef32009-08-12 16:08:25 -0700357 mNetTrackers = new NetworkStateTracker[
358 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700359 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700362
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700363 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700364 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700365
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700367 String[] raStrings = context.getResources().getStringArray(
368 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700369 for (String raString : raStrings) {
370 RadioAttributes r = new RadioAttributes(raString);
371 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800372 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700373 continue;
374 }
375 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800376 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700377 r.mType);
378 continue;
379 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700380 mRadioAttributes[r.mType] = r;
381 }
382
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700383 String[] naStrings = context.getResources().getStringArray(
384 com.android.internal.R.array.networkAttributes);
385 for (String naString : naStrings) {
386 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700387 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700388 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700390 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700391 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700392 }
Wink Saville975c8482011-04-07 14:23:45 -0700393 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800394 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700395 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700396 continue;
397 }
Wink Saville975c8482011-04-07 14:23:45 -0700398 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800399 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700400 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700401 continue;
402 }
Wink Saville975c8482011-04-07 14:23:45 -0700403 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700404 mNetworksDefined++;
405 } catch(Exception e) {
406 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407 }
408 }
409
Robert Greenwalt50393202011-06-21 17:26:14 -0700410 mProtectedNetworks = new ArrayList<Integer>();
411 int[] protectedNetworks = context.getResources().getIntArray(
412 com.android.internal.R.array.config_protectedNetworks);
413 for (int p : protectedNetworks) {
414 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
415 mProtectedNetworks.add(p);
416 } else {
417 if (DBG) loge("Ignoring protectedNetwork " + p);
418 }
419 }
420
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700421 // high priority first
422 mPriorityList = new int[mNetworksDefined];
423 {
424 int insertionPoint = mNetworksDefined-1;
425 int currentLowest = 0;
426 int nextLowest = 0;
427 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700428 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700430 if (na.priority < currentLowest) continue;
431 if (na.priority > currentLowest) {
432 if (na.priority < nextLowest || nextLowest == 0) {
433 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700434 }
435 continue;
436 }
Wink Saville975c8482011-04-07 14:23:45 -0700437 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700438 }
439 currentLowest = nextLowest;
440 nextLowest = 0;
441 }
442 }
443
444 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
445 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700446 mNetRequestersPids[i] = new ArrayList();
447 }
448
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500449 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700450
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700451 mNumDnsEntries = 0;
452
453 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
454 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 /*
456 * Create the network state trackers for Wi-Fi and mobile
457 * data. Maybe this could be done with a factory class,
458 * but it's not clear that it's worth it, given that
459 * the number of different network types is not going
460 * to change very often.
461 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700462 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700463 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700464 case ConnectivityManager.TYPE_WIFI:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800465 if (DBG) log("Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700466 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700467 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700468 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700469 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700470 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700471 wst.startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700472 break;
473 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700474 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700475 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700476 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700477 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800478 case ConnectivityManager.TYPE_DUMMY:
479 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700480 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800481 mNetTrackers[netType].startMonitoring(context, mHandler);
482 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800483 case ConnectivityManager.TYPE_BLUETOOTH:
484 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Benoit Goby19970692010-12-22 14:29:40 -0800487 case ConnectivityManager.TYPE_ETHERNET:
488 mNetTrackers[netType] = EthernetDataTracker.getInstance();
489 mNetTrackers[netType].startMonitoring(context, mHandler);
490 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700491 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800492 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700493 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700494 continue;
495 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700496 mCurrentLinkProperties[netType] = null;
Robert Greenwaltc96e6cc2011-07-15 11:16:45 -0700497 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700498 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800499
Chia-chi Yehc9338302011-05-11 16:35:13 -0700500 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
501 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
502
503 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700504 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700505 mTethering.getTetherableWifiRegexs().length != 0 ||
506 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700507 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800508
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700509 mVpn = new Vpn(mContext, new VpnCallback());
510
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700511 try {
512 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700513 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700514 } catch (RemoteException e) {
515 loge("Error registering observer :" + e);
516 }
517
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700518 if (DBG) {
519 mInetLog = new ArrayList();
520 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700521
522 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
523 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800524
525 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 }
527
528 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700529 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 * @param preference the new preference
531 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700532 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700534
535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 }
537
538 public int getNetworkPreference() {
539 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700540 int preference;
541 synchronized(this) {
542 preference = mNetworkPreference;
543 }
544 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700547 private void handleSetNetworkPreference(int preference) {
548 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700549 mNetConfigs[preference] != null &&
550 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700551 if (mNetworkPreference != preference) {
552 final ContentResolver cr = mContext.getContentResolver();
553 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
554 synchronized(this) {
555 mNetworkPreference = preference;
556 }
557 enforcePreference();
558 }
559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 private int getPersistedNetworkPreference() {
563 final ContentResolver cr = mContext.getContentResolver();
564
565 final int networkPrefSetting = Settings.Secure
566 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
567 if (networkPrefSetting != -1) {
568 return networkPrefSetting;
569 }
570
571 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
572 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700575 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 * In this method, we only tear down a non-preferred network. Establishing
577 * a connection to the preferred network is taken care of when we handle
578 * the disconnect event from the non-preferred network
579 * (see {@link #handleDisconnect(NetworkInfo)}).
580 */
581 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700582 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 return;
584
Robert Greenwalt42acef32009-08-12 16:08:25 -0700585 if (!mNetTrackers[mNetworkPreference].isAvailable())
586 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
Robert Greenwalt42acef32009-08-12 16:08:25 -0700588 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700589 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700590 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700591 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800592 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700593 " in enforcePreference");
594 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700595 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597 }
598 }
599
600 private boolean teardown(NetworkStateTracker netTracker) {
601 if (netTracker.teardown()) {
602 netTracker.setTeardownRequested(true);
603 return true;
604 } else {
605 return false;
606 }
607 }
608
609 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700610 * Check if UID should be blocked from using the network represented by the
611 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700612 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700613 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
614 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700615
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700616 final boolean networkCostly;
617 final int uidRules;
618 synchronized (mRulesLock) {
619 networkCostly = mMeteredIfaces.contains(iface);
620 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700621 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700622
623 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
624 return true;
625 }
626
627 // no restrictive rules; network is visible
628 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700629 }
630
631 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700632 * Return a filtered {@link NetworkInfo}, potentially marked
633 * {@link DetailedState#BLOCKED} based on
634 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700635 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700636 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
637 NetworkInfo info = tracker.getNetworkInfo();
638 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700639 // network is blocked; clone and override state
640 info = new NetworkInfo(info);
641 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700642 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700643 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700644 }
645
646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 * Return NetworkInfo for the active (i.e., connected) network interface.
648 * It is assumed that at most one network is active at a time. If more
649 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700650 * @return the info for the active network, or {@code null} if none is
651 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700653 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700655 enforceAccessPermission();
656 final int uid = Binder.getCallingUid();
657 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 }
659
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 @Override
661 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
662 enforceConnectivityInternalPermission();
663 return getNetworkInfo(mActiveDefaultNetwork, uid);
664 }
665
666 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 public NetworkInfo getNetworkInfo(int networkType) {
668 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 final int uid = Binder.getCallingUid();
670 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 private NetworkInfo getNetworkInfo(int networkType, int uid) {
674 NetworkInfo info = null;
675 if (isNetworkTypeValid(networkType)) {
676 final NetworkStateTracker tracker = mNetTrackers[networkType];
677 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700678 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700679 }
680 }
681 return info;
682 }
683
684 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public NetworkInfo[] getAllNetworkInfo() {
686 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700687 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700688 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700689 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700690 for (NetworkStateTracker tracker : mNetTrackers) {
691 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700692 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700693 }
694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700696 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
698
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700699 /**
700 * Return LinkProperties for the active (i.e., connected) default
701 * network interface. It is assumed that at most one default network
702 * is active at a time. If more than one is active, it is indeterminate
703 * which will be returned.
704 * @return the ip properties for the active network, or {@code null} if
705 * none is active
706 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700707 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700708 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700709 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700710 }
711
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700712 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700713 public LinkProperties getLinkProperties(int networkType) {
714 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700715 if (isNetworkTypeValid(networkType)) {
716 final NetworkStateTracker tracker = mNetTrackers[networkType];
717 if (tracker != null) {
718 return tracker.getLinkProperties();
719 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700720 }
721 return null;
722 }
723
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700724 @Override
725 public NetworkState[] getAllNetworkState() {
726 enforceAccessPermission();
727 final int uid = Binder.getCallingUid();
728 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700729 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700730 for (NetworkStateTracker tracker : mNetTrackers) {
731 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700732 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700733 result.add(new NetworkState(
734 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
735 }
736 }
737 }
738 return result.toArray(new NetworkState[result.size()]);
739 }
740
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700741 private NetworkState getNetworkStateUnchecked(int networkType) {
742 if (isNetworkTypeValid(networkType)) {
743 final NetworkStateTracker tracker = mNetTrackers[networkType];
744 if (tracker != null) {
745 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
746 tracker.getLinkCapabilities());
747 }
748 }
749 return null;
750 }
751
752 @Override
753 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
754 enforceAccessPermission();
755 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
756 if (state != null) {
757 try {
758 return mPolicyManager.getNetworkQuotaInfo(state);
759 } catch (RemoteException e) {
760 }
761 }
762 return null;
763 }
764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 public boolean setRadios(boolean turnOn) {
766 boolean result = true;
767 enforceChangePermission();
768 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700769 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
771 return result;
772 }
773
774 public boolean setRadio(int netType, boolean turnOn) {
775 enforceChangePermission();
776 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
777 return false;
778 }
779 NetworkStateTracker tracker = mNetTrackers[netType];
780 return tracker != null && tracker.setRadio(turnOn);
781 }
782
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700783 /**
784 * Used to notice when the calling process dies so we can self-expire
785 *
786 * Also used to know if the process has cleaned up after itself when
787 * our auto-expire timer goes off. The timer has a link to an object.
788 *
789 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700790 private class FeatureUser implements IBinder.DeathRecipient {
791 int mNetworkType;
792 String mFeature;
793 IBinder mBinder;
794 int mPid;
795 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800796 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700797
798 FeatureUser(int type, String feature, IBinder binder) {
799 super();
800 mNetworkType = type;
801 mFeature = feature;
802 mBinder = binder;
803 mPid = getCallingPid();
804 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800805 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700806
Robert Greenwalt42acef32009-08-12 16:08:25 -0700807 try {
808 mBinder.linkToDeath(this, 0);
809 } catch (RemoteException e) {
810 binderDied();
811 }
812 }
813
814 void unlinkDeathRecipient() {
815 mBinder.unlinkToDeath(this, 0);
816 }
817
818 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800819 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800820 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
821 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700822 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700823 }
824
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700825 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700826 if (VDBG) {
827 log("ConnectivityService FeatureUser expire(" +
828 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
829 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
830 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700831 stopUsingNetworkFeature(this, false);
832 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800833
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500834 public boolean isSameUser(FeatureUser u) {
835 if (u == null) return false;
836
837 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
838 }
839
840 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
841 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
842 TextUtils.equals(mFeature, feature)) {
843 return true;
844 }
845 return false;
846 }
847
Robert Greenwaltb9285352009-12-21 18:24:07 -0800848 public String toString() {
849 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
850 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
851 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700852 }
853
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700854 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700855 public int startUsingNetworkFeature(int networkType, String feature,
856 IBinder binder) {
857 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800858 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700861 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700862 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700863 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700865
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700866 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700867
868 // TODO - move this into the MobileDataStateTracker
869 int usedNetworkType = networkType;
870 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800871 usedNetworkType = convertFeatureToNetworkType(feature);
872 if (usedNetworkType < 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700873 loge("Can't match any netTracker!");
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800874 usedNetworkType = networkType;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700875 }
876 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700877
878 if (mProtectedNetworks.contains(usedNetworkType)) {
879 enforceConnectivityInternalPermission();
880 }
881
Robert Greenwalt42acef32009-08-12 16:08:25 -0700882 NetworkStateTracker network = mNetTrackers[usedNetworkType];
883 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800884 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700885 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700886 NetworkStateTracker radio = mNetTrackers[networkType];
887 NetworkInfo ni = network.getNetworkInfo();
888
889 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800890 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800891 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
892 return Phone.APN_TYPE_NOT_AVAILABLE;
893 } else {
894 // else make the attempt anyway - probably giving REQUEST_STARTED below
895 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700896 }
897
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500898 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
899
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700900 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500901 boolean addToList = true;
902 if (restoreTimer < 0) {
903 // In case there is no timer is specified for the feature,
904 // make sure we don't add duplicate entry with the same request.
905 for (FeatureUser u : mFeatureUsers) {
906 if (u.isSameUser(f)) {
907 // Duplicate user is found. Do not add.
908 addToList = false;
909 break;
910 }
911 }
912 }
913
914 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700915 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
916 // this gets used for per-pid dns when connected
917 mNetRequestersPids[usedNetworkType].add(currentPid);
918 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700919 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700920
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700921 if (restoreTimer >= 0) {
922 mHandler.sendMessageDelayed(
923 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
924 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700925
Robert Greenwalta64bf832009-08-19 20:19:33 -0700926 if ((ni.isConnectedOrConnecting() == true) &&
927 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700928 if (ni.isConnected() == true) {
929 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -0700930 handleDnsConfigurationChange(usedNetworkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800931 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700932 return Phone.APN_ALREADY_ACTIVE;
933 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800934 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700935 return Phone.APN_REQUEST_STARTED;
936 }
937
938 // check if the radio in play can make another contact
939 // assume if cannot for now
940
Wink Savilleed9c02b2010-12-03 12:01:38 -0800941 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700942 network.reconnect();
943 return Phone.APN_REQUEST_STARTED;
944 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800945 // need to remember this unsupported request so we respond appropriately on stop
946 synchronized(this) {
947 mFeatureUsers.add(f);
948 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
949 // this gets used for per-pid dns when connected
950 mNetRequestersPids[usedNetworkType].add(currentPid);
951 }
952 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700953 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700954 }
955 }
956 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700959 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700961 enforceChangePermission();
962
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700963 int pid = getCallingPid();
964 int uid = getCallingUid();
965
966 FeatureUser u = null;
967 boolean found = false;
968
969 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500970 for (FeatureUser x : mFeatureUsers) {
971 if (x.isSameUser(pid, uid, networkType, feature)) {
972 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700973 found = true;
974 break;
975 }
976 }
977 }
978 if (found && u != null) {
979 // stop regardless of how many other time this proc had called start
980 return stopUsingNetworkFeature(u, true);
981 } else {
982 // none found!
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700983 if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700984 return 1;
985 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700986 }
987
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700988 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
989 int networkType = u.mNetworkType;
990 String feature = u.mFeature;
991 int pid = u.mPid;
992 int uid = u.mUid;
993
994 NetworkStateTracker tracker = null;
995 boolean callTeardown = false; // used to carry our decision outside of sync block
996
Robert Greenwalt42acef32009-08-12 16:08:25 -0700997 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800998 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700999 ": " + feature);
1000 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1003 return -1;
1004 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001005
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001006 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1007 // sync block
1008 synchronized(this) {
1009 // check if this process still has an outstanding start request
1010 if (!mFeatureUsers.contains(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001011 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001012 return 1;
1013 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001014 u.unlinkDeathRecipient();
1015 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1016 // If we care about duplicate requests, check for that here.
1017 //
1018 // This is done to support the extension of a request - the app
1019 // can request we start the network feature again and renew the
1020 // auto-shutoff delay. Normal "stop" calls from the app though
1021 // do not pay attention to duplicate requests - in effect the
1022 // API does not refcount and a single stop will counter multiple starts.
1023 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001024 for (FeatureUser x : mFeatureUsers) {
1025 if (x.isSameUser(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001026 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001027 return 1;
1028 }
1029 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001030 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001031
1032 // TODO - move to MobileDataStateTracker
1033 int usedNetworkType = networkType;
1034 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -08001035 usedNetworkType = convertFeatureToNetworkType(feature);
1036 if (usedNetworkType < 0) {
1037 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001038 }
1039 }
1040 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001041 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001042 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001043 return -1;
1044 }
1045 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001046 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001047 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001048 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001049 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001050 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001051 "others still using it");
1052 return 1;
1053 }
1054 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001055 } else {
1056 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001057 }
1058 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001059 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001060 if (callTeardown) {
1061 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001062 return 1;
1063 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001064 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067
1068 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001069 * @deprecated use requestRouteToHostAddress instead
1070 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 * Ensure that a network route exists to deliver traffic to the specified
1072 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001073 * @param networkType the type of the network over which traffic to the
1074 * specified host is to be routed
1075 * @param hostAddress the IP address of the host to which the route is
1076 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 * @return {@code true} on success, {@code false} on failure
1078 */
1079 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001080 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1081
1082 if (inetAddress == null) {
1083 return false;
1084 }
1085
1086 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1087 }
1088
1089 /**
1090 * Ensure that a network route exists to deliver traffic to the specified
1091 * host via the specified network interface.
1092 * @param networkType the type of the network over which traffic to the
1093 * specified host is to be routed
1094 * @param hostAddress the IP address of the host to which the route is
1095 * desired
1096 * @return {@code true} on success, {@code false} on failure
1097 */
1098 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001100 if (mProtectedNetworks.contains(networkType)) {
1101 enforceConnectivityInternalPermission();
1102 }
1103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1105 return false;
1106 }
1107 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001108
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001109 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1110 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001111 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001112 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001113 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001114 }
1115 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001117 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001118 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001119 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001120 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001121 } catch (UnknownHostException e) {}
1122 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001123 }
1124
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001125 private boolean addRoute(LinkProperties p, RouteInfo r) {
1126 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001127 }
1128
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001129 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1130 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1131 }
1132
Robert Greenwaltad55d352011-07-22 11:55:33 -07001133 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1134 return modifyRouteToAddress(lp, addr, true);
1135 }
1136
1137 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1138 return modifyRouteToAddress(lp, addr, false);
1139 }
1140
1141 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1142 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1143 if (bestRoute == null) {
1144 bestRoute = RouteInfo.makeHostRoute(addr);
1145 } else {
1146 if (bestRoute.getGateway().equals(addr)) {
1147 // if there is no better route, add the implied hostroute for our gateway
1148 bestRoute = RouteInfo.makeHostRoute(addr);
1149 } else {
1150 // if we will connect to this through another route, add a direct route
1151 // to it's gateway
1152 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1153 }
1154 }
1155 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1156 }
1157
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001158 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1159 boolean doAdd) {
1160 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1161
1162 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1163 loge("Error adding route - too much recursion");
1164 return false;
1165 }
1166
1167 if (r.isHostRoute() == false) {
1168 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1169 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001170 if (bestRoute.getGateway().equals(r.getGateway())) {
1171 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001172 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001173 } else {
1174 // if we will connect to our gateway through another route, add a direct
1175 // route to it's gateway
1176 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001177 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001178 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001179 }
1180 }
1181 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001182 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001183 mAddedRoutes.add(r);
1184 try {
1185 mNetd.addRoute(ifaceName, r);
1186 } catch (Exception e) {
1187 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001188 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001189 return false;
1190 }
1191 } else {
1192 // if we remove this one and there are no more like it, then refcount==0 and
1193 // we can remove it from the table
1194 mAddedRoutes.remove(r);
1195 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001196 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001197 try {
1198 mNetd.removeRoute(ifaceName, r);
1199 } catch (Exception e) {
1200 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001201 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001202 return false;
1203 }
1204 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001205 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001206 }
1207 }
1208 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210
1211 /**
1212 * @see ConnectivityManager#getBackgroundDataSetting()
1213 */
1214 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001215 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 /**
1219 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1220 */
1221 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1222 mContext.enforceCallingOrSelfPermission(
1223 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1224 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001225
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001226 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1227
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1229 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001232 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-02-25 13:44:09 -08001233 Settings.Secure.putInt(mContext.getContentResolver(),
1234 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1235 Intent broadcast = new Intent(
1236 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1237 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001238 }
1239
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001240 /**
1241 * @see ConnectivityManager#getMobileDataEnabled()
1242 */
1243 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001244 // TODO: This detail should probably be in DataConnectionTracker's
1245 // which is where we store the value and maybe make this
1246 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001247 enforceAccessPermission();
1248 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1249 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001250 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001251 return retVal;
1252 }
1253
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001254 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001255 enforceConnectivityInternalPermission();
1256
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1258 (met ? ENABLED : DISABLED), networkType));
1259 }
1260
1261 private void handleSetDependencyMet(int networkType, boolean met) {
1262 if (mNetTrackers[networkType] != null) {
1263 if (DBG) {
1264 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1265 }
1266 mNetTrackers[networkType].setDependencyMet(met);
1267 }
1268 }
1269
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001270 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1271 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001272 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001274 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001275
1276 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001277 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001278 }
1279
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001280 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001281 // skip update when we've already applied rules
1282 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1283 if (oldRules == uidRules) return;
1284
1285 mUidRules.put(uid, uidRules);
1286 }
1287
1288 // TODO: dispatch into NMS to push rules towards kernel module
1289 // TODO: notify UID when it has requested targeted updates
1290 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001291
1292 @Override
1293 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1294 // only someone like NPMS should only be calling us
1295 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1296
1297 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001298 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001299 }
1300
1301 synchronized (mRulesLock) {
1302 mMeteredIfaces.clear();
1303 for (String iface : meteredIfaces) {
1304 mMeteredIfaces.add(iface);
1305 }
1306 }
1307 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001308 };
1309
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001310 /**
1311 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1312 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001313 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001314 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001315 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001316
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001317 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001318 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001319 }
1320
1321 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001322 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001323 if (VDBG) {
1324 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001325 }
Wink Savillee7982682010-12-07 10:31:02 -08001326 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001327 }
1328 }
1329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001331 mContext.enforceCallingOrSelfPermission(
1332 android.Manifest.permission.ACCESS_NETWORK_STATE,
1333 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335
1336 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001337 mContext.enforceCallingOrSelfPermission(
1338 android.Manifest.permission.CHANGE_NETWORK_STATE,
1339 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001342 // TODO Make this a special check when it goes public
1343 private void enforceTetherChangePermission() {
1344 mContext.enforceCallingOrSelfPermission(
1345 android.Manifest.permission.CHANGE_NETWORK_STATE,
1346 "ConnectivityService");
1347 }
1348
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001349 private void enforceTetherAccessPermission() {
1350 mContext.enforceCallingOrSelfPermission(
1351 android.Manifest.permission.ACCESS_NETWORK_STATE,
1352 "ConnectivityService");
1353 }
1354
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001355 private void enforceConnectivityInternalPermission() {
1356 mContext.enforceCallingOrSelfPermission(
1357 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1358 "ConnectivityService");
1359 }
1360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001362 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1363 * network, we ignore it. If it is for the active network, we send out a
1364 * broadcast. But first, we check whether it might be possible to connect
1365 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 * @param info the {@code NetworkInfo} for the network
1367 */
1368 private void handleDisconnect(NetworkInfo info) {
1369
Robert Greenwalt42acef32009-08-12 16:08:25 -07001370 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371
Robert Greenwalt42acef32009-08-12 16:08:25 -07001372 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 /*
1374 * If the disconnected network is not the active one, then don't report
1375 * this as a loss of connectivity. What probably happened is that we're
1376 * getting the disconnect for a network that we explicitly disabled
1377 * in accordance with network preference policies.
1378 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001379 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001380 List pids = mNetRequestersPids[prevNetType];
1381 for (int i = 0; i<pids.size(); i++) {
1382 Integer pid = (Integer)pids.get(i);
1383 // will remove them because the net's no longer connected
1384 // need to do this now as only now do we know the pids and
1385 // can properly null things that are no longer referenced.
1386 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1391 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1392 if (info.isFailover()) {
1393 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1394 info.setFailover(false);
1395 }
1396 if (info.getReason() != null) {
1397 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1398 }
1399 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001400 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1401 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001403
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001404 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001405 tryFailover(prevNetType);
1406 if (mActiveDefaultNetwork != -1) {
1407 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001408 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1409 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001410 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001411 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1412 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001413 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001414 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001415
1416 // Reset interface if no other connections are using the same interface
1417 boolean doReset = true;
1418 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1419 if (linkProperties != null) {
1420 String oldIface = linkProperties.getInterfaceName();
1421 if (TextUtils.isEmpty(oldIface) == false) {
1422 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1423 if (networkStateTracker == null) continue;
1424 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1425 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1426 LinkProperties l = networkStateTracker.getLinkProperties();
1427 if (l == null) continue;
1428 if (oldIface.equals(l.getInterfaceName())) {
1429 doReset = false;
1430 break;
1431 }
1432 }
1433 }
1434 }
1435 }
1436
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001437 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001438 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001439
1440 sendStickyBroadcast(intent);
1441 /*
1442 * If the failover network is already connected, then immediately send
1443 * out a followup broadcast indicating successful failover
1444 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001445 if (mActiveDefaultNetwork != -1) {
1446 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001447 }
1448 }
1449
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001450 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001451 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001452 * If this is a default network, check if other defaults are available.
1453 * Try to reconnect on all available and let them hash it out when
1454 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001455 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001456 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001457 if (mActiveDefaultNetwork == prevNetType) {
1458 mActiveDefaultNetwork = -1;
1459 }
1460
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001461 // don't signal a reconnect for anything lower or equal priority than our
1462 // current connected default
1463 // TODO - don't filter by priority now - nice optimization but risky
1464// int currentPriority = -1;
1465// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001466// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001467// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001468 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001469 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001470 if (mNetConfigs[checkType] == null) continue;
1471 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001472
1473// Enabling the isAvailable() optimization caused mobile to not get
1474// selected if it was in the middle of error handling. Specifically
1475// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1476// would not be available and we wouldn't get connected to anything.
1477// So removing the isAvailable() optimization below for now. TODO: This
1478// optimization should work and we need to investigate why it doesn't work.
1479// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1480// complete before it is really complete.
1481// if (!mNetTrackers[checkType].isAvailable()) continue;
1482
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001483// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001484
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001485 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1486 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1487 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1488 checkInfo.setFailover(true);
1489 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001490 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001491 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
1496 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001497 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1498 }
1499
1500 private void sendInetConditionBroadcast(NetworkInfo info) {
1501 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1502 }
1503
1504 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1505 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1507 if (info.isFailover()) {
1508 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1509 info.setFailover(false);
1510 }
1511 if (info.getReason() != null) {
1512 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1513 }
1514 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001515 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1516 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001518 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001519 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521
1522 /**
1523 * Called when an attempt to fail over to another network has failed.
1524 * @param info the {@link NetworkInfo} for the failed network
1525 */
1526 private void handleConnectionFailure(NetworkInfo info) {
1527 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528
Robert Greenwalt42acef32009-08-12 16:08:25 -07001529 String reason = info.getReason();
1530 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001531
Robert Greenwalt572172b2010-10-08 16:35:52 -07001532 String reasonText;
1533 if (reason == null) {
1534 reasonText = ".";
1535 } else {
1536 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001538 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001539
1540 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1542 if (getActiveNetworkInfo() == null) {
1543 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1544 }
1545 if (reason != null) {
1546 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1547 }
1548 if (extraInfo != null) {
1549 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1550 }
1551 if (info.isFailover()) {
1552 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1553 info.setFailover(false);
1554 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001555
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001556 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001557 tryFailover(info.getType());
1558 if (mActiveDefaultNetwork != -1) {
1559 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001560 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1561 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001562 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001563 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1564 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001565 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001566
Robert Greenwalt029be812010-09-20 18:01:43 -07001567 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001568 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001569 /*
1570 * If the failover network is already connected, then immediately send
1571 * out a followup broadcast indicating successful failover
1572 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001573 if (mActiveDefaultNetwork != -1) {
1574 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001575 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001576 }
1577
1578 private void sendStickyBroadcast(Intent intent) {
1579 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001580 if (!mSystemReady) {
1581 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001582 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001583 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1584 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001585 }
1586 }
1587
1588 void systemReady() {
1589 synchronized(this) {
1590 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001591 if (mInitialBroadcast != null) {
1592 mContext.sendStickyBroadcast(mInitialBroadcast);
1593 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001594 }
1595 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001596 // load the global proxy at startup
1597 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599
1600 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001601 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602
1603 // snapshot isFailover, because sendConnectedBroadcast() resets it
1604 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001605 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606
Robert Greenwalt42acef32009-08-12 16:08:25 -07001607 // if this is a default net and other default is running
1608 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001609 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001610 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1611 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001612 mNetConfigs[mActiveDefaultNetwork].priority >
1613 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001614 mNetworkPreference == mActiveDefaultNetwork) {
1615 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001616 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001617 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001618 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001619 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001620 teardown(thisNet);
1621 return;
1622 } else {
1623 // tear down the other
1624 NetworkStateTracker otherNet =
1625 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001626 if (DBG) {
1627 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001628 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001629 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001630 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001631 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001632 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001633 return;
1634 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001635 }
1636 }
1637 synchronized (ConnectivityService.this) {
1638 // have a new default network, release the transition wakelock in a second
1639 // if it's held. The second pause is to allow apps to reconnect over the
1640 // new network
1641 if (mNetTransitionWakeLock.isHeld()) {
1642 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001643 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001644 mNetTransitionWakeLockSerialNumber, 0),
1645 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001646 }
1647 }
1648 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001649 // this will cause us to come up initially as unconnected and switching
1650 // to connected after our normal pause unless somebody reports us as reall
1651 // disconnected
1652 mDefaultInetConditionPublished = 0;
1653 mDefaultConnectionSequence++;
1654 mInetConditionChangeInFlight = false;
1655 // Don't do this - if we never sign in stay, grey
1656 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001659 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001660 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001661 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001665 * After a change in the connectivity state of a network. We're mainly
1666 * concerned with making sure that the list of DNS servers is set up
1667 * according to which networks are connected, and ensuring that the
1668 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001670 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001671 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001674 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001675 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001677 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001678
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001679 LinkProperties curLp = mCurrentLinkProperties[netType];
1680 LinkProperties newLp = null;
1681
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001682 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001683 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001684 if (VDBG) {
1685 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1686 " doReset=" + doReset + " resetMask=" + resetMask +
1687 "\n curLp=" + curLp +
1688 "\n newLp=" + newLp);
1689 }
1690
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001691 if (curLp != null) {
1692 if (curLp.isIdenticalInterfaceName(newLp)) {
1693 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1694 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1695 for (LinkAddress linkAddr : car.removed) {
1696 if (linkAddr.getAddress() instanceof Inet4Address) {
1697 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1698 }
1699 if (linkAddr.getAddress() instanceof Inet6Address) {
1700 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1701 }
Wink Savillee8222252011-07-13 13:44:13 -07001702 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001703 if (DBG) {
1704 log("handleConnectivityChange: addresses changed" +
1705 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1706 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001707 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001708 } else {
1709 if (DBG) {
1710 log("handleConnectivityChange: address are the same reset per doReset" +
1711 " linkProperty[" + netType + "]:" +
1712 " resetMask=" + resetMask);
1713 }
Wink Savillee8222252011-07-13 13:44:13 -07001714 }
1715 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001716 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001717 if (DBG) {
1718 log("handleConnectivityChange: interface not not equivalent reset both" +
1719 " linkProperty[" + netType + "]:" +
1720 " resetMask=" + resetMask);
1721 }
Wink Savillee8222252011-07-13 13:44:13 -07001722 }
Wink Savillee8222252011-07-13 13:44:13 -07001723 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001724 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001725 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001726 }
1727 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001728 if (VDBG) {
1729 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1730 " doReset=" + doReset + " resetMask=" + resetMask +
1731 "\n curLp=" + curLp +
1732 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001735 mCurrentLinkProperties[netType] = newLp;
1736 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001737
Wink Savillee8222252011-07-13 13:44:13 -07001738 if (doReset || resetMask != 0) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001739 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1740 if (linkProperties != null) {
1741 String iface = linkProperties.getInterfaceName();
1742 if (TextUtils.isEmpty(iface) == false) {
Wink Savillee8222252011-07-13 13:44:13 -07001743 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1744 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001745 }
1746 }
1747 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001748
1749 // TODO: Temporary notifying upstread change to Tethering.
1750 // @see bug/4455071
1751 /** Notify TetheringService if interface name has been changed. */
1752 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1753 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1754 if (isTetheringSupported()) {
1755 mTethering.handleTetherIfaceChange();
1756 }
1757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 }
1759
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001760 /**
1761 * Add and remove routes using the old properties (null if not previously connected),
1762 * new properties (null if becoming disconnected). May even be double null, which
1763 * is a noop.
1764 * Uses isLinkDefault to determine if default routes should be set or conversely if
1765 * host routes should be set to the dns servers
1766 */
1767 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1768 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001769 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1770 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001771 if (curLp != null) {
1772 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001773 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001774 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001775 } else if (newLp != null) {
1776 routeDiff.added = newLp.getRoutes();
1777 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001778 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001779
Robert Greenwaltad55d352011-07-22 11:55:33 -07001780 for (RouteInfo r : routeDiff.removed) {
1781 if (isLinkDefault || ! r.isDefaultRoute()) {
1782 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001783 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001784 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001785
Robert Greenwaltad55d352011-07-22 11:55:33 -07001786 for (RouteInfo r : routeDiff.added) {
1787 if (isLinkDefault || ! r.isDefaultRoute()) {
1788 addRoute(newLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001789 }
1790 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001791
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001792 if (!isLinkDefault) {
1793 // handle DNS routes
Robert Greenwaltad55d352011-07-22 11:55:33 -07001794 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1795 // no change in routes, check for change in dns themselves
1796 for (InetAddress oldDns : dnsDiff.removed) {
1797 removeRouteToAddress(curLp, oldDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001798 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001799 for (InetAddress newDns : dnsDiff.added) {
1800 addRouteToAddress(newLp, newDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001801 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001802 } else {
1803 // routes changed - remove all old dns entries and add new
1804 if (curLp != null) {
1805 for (InetAddress oldDns : curLp.getDnses()) {
1806 removeRouteToAddress(curLp, oldDns);
1807 }
1808 }
1809 if (newLp != null) {
1810 for (InetAddress newDns : newLp.getDnses()) {
1811 addRouteToAddress(newLp, newDns);
1812 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001813 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001814 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001815 }
1816 }
1817
1818
Irfan Sheriffd649c122010-06-09 15:39:36 -07001819 /**
1820 * Reads the network specific TCP buffer sizes from SystemProperties
1821 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1822 * wide use
1823 */
1824 public void updateNetworkSettings(NetworkStateTracker nt) {
1825 String key = nt.getTcpBufferSizesPropName();
1826 String bufferSizes = SystemProperties.get(key);
1827
1828 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001829 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001830
1831 // Setting to default values so we won't be stuck to previous values
1832 key = "net.tcp.buffersize.default";
1833 bufferSizes = SystemProperties.get(key);
1834 }
1835
1836 // Set values in kernel
1837 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001838 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001839 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001840 + "] which comes from [" + key + "]");
1841 }
1842 setBufferSize(bufferSizes);
1843 }
1844 }
1845
1846 /**
1847 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1848 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1849 *
1850 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1851 * writeMin, writeInitial, writeMax"
1852 */
1853 private void setBufferSize(String bufferSizes) {
1854 try {
1855 String[] values = bufferSizes.split(",");
1856
1857 if (values.length == 6) {
1858 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001859 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1860 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1861 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1862 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1863 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1864 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001865 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001866 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001867 }
1868 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001869 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001870 }
1871 }
1872
Robert Greenwalt42acef32009-08-12 16:08:25 -07001873 /**
1874 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1875 * on the highest priority active net which this process requested.
1876 * If there aren't any, clear it out
1877 */
1878 private void reassessPidDns(int myPid, boolean doBump)
1879 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001880 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001881 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001882 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001883 continue;
1884 }
1885 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001886 if (nt.getNetworkInfo().isConnected() &&
1887 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001888 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001889 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001890 List pids = mNetRequestersPids[i];
1891 for (int j=0; j<pids.size(); j++) {
1892 Integer pid = (Integer)pids.get(j);
1893 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001894 Collection<InetAddress> dnses = p.getDnses();
1895 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001896 if (doBump) {
1897 bumpDns();
1898 }
1899 return;
1900 }
1901 }
1902 }
1903 }
1904 // nothing found - delete
1905 for (int i = 1; ; i++) {
1906 String prop = "net.dns" + i + "." + myPid;
1907 if (SystemProperties.get(prop).length() == 0) {
1908 if (doBump) {
1909 bumpDns();
1910 }
1911 return;
1912 }
1913 SystemProperties.set(prop, "");
1914 }
1915 }
1916
Robert Greenwalt10398722010-12-17 15:20:36 -08001917 // return true if results in a change
1918 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001919 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001920 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001921 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001922 String dnsString = dns.getHostAddress();
1923 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1924 changed = true;
1925 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1926 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001927 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001928 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001929 }
1930
1931 private void bumpDns() {
1932 /*
1933 * Bump the property that tells the name resolver library to reread
1934 * the DNS server list from the properties.
1935 */
1936 String propVal = SystemProperties.get("net.dnschange");
1937 int n = 0;
1938 if (propVal.length() != 0) {
1939 try {
1940 n = Integer.parseInt(propVal);
1941 } catch (NumberFormatException e) {}
1942 }
1943 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001944 /*
1945 * Tell the VMs to toss their DNS caches
1946 */
1947 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1948 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001949 /*
1950 * Connectivity events can happen before boot has completed ...
1951 */
1952 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001953 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001954 }
1955
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001956 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001957 private boolean updateDns(String network, String iface,
1958 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001959 boolean changed = false;
1960 int last = 0;
1961 if (dnses.size() == 0 && mDefaultDns != null) {
1962 ++last;
1963 String value = mDefaultDns.getHostAddress();
1964 if (!value.equals(SystemProperties.get("net.dns1"))) {
1965 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001966 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001967 }
1968 changed = true;
1969 SystemProperties.set("net.dns1", value);
1970 }
1971 } else {
1972 for (InetAddress dns : dnses) {
1973 ++last;
1974 String key = "net.dns" + last;
1975 String value = dns.getHostAddress();
1976 if (!changed && value.equals(SystemProperties.get(key))) {
1977 continue;
1978 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001979 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001980 log("adding dns " + value + " for " + network);
1981 }
1982 changed = true;
1983 SystemProperties.set(key, value);
1984 }
1985 }
1986 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
1987 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001988 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07001989 changed = true;
1990 SystemProperties.set(key, "");
1991 }
1992 mNumDnsEntries = last;
1993
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07001994 if (changed) {
1995 try {
1996 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
1997 mNetd.setDefaultInterfaceForDns(iface);
1998 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001999 loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002000 }
2001 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002002 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2003 SystemProperties.set("net.dns.search", domains);
2004 changed = true;
2005 }
2006 return changed;
2007 }
2008
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002009 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002010 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002011 NetworkStateTracker nt = mNetTrackers[netType];
2012 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002013 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002014 if (p == null) return;
2015 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002016 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002017 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002018 String network = nt.getNetworkInfo().getTypeName();
2019 synchronized (mDnsLock) {
2020 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002021 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002022 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002023 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002024 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002025 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002026 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002027 NetworkUtils.makeStrings(dnses));
2028 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002029 loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002030 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002031 // set per-pid dns for attached secondary nets
2032 List pids = mNetRequestersPids[netType];
2033 for (int y=0; y< pids.size(); y++) {
2034 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002035 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002038 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002040 }
2041
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002042 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002043 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2044 NETWORK_RESTORE_DELAY_PROP_NAME);
2045 if(restoreDefaultNetworkDelayStr != null &&
2046 restoreDefaultNetworkDelayStr.length() != 0) {
2047 try {
2048 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2049 } catch (NumberFormatException e) {
2050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002052 // if the system property isn't set, use the value for the apn type
2053 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2054
2055 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2056 (mNetConfigs[networkType] != null)) {
2057 ret = mNetConfigs[networkType].restoreTime;
2058 }
2059 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061
2062 @Override
2063 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002064 if (mContext.checkCallingOrSelfPermission(
2065 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002067 pw.println("Permission Denial: can't dump ConnectivityService " +
2068 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2069 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 return;
2071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 pw.println();
2073 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002074 if (nst != null) {
2075 if (nst.getNetworkInfo().isConnected()) {
2076 pw.println("Active network: " + nst.getNetworkInfo().
2077 getTypeName());
2078 }
2079 pw.println(nst.getNetworkInfo());
2080 pw.println(nst);
2081 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002084
2085 pw.println("Network Requester Pids:");
2086 for (int net : mPriorityList) {
2087 String pidString = net + ": ";
2088 for (Object pid : mNetRequestersPids[net]) {
2089 pidString = pidString + pid.toString() + ", ";
2090 }
2091 pw.println(pidString);
2092 }
2093 pw.println();
2094
2095 pw.println("FeatureUsers:");
2096 for (Object requester : mFeatureUsers) {
2097 pw.println(requester.toString());
2098 }
2099 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002100
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002101 synchronized (this) {
2102 pw.println("NetworkTranstionWakeLock is currently " +
2103 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2104 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2105 }
2106 pw.println();
2107
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002108 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002109
2110 if (mInetLog != null) {
2111 pw.println();
2112 pw.println("Inet condition reports:");
2113 for(int i = 0; i < mInetLog.size(); i++) {
2114 pw.println(mInetLog.get(i));
2115 }
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
2118
Robert Greenwalt42acef32009-08-12 16:08:25 -07002119 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002121 public MyHandler(Looper looper) {
2122 super(looper);
2123 }
2124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 @Override
2126 public void handleMessage(Message msg) {
2127 NetworkInfo info;
2128 switch (msg.what) {
2129 case NetworkStateTracker.EVENT_STATE_CHANGED:
2130 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002131 int type = info.getType();
2132 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002133
Wink Savilleed9c02b2010-12-03 12:01:38 -08002134 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002135 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002136 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137
2138 // Connectivity state changed:
2139 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002140 // [12-9] Network subtype (for mobile network, as defined
2141 // by TelephonyManager)
2142 // [8-3] Detailed state ordinal (as defined by
2143 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 // [2-0] Network type (as defined by ConnectivityManager)
2145 int eventLogParam = (info.getType() & 0x7) |
2146 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2147 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002148 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002149 eventLogParam);
2150
2151 if (info.getDetailedState() ==
2152 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002154 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002156 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002158 // the logic here is, handle SUSPENDED the same as
2159 // DISCONNECTED. The only difference being we are
2160 // broadcasting an intent with NetworkInfo that's
2161 // suspended. This allows the applications an
2162 // opportunity to handle DISCONNECTED and SUSPENDED
2163 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002165 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 handleConnect(info);
2167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002170 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002171 // TODO: Temporary allowing network configuration
2172 // change not resetting sockets.
2173 // @see bug/4455071
2174 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002176 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002177 String causedBy = null;
2178 synchronized (ConnectivityService.this) {
2179 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2180 mNetTransitionWakeLock.isHeld()) {
2181 mNetTransitionWakeLock.release();
2182 causedBy = mNetTransitionWakeLockCausedBy;
2183 }
2184 }
2185 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002186 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002187 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002188 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002189 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002190 FeatureUser u = (FeatureUser)msg.obj;
2191 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002192 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002193 case EVENT_INET_CONDITION_CHANGE:
2194 {
2195 int netType = msg.arg1;
2196 int condition = msg.arg2;
2197 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002198 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002199 }
2200 case EVENT_INET_CONDITION_HOLD_END:
2201 {
2202 int netType = msg.arg1;
2203 int sequence = msg.arg2;
2204 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002205 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002206 }
2207 case EVENT_SET_NETWORK_PREFERENCE:
2208 {
2209 int preference = msg.arg1;
2210 handleSetNetworkPreference(preference);
2211 break;
2212 }
2213 case EVENT_SET_BACKGROUND_DATA:
2214 {
2215 boolean enabled = (msg.arg1 == ENABLED);
2216 handleSetBackgroundData(enabled);
2217 break;
2218 }
2219 case EVENT_SET_MOBILE_DATA:
2220 {
2221 boolean enabled = (msg.arg1 == ENABLED);
2222 handleSetMobileData(enabled);
2223 break;
2224 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002225 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2226 {
2227 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002228 break;
2229 }
2230 case EVENT_SET_DEPENDENCY_MET:
2231 {
2232 boolean met = (msg.arg1 == ENABLED);
2233 handleSetDependencyMet(msg.arg2, met);
2234 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002235 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002236 case EVENT_RESTORE_DNS:
2237 {
2238 if (mActiveDefaultNetwork != -1) {
2239 handleDnsConfigurationChange(mActiveDefaultNetwork);
2240 }
2241 break;
2242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 }
2244 }
2245 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002246
2247 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002248 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002249 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002250
2251 if (isTetheringSupported()) {
2252 return mTethering.tether(iface);
2253 } else {
2254 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2255 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002256 }
2257
2258 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002259 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002260 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002261
2262 if (isTetheringSupported()) {
2263 return mTethering.untether(iface);
2264 } else {
2265 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2266 }
2267 }
2268
2269 // javadoc from interface
2270 public int getLastTetherError(String iface) {
2271 enforceTetherAccessPermission();
2272
2273 if (isTetheringSupported()) {
2274 return mTethering.getLastTetherError(iface);
2275 } else {
2276 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2277 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002278 }
2279
2280 // TODO - proper iface API for selection by property, inspection, etc
2281 public String[] getTetherableUsbRegexs() {
2282 enforceTetherAccessPermission();
2283 if (isTetheringSupported()) {
2284 return mTethering.getTetherableUsbRegexs();
2285 } else {
2286 return new String[0];
2287 }
2288 }
2289
2290 public String[] getTetherableWifiRegexs() {
2291 enforceTetherAccessPermission();
2292 if (isTetheringSupported()) {
2293 return mTethering.getTetherableWifiRegexs();
2294 } else {
2295 return new String[0];
2296 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002297 }
2298
Danica Chang6fdd0c62010-08-11 14:54:43 -07002299 public String[] getTetherableBluetoothRegexs() {
2300 enforceTetherAccessPermission();
2301 if (isTetheringSupported()) {
2302 return mTethering.getTetherableBluetoothRegexs();
2303 } else {
2304 return new String[0];
2305 }
2306 }
2307
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002308 public int setUsbTethering(boolean enable) {
2309 enforceTetherAccessPermission();
2310 if (isTetheringSupported()) {
2311 return mTethering.setUsbTethering(enable);
2312 } else {
2313 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2314 }
2315 }
2316
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002317 // TODO - move iface listing, queries, etc to new module
2318 // javadoc from interface
2319 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002320 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002321 return mTethering.getTetherableIfaces();
2322 }
2323
2324 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002325 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002326 return mTethering.getTetheredIfaces();
2327 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002328
Robert Greenwalt5a735062010-03-02 17:25:02 -08002329 public String[] getTetheringErroredIfaces() {
2330 enforceTetherAccessPermission();
2331 return mTethering.getErroredIfaces();
2332 }
2333
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002334 // if ro.tether.denied = true we default to no tethering
2335 // gservices could set the secure setting to 1 though to enable it on a build where it
2336 // had previously been turned off.
2337 public boolean isTetheringSupported() {
2338 enforceTetherAccessPermission();
2339 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002340 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2341 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2342 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002343 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002344
2345 // An API NetworkStateTrackers can call when they lose their network.
2346 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2347 // whichever happens first. The timer is started by the first caller and not
2348 // restarted by subsequent callers.
2349 public void requestNetworkTransitionWakelock(String forWhom) {
2350 enforceConnectivityInternalPermission();
2351 synchronized (this) {
2352 if (mNetTransitionWakeLock.isHeld()) return;
2353 mNetTransitionWakeLockSerialNumber++;
2354 mNetTransitionWakeLock.acquire();
2355 mNetTransitionWakeLockCausedBy = forWhom;
2356 }
2357 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002358 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002359 mNetTransitionWakeLockSerialNumber, 0),
2360 mNetTransitionWakeLockTimeout);
2361 return;
2362 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002363
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002364 // 100 percent is full good, 0 is full bad.
2365 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002366 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002367 mContext.enforceCallingOrSelfPermission(
2368 android.Manifest.permission.STATUS_BAR,
2369 "ConnectivityService");
2370
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002371 if (DBG) {
2372 int pid = getCallingPid();
2373 int uid = getCallingUid();
2374 String s = pid + "(" + uid + ") reports inet is " +
2375 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2376 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2377 mInetLog.add(s);
2378 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2379 mInetLog.remove(0);
2380 }
2381 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002382 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002383 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2384 }
2385
2386 private void handleInetConditionChange(int netType, int condition) {
2387 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002388 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002389 netType + ", condition=" + condition +
2390 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2391 }
2392 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002393 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002394 return;
2395 }
2396 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002397 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002398 return;
2399 }
2400 mDefaultInetCondition = condition;
2401 int delay;
2402 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002403 if (VDBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002404 // setup a new hold to debounce this
2405 if (mDefaultInetCondition > 50) {
2406 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2407 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2408 } else {
2409 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2410 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2411 }
2412 mInetConditionChangeInFlight = true;
2413 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2414 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2415 } else {
2416 // we've set the new condition, when this hold ends that will get
2417 // picked up
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002418 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002419 }
2420 }
2421
2422 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002423 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002424 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002425 ", condition =" + mDefaultInetCondition +
2426 ", published condition =" + mDefaultInetConditionPublished);
2427 }
2428 mInetConditionChangeInFlight = false;
2429
2430 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002431 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002432 return;
2433 }
2434 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002435 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002436 return;
2437 }
2438 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002439 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002440 return;
2441 }
2442 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2443 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002444 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002445 return;
2446 }
2447 mDefaultInetConditionPublished = mDefaultInetCondition;
2448 sendInetConditionBroadcast(networkInfo);
2449 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002450 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002451
2452 public synchronized ProxyProperties getProxy() {
2453 if (mGlobalProxy != null) return mGlobalProxy;
2454 if (mDefaultProxy != null) return mDefaultProxy;
2455 return null;
2456 }
2457
2458 public void setGlobalProxy(ProxyProperties proxyProperties) {
2459 enforceChangePermission();
2460 synchronized (mGlobalProxyLock) {
2461 if (proxyProperties == mGlobalProxy) return;
2462 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2463 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2464
2465 String host = "";
2466 int port = 0;
2467 String exclList = "";
2468 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2469 mGlobalProxy = new ProxyProperties(proxyProperties);
2470 host = mGlobalProxy.getHost();
2471 port = mGlobalProxy.getPort();
2472 exclList = mGlobalProxy.getExclusionList();
2473 } else {
2474 mGlobalProxy = null;
2475 }
2476 ContentResolver res = mContext.getContentResolver();
2477 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2478 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002479 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002480 exclList);
2481 }
2482
2483 if (mGlobalProxy == null) {
2484 proxyProperties = mDefaultProxy;
2485 }
2486 sendProxyBroadcast(proxyProperties);
2487 }
2488
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002489 private void loadGlobalProxy() {
2490 ContentResolver res = mContext.getContentResolver();
2491 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2492 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2493 String exclList = Settings.Secure.getString(res,
2494 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2495 if (!TextUtils.isEmpty(host)) {
2496 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2497 synchronized (mGlobalProxyLock) {
2498 mGlobalProxy = proxyProperties;
2499 }
2500 }
2501 }
2502
Robert Greenwalt434203a2010-10-11 16:00:27 -07002503 public ProxyProperties getGlobalProxy() {
2504 synchronized (mGlobalProxyLock) {
2505 return mGlobalProxy;
2506 }
2507 }
2508
2509 private void handleApplyDefaultProxy(int type) {
2510 // check if new default - push it out to all VM if so
2511 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2512 synchronized (this) {
2513 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2514 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002515 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002516 mDefaultProxy = proxy;
2517 } else {
2518 mDefaultProxy = null;
2519 }
2520 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002521 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002522 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2523 if (mGlobalProxy != null) return;
2524 sendProxyBroadcast(proxy);
2525 }
2526
2527 private void handleDeprecatedGlobalHttpProxy() {
2528 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2529 Settings.Secure.HTTP_PROXY);
2530 if (!TextUtils.isEmpty(proxy)) {
2531 String data[] = proxy.split(":");
2532 String proxyHost = data[0];
2533 int proxyPort = 8080;
2534 if (data.length > 1) {
2535 try {
2536 proxyPort = Integer.parseInt(data[1]);
2537 } catch (NumberFormatException e) {
2538 return;
2539 }
2540 }
2541 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2542 setGlobalProxy(p);
2543 }
2544 }
2545
2546 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002547 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002548 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002549 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002550 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2551 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002552 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002553 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002554 }
2555
2556 private static class SettingsObserver extends ContentObserver {
2557 private int mWhat;
2558 private Handler mHandler;
2559 SettingsObserver(Handler handler, int what) {
2560 super(handler);
2561 mHandler = handler;
2562 mWhat = what;
2563 }
2564
2565 void observe(Context context) {
2566 ContentResolver resolver = context.getContentResolver();
2567 resolver.registerContentObserver(Settings.Secure.getUriFor(
2568 Settings.Secure.HTTP_PROXY), false, this);
2569 }
2570
2571 @Override
2572 public void onChange(boolean selfChange) {
2573 mHandler.obtainMessage(mWhat).sendToTarget();
2574 }
2575 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002576
2577 private void log(String s) {
2578 Slog.d(TAG, s);
2579 }
2580
2581 private void loge(String s) {
2582 Slog.e(TAG, s);
2583 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002584
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002585 int convertFeatureToNetworkType(String feature){
2586 int networkType = -1;
2587 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2588 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2589 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2590 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2591 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2592 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2593 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2594 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2595 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2596 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2597 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2598 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2599 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2600 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2601 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2602 }
2603 return networkType;
2604 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002605
2606 private static <T> T checkNotNull(T value, String message) {
2607 if (value == null) {
2608 throw new NullPointerException(message);
2609 }
2610 return value;
2611 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002612
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002613 /**
2614 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002615 * VpnBuilder and not available in ConnectivityManager. Permissions
2616 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002617 * @hide
2618 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002619 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002620 public boolean protectVpn(ParcelFileDescriptor socket) {
2621 try {
2622 int type = mActiveDefaultNetwork;
2623 if (ConnectivityManager.isNetworkTypeValid(type)) {
2624 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2625 return true;
2626 }
2627 } catch (Exception e) {
2628 // ignore
2629 } finally {
2630 try {
2631 socket.close();
2632 } catch (Exception e) {
2633 // ignore
2634 }
2635 }
2636 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002637 }
2638
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002639 /**
2640 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002641 * and not available in ConnectivityManager. Permissions are checked
2642 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002643 * @hide
2644 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002645 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002646 public boolean prepareVpn(String oldPackage, String newPackage) {
2647 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002648 }
2649
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002650 /**
2651 * Configure a TUN interface and return its file descriptor. Parameters
2652 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002653 * and not available in ConnectivityManager. Permissions are checked in
2654 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002655 * @hide
2656 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002657 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002658 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002659 return mVpn.establish(config);
2660 }
2661
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002662 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002663 * Start legacy VPN and return an intent to VpnDialogs. This method is
2664 * used by VpnSettings and not available in ConnectivityManager.
2665 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002666 * @hide
2667 */
2668 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002669 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2670 mVpn.startLegacyVpn(config, racoon, mtpd);
2671 }
2672
2673 /**
2674 * Return the information of the ongoing legacy VPN. This method is used
2675 * by VpnSettings and not available in ConnectivityManager. Permissions
2676 * are checked in Vpn class.
2677 * @hide
2678 */
2679 @Override
2680 public LegacyVpnInfo getLegacyVpnInfo() {
2681 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002682 }
2683
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002684 /**
2685 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2686 * through NetworkStateTracker since it works differently. For example, it
2687 * needs to override DNS servers but never takes the default routes. It
2688 * relies on another data network, and it could keep existing connections
2689 * alive after reconnecting, switching between networks, or even resuming
2690 * from deep sleep. Calls from applications should be done synchronously
2691 * to avoid race conditions. As these are all hidden APIs, refactoring can
2692 * be done whenever a better abstraction is developed.
2693 */
2694 public class VpnCallback {
2695
2696 private VpnCallback() {
2697 }
2698
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002699 public void override(List<String> dnsServers, List<String> searchDomains) {
2700 if (dnsServers == null) {
2701 restore();
2702 return;
2703 }
2704
2705 // Convert DNS servers into addresses.
2706 List<InetAddress> addresses = new ArrayList<InetAddress>();
2707 for (String address : dnsServers) {
2708 // Double check the addresses and remove invalid ones.
2709 try {
2710 addresses.add(InetAddress.parseNumericAddress(address));
2711 } catch (Exception e) {
2712 // ignore
2713 }
2714 }
2715 if (addresses.isEmpty()) {
2716 restore();
2717 return;
2718 }
2719
2720 // Concatenate search domains into a string.
2721 StringBuilder buffer = new StringBuilder();
2722 if (searchDomains != null) {
2723 for (String domain : searchDomains) {
2724 buffer.append(domain).append(' ');
2725 }
2726 }
2727 String domains = buffer.toString().trim();
2728
2729 // Apply DNS changes.
2730 boolean changed = false;
2731 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002732 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002733 mDnsOverridden = true;
2734 }
2735 if (changed) {
2736 bumpDns();
2737 }
2738
2739 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002740 }
2741
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002742 public void restore() {
2743 synchronized (mDnsLock) {
2744 if (!mDnsOverridden) {
2745 return;
2746 }
2747 mDnsOverridden = false;
2748 }
2749 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002750 }
2751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752}