blob: 2bb952ee8b2d8d8f8ed8254e258c7b9a07f8d4f9 [file] [log] [blame]
The Android Open Source Project28527d22009-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 Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070036import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070038import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070040import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070042import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070043import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070044import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080045import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070046import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070047import android.net.Proxy;
48import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070049import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080050import android.net.wifi.WifiStateTracker;
51import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040052import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080053import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070054import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070055import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070056import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.os.Looper;
58import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070059import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070060import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070061import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.os.ServiceManager;
63import android.os.SystemProperties;
64import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070065import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080066import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080067import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070068import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070072import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080073import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070074import com.android.server.connectivity.Vpn;
75
Jeff Sharkey21062e72011-05-28 20:56:34 -070076import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070077import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080078
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070080import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070082import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070083import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070084import java.net.InetAddress;
85import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070086import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070087import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070088import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070089import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070090import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070092import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093
94/**
95 * @hide
96 */
97public class ConnectivityService extends IConnectivityManager.Stub {
98
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070099 private static final boolean DBG = true;
Wink Saville051a6642011-07-13 13:44:13 -0700100 private static final boolean VDBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101 private static final String TAG = "ConnectivityService";
102
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700103 private static final boolean LOGD_RULES = false;
104
Robert Greenwalt2034b912009-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 Greenwaltbd492212011-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 Greenwalt0c4828c2010-01-26 11:40:34 -0800115 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800116 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800117
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700118 private Vpn mVpn;
119
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700120 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
121 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700122 /** Currently active network rules by UID. */
123 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700124 /** Set of ifaces that are costly. */
125 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700126
The Android Open Source Project28527d22009-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 Greenwalt2034b912009-08-12 16:08:25 -0700133
134 /**
Wink Saville051a6642011-07-13 13:44:13 -0700135 * The link properties that define the current links
136 */
137 private LinkProperties mCurrentLinkProperties[];
138
139 /**
Robert Greenwalt2034b912009-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 Greenwalt2034b912009-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 Project28527d22009-03-03 19:31:44 -0800150 private Context mContext;
151 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700152 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-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 Project28527d22009-03-03 19:31:44 -0800158
Chia-chi Yehcc844502011-07-14 18:01:57 -0700159 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700161 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
163 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700164 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800165
Robert Greenwalt355205c2011-05-10 15:05:02 -0700166 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700167 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700168
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700169 private static final int ENABLED = 1;
170 private static final int DISABLED = 0;
171
172 // Share the event space with NetworkStateTracker (which can't see this
173 // internal class but sends us events). If you change these, change
174 // NetworkStateTracker.java too.
175 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
176 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
177
178 /**
179 * used internally as a delayed event to make us switch back to the
180 * default network
181 */
182 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
183 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
184
185 /**
186 * used internally to change our mobile data enabled flag
187 */
188 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
189 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
190
191 /**
192 * used internally to change our network preference setting
193 * arg1 = networkType to prefer
194 */
195 private static final int EVENT_SET_NETWORK_PREFERENCE =
196 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
197
198 /**
199 * used internally to synchronize inet condition reports
200 * arg1 = networkType
201 * arg2 = condition (0 bad, 100 good)
202 */
203 private static final int EVENT_INET_CONDITION_CHANGE =
204 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
205
206 /**
207 * used internally to mark the end of inet condition hold periods
208 * arg1 = networkType
209 */
210 private static final int EVENT_INET_CONDITION_HOLD_END =
211 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
212
213 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700214 * used internally to set enable/disable cellular data
215 * arg1 = ENBALED or DISABLED
216 */
217 private static final int EVENT_SET_MOBILE_DATA =
218 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
219
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700220 /**
221 * used internally to clear a wakelock when transitioning
222 * from one net to another
223 */
224 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
225 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
226
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700227 /**
228 * used internally to reload global proxy settings
229 */
230 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
231 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
232
Robert Greenwalt34848c02011-03-25 13:09:25 -0700233 /**
234 * used internally to set external dependency met/unmet
235 * arg1 = ENABLED (met) or DISABLED (unmet)
236 * arg2 = NetworkType
237 */
238 private static final int EVENT_SET_DEPENDENCY_MET =
239 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
240
Chia-chi Yehcc844502011-07-14 18:01:57 -0700241 /**
242 * used internally to restore DNS properties back to the
243 * default network
244 */
245 private static final int EVENT_RESTORE_DNS =
246 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
247
Wink Saville7e4333c2011-08-05 11:40:22 -0700248 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700249 * used internally to send a sticky broadcast delayed.
250 */
251 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville7e4333c2011-08-05 11:40:22 -0700252 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700253
Robert Greenwalt2034b912009-08-12 16:08:25 -0700254 private Handler mHandler;
255
256 // list of DeathRecipients used to make sure features are turned off when
257 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500258 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700259
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400260 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800261 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400262
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700263 private PowerManager.WakeLock mNetTransitionWakeLock;
264 private String mNetTransitionWakeLockCausedBy = "";
265 private int mNetTransitionWakeLockSerialNumber;
266 private int mNetTransitionWakeLockTimeout;
267
Robert Greenwalt94daa182010-09-01 11:34:05 -0700268 private InetAddress mDefaultDns;
269
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700270 // this collection is used to refcount the added routes - if there are none left
271 // it's time to remove the route from the route table
272 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
273
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700274 // used in DBG mode to track inet condition reports
275 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
276 private ArrayList mInetLog;
277
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700278 // track the current default http proxy - tell the world if we get a new one (real change)
279 private ProxyProperties mDefaultProxy = null;
280 // track the global proxy.
281 private ProxyProperties mGlobalProxy = null;
282 private final Object mGlobalProxyLock = new Object();
283
284 private SettingsObserver mSettingsObserver;
285
Robert Greenwalt34848c02011-03-25 13:09:25 -0700286 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700287 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700288
Robert Greenwalt12c44552009-12-07 11:33:18 -0800289 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700290 public int mSimultaneity;
291 public int mType;
292 public RadioAttributes(String init) {
293 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700294 mType = Integer.parseInt(fragments[0]);
295 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700296 }
297 }
298 RadioAttributes[] mRadioAttributes;
299
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700300 // the set of network types that can only be enabled by system/sig apps
301 List mProtectedNetworks;
302
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700303 public ConnectivityService(
304 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800305 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800306
Wink Saville775aad62010-09-02 19:23:52 -0700307 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
308 handlerThread.start();
309 mHandler = new MyHandler(handlerThread.getLooper());
310
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800311 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800312 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
313 String id = Settings.Secure.getString(context.getContentResolver(),
314 Settings.Secure.ANDROID_ID);
315 if (id != null && id.length() > 0) {
316 String name = new String("android_").concat(id);
317 SystemProperties.set("net.hostname", name);
318 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800319 }
320
Robert Greenwalt94daa182010-09-01 11:34:05 -0700321 // read our default dns server ip
322 String dns = Settings.Secure.getString(context.getContentResolver(),
323 Settings.Secure.DEFAULT_DNS_SERVER);
324 if (dns == null || dns.length() == 0) {
325 dns = context.getResources().getString(
326 com.android.internal.R.string.config_default_dns_server);
327 }
328 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800329 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
330 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800331 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700332 }
333
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700334 mContext = checkNotNull(context, "missing Context");
335 mNetd = checkNotNull(netd, "missing INetworkManagementService");
336 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700337
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700338 try {
339 mPolicyManager.registerListener(mPolicyListener);
340 } catch (RemoteException e) {
341 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700342 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700343 }
344
345 final PowerManager powerManager = (PowerManager) context.getSystemService(
346 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700347 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
348 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
349 com.android.internal.R.integer.config_networkTransitionTimeout);
350
Robert Greenwalt2034b912009-08-12 16:08:25 -0700351 mNetTrackers = new NetworkStateTracker[
352 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700353 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700354
The Android Open Source Project28527d22009-03-03 19:31:44 -0800355 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700356
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700357 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700358 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700359
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361 String[] raStrings = context.getResources().getStringArray(
362 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 for (String raString : raStrings) {
364 RadioAttributes r = new RadioAttributes(raString);
365 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800366 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700367 continue;
368 }
369 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800370 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700371 r.mType);
372 continue;
373 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700374 mRadioAttributes[r.mType] = r;
375 }
376
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700377 String[] naStrings = context.getResources().getStringArray(
378 com.android.internal.R.array.networkAttributes);
379 for (String naString : naStrings) {
380 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700381 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700382 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800383 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700384 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700385 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700386 }
Wink Savillef2a62832011-04-07 14:23:45 -0700387 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800388 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700389 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700390 continue;
391 }
Wink Savillef2a62832011-04-07 14:23:45 -0700392 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800393 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700394 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700395 continue;
396 }
Wink Savillef2a62832011-04-07 14:23:45 -0700397 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700398 mNetworksDefined++;
399 } catch(Exception e) {
400 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700401 }
402 }
403
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700404 mProtectedNetworks = new ArrayList<Integer>();
405 int[] protectedNetworks = context.getResources().getIntArray(
406 com.android.internal.R.array.config_protectedNetworks);
407 for (int p : protectedNetworks) {
408 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
409 mProtectedNetworks.add(p);
410 } else {
411 if (DBG) loge("Ignoring protectedNetwork " + p);
412 }
413 }
414
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700415 // high priority first
416 mPriorityList = new int[mNetworksDefined];
417 {
418 int insertionPoint = mNetworksDefined-1;
419 int currentLowest = 0;
420 int nextLowest = 0;
421 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700422 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700423 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700424 if (na.priority < currentLowest) continue;
425 if (na.priority > currentLowest) {
426 if (na.priority < nextLowest || nextLowest == 0) {
427 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 }
429 continue;
430 }
Wink Savillef2a62832011-04-07 14:23:45 -0700431 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700432 }
433 currentLowest = nextLowest;
434 nextLowest = 0;
435 }
436 }
437
438 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
439 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700440 mNetRequestersPids[i] = new ArrayList();
441 }
442
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500443 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700444
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700445 mNumDnsEntries = 0;
446
447 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
448 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800449 /*
450 * Create the network state trackers for Wi-Fi and mobile
451 * data. Maybe this could be done with a factory class,
452 * but it's not clear that it's worth it, given that
453 * the number of different network types is not going
454 * to change very often.
455 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700457 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700458 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800459 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700460 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700461 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700463 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700464 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700465 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700466 break;
467 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700468 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700469 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700470 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700471 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800472 case ConnectivityManager.TYPE_DUMMY:
473 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700474 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800475 mNetTrackers[netType].startMonitoring(context, mHandler);
476 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800477 case ConnectivityManager.TYPE_BLUETOOTH:
478 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
479 mNetTrackers[netType].startMonitoring(context, mHandler);
480 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800481 case ConnectivityManager.TYPE_ETHERNET:
482 mNetTrackers[netType] = EthernetDataTracker.getInstance();
483 mNetTrackers[netType].startMonitoring(context, mHandler);
484 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700485 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800486 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700487 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700488 continue;
489 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700490 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700491 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700492 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800493
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700494 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
495 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
496
497 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700498 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700499 mTethering.getTetherableWifiRegexs().length != 0 ||
500 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700501 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800502
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700503 mVpn = new Vpn(mContext, new VpnCallback());
504
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700505 try {
506 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700507 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700508 } catch (RemoteException e) {
509 loge("Error registering observer :" + e);
510 }
511
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700512 if (DBG) {
513 mInetLog = new ArrayList();
514 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700515
516 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
517 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800518
519 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800520 }
521
522 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700523 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800524 * @param preference the new preference
525 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700526 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800527 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700528
529 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800530 }
531
532 public int getNetworkPreference() {
533 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700534 int preference;
535 synchronized(this) {
536 preference = mNetworkPreference;
537 }
538 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800539 }
540
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700541 private void handleSetNetworkPreference(int preference) {
542 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700543 mNetConfigs[preference] != null &&
544 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700545 if (mNetworkPreference != preference) {
546 final ContentResolver cr = mContext.getContentResolver();
547 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
548 synchronized(this) {
549 mNetworkPreference = preference;
550 }
551 enforcePreference();
552 }
553 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800554 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700555
Wink Saville4f0de1e2011-08-04 15:01:58 -0700556 private int getConnectivityChangeDelay() {
557 final ContentResolver cr = mContext.getContentResolver();
558
559 /** Check system properties for the default value then use secure settings value, if any. */
560 int defaultDelay = SystemProperties.getInt(
561 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
562 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
563 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
564 defaultDelay);
565 }
566
The Android Open Source Project28527d22009-03-03 19:31:44 -0800567 private int getPersistedNetworkPreference() {
568 final ContentResolver cr = mContext.getContentResolver();
569
570 final int networkPrefSetting = Settings.Secure
571 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
572 if (networkPrefSetting != -1) {
573 return networkPrefSetting;
574 }
575
576 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
577 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700578
The Android Open Source Project28527d22009-03-03 19:31:44 -0800579 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700580 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800581 * In this method, we only tear down a non-preferred network. Establishing
582 * a connection to the preferred network is taken care of when we handle
583 * the disconnect event from the non-preferred network
584 * (see {@link #handleDisconnect(NetworkInfo)}).
585 */
586 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700587 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800588 return;
589
Robert Greenwalt2034b912009-08-12 16:08:25 -0700590 if (!mNetTrackers[mNetworkPreference].isAvailable())
591 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800592
Robert Greenwalt2034b912009-08-12 16:08:25 -0700593 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700594 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700595 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700596 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800597 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700598 " in enforcePreference");
599 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700600 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800601 }
602 }
603 }
604
605 private boolean teardown(NetworkStateTracker netTracker) {
606 if (netTracker.teardown()) {
607 netTracker.setTeardownRequested(true);
608 return true;
609 } else {
610 return false;
611 }
612 }
613
614 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700615 * Check if UID should be blocked from using the network represented by the
616 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700617 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700618 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
619 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700620
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700621 final boolean networkCostly;
622 final int uidRules;
623 synchronized (mRulesLock) {
624 networkCostly = mMeteredIfaces.contains(iface);
625 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700626 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700627
628 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
629 return true;
630 }
631
632 // no restrictive rules; network is visible
633 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700634 }
635
636 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700637 * Return a filtered {@link NetworkInfo}, potentially marked
638 * {@link DetailedState#BLOCKED} based on
639 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700640 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700641 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
642 NetworkInfo info = tracker.getNetworkInfo();
643 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700644 // network is blocked; clone and override state
645 info = new NetworkInfo(info);
646 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700647 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700648 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700649 }
650
651 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800652 * Return NetworkInfo for the active (i.e., connected) network interface.
653 * It is assumed that at most one network is active at a time. If more
654 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700655 * @return the info for the active network, or {@code null} if none is
656 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800657 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700658 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800659 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700660 enforceAccessPermission();
661 final int uid = Binder.getCallingUid();
662 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800663 }
664
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700665 @Override
666 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
667 enforceConnectivityInternalPermission();
668 return getNetworkInfo(mActiveDefaultNetwork, uid);
669 }
670
671 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800672 public NetworkInfo getNetworkInfo(int networkType) {
673 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700674 final int uid = Binder.getCallingUid();
675 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800676 }
677
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700678 private NetworkInfo getNetworkInfo(int networkType, int uid) {
679 NetworkInfo info = null;
680 if (isNetworkTypeValid(networkType)) {
681 final NetworkStateTracker tracker = mNetTrackers[networkType];
682 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700683 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700684 }
685 }
686 return info;
687 }
688
689 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800690 public NetworkInfo[] getAllNetworkInfo() {
691 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700692 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700693 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700694 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700695 for (NetworkStateTracker tracker : mNetTrackers) {
696 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700697 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700698 }
699 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800700 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700701 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800702 }
703
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700704 /**
705 * Return LinkProperties for the active (i.e., connected) default
706 * network interface. It is assumed that at most one default network
707 * is active at a time. If more than one is active, it is indeterminate
708 * which will be returned.
709 * @return the ip properties for the active network, or {@code null} if
710 * none is active
711 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700712 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700713 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700714 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700715 }
716
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700717 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700718 public LinkProperties getLinkProperties(int networkType) {
719 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700720 if (isNetworkTypeValid(networkType)) {
721 final NetworkStateTracker tracker = mNetTrackers[networkType];
722 if (tracker != null) {
723 return tracker.getLinkProperties();
724 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700725 }
726 return null;
727 }
728
Jeff Sharkey21062e72011-05-28 20:56:34 -0700729 @Override
730 public NetworkState[] getAllNetworkState() {
731 enforceAccessPermission();
732 final int uid = Binder.getCallingUid();
733 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700734 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700735 for (NetworkStateTracker tracker : mNetTrackers) {
736 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700737 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700738 result.add(new NetworkState(
739 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
740 }
741 }
742 }
743 return result.toArray(new NetworkState[result.size()]);
744 }
745
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700746 private NetworkState getNetworkStateUnchecked(int networkType) {
747 if (isNetworkTypeValid(networkType)) {
748 final NetworkStateTracker tracker = mNetTrackers[networkType];
749 if (tracker != null) {
750 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
751 tracker.getLinkCapabilities());
752 }
753 }
754 return null;
755 }
756
757 @Override
758 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
759 enforceAccessPermission();
760 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
761 if (state != null) {
762 try {
763 return mPolicyManager.getNetworkQuotaInfo(state);
764 } catch (RemoteException e) {
765 }
766 }
767 return null;
768 }
769
The Android Open Source Project28527d22009-03-03 19:31:44 -0800770 public boolean setRadios(boolean turnOn) {
771 boolean result = true;
772 enforceChangePermission();
773 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700774 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800775 }
776 return result;
777 }
778
779 public boolean setRadio(int netType, boolean turnOn) {
780 enforceChangePermission();
781 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
782 return false;
783 }
784 NetworkStateTracker tracker = mNetTrackers[netType];
785 return tracker != null && tracker.setRadio(turnOn);
786 }
787
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700788 /**
789 * Used to notice when the calling process dies so we can self-expire
790 *
791 * Also used to know if the process has cleaned up after itself when
792 * our auto-expire timer goes off. The timer has a link to an object.
793 *
794 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700795 private class FeatureUser implements IBinder.DeathRecipient {
796 int mNetworkType;
797 String mFeature;
798 IBinder mBinder;
799 int mPid;
800 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800801 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700802
803 FeatureUser(int type, String feature, IBinder binder) {
804 super();
805 mNetworkType = type;
806 mFeature = feature;
807 mBinder = binder;
808 mPid = getCallingPid();
809 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800810 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700811
Robert Greenwalt2034b912009-08-12 16:08:25 -0700812 try {
813 mBinder.linkToDeath(this, 0);
814 } catch (RemoteException e) {
815 binderDied();
816 }
817 }
818
819 void unlinkDeathRecipient() {
820 mBinder.unlinkToDeath(this, 0);
821 }
822
823 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800824 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800825 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
826 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700827 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700828 }
829
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700830 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700831 if (VDBG) {
832 log("ConnectivityService FeatureUser expire(" +
833 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
834 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
835 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700836 stopUsingNetworkFeature(this, false);
837 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800838
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500839 public boolean isSameUser(FeatureUser u) {
840 if (u == null) return false;
841
842 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
843 }
844
845 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
846 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
847 TextUtils.equals(mFeature, feature)) {
848 return true;
849 }
850 return false;
851 }
852
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800853 public String toString() {
854 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
855 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
856 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700857 }
858
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700859 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700860 public int startUsingNetworkFeature(int networkType, String feature,
861 IBinder binder) {
862 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800863 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700864 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800865 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700866 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700867 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700868 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700870
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700871 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700872
873 // TODO - move this into the MobileDataStateTracker
874 int usedNetworkType = networkType;
875 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800876 usedNetworkType = convertFeatureToNetworkType(feature);
877 if (usedNetworkType < 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700878 loge("Can't match any netTracker!");
Wink Savillef6b76692011-02-24 17:58:51 -0800879 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700880 }
881 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700882
883 if (mProtectedNetworks.contains(usedNetworkType)) {
884 enforceConnectivityInternalPermission();
885 }
886
Robert Greenwalt2034b912009-08-12 16:08:25 -0700887 NetworkStateTracker network = mNetTrackers[usedNetworkType];
888 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800889 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700890 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700891 NetworkStateTracker radio = mNetTrackers[networkType];
892 NetworkInfo ni = network.getNetworkInfo();
893
894 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800895 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800896 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
897 return Phone.APN_TYPE_NOT_AVAILABLE;
898 } else {
899 // else make the attempt anyway - probably giving REQUEST_STARTED below
900 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700901 }
902
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500903 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
904
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700905 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500906 boolean addToList = true;
907 if (restoreTimer < 0) {
908 // In case there is no timer is specified for the feature,
909 // make sure we don't add duplicate entry with the same request.
910 for (FeatureUser u : mFeatureUsers) {
911 if (u.isSameUser(f)) {
912 // Duplicate user is found. Do not add.
913 addToList = false;
914 break;
915 }
916 }
917 }
918
919 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700920 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
921 // this gets used for per-pid dns when connected
922 mNetRequestersPids[usedNetworkType].add(currentPid);
923 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700924 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700925
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700926 if (restoreTimer >= 0) {
927 mHandler.sendMessageDelayed(
928 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
929 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700930
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700931 if ((ni.isConnectedOrConnecting() == true) &&
932 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700933 if (ni.isConnected() == true) {
934 // add the pid-specific dns
repo sync3035f652011-08-02 13:39:06 -0700935 handleDnsConfigurationChange(usedNetworkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800936 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700937 return Phone.APN_ALREADY_ACTIVE;
938 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800939 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700940 return Phone.APN_REQUEST_STARTED;
941 }
942
943 // check if the radio in play can make another contact
944 // assume if cannot for now
945
Wink Savillee70c6f52010-12-03 12:01:38 -0800946 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700947 network.reconnect();
948 return Phone.APN_REQUEST_STARTED;
949 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800950 // need to remember this unsupported request so we respond appropriately on stop
951 synchronized(this) {
952 mFeatureUsers.add(f);
953 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
954 // this gets used for per-pid dns when connected
955 mNetRequestersPids[usedNetworkType].add(currentPid);
956 }
957 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700958 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700959 }
960 }
961 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800962 }
963
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700964 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800965 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700966 enforceChangePermission();
967
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700968 int pid = getCallingPid();
969 int uid = getCallingUid();
970
971 FeatureUser u = null;
972 boolean found = false;
973
974 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500975 for (FeatureUser x : mFeatureUsers) {
976 if (x.isSameUser(pid, uid, networkType, feature)) {
977 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700978 found = true;
979 break;
980 }
981 }
982 }
983 if (found && u != null) {
984 // stop regardless of how many other time this proc had called start
985 return stopUsingNetworkFeature(u, true);
986 } else {
987 // none found!
Robert Greenwalt78f28112011-08-02 17:18:41 -0700988 if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700989 return 1;
990 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700991 }
992
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700993 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
994 int networkType = u.mNetworkType;
995 String feature = u.mFeature;
996 int pid = u.mPid;
997 int uid = u.mUid;
998
999 NetworkStateTracker tracker = null;
1000 boolean callTeardown = false; // used to carry our decision outside of sync block
1001
Robert Greenwalt2034b912009-08-12 16:08:25 -07001002 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001003 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001004 ": " + feature);
1005 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001006
The Android Open Source Project28527d22009-03-03 19:31:44 -08001007 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1008 return -1;
1009 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001010
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001011 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1012 // sync block
1013 synchronized(this) {
1014 // check if this process still has an outstanding start request
1015 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001016 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001017 return 1;
1018 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001019 u.unlinkDeathRecipient();
1020 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1021 // If we care about duplicate requests, check for that here.
1022 //
1023 // This is done to support the extension of a request - the app
1024 // can request we start the network feature again and renew the
1025 // auto-shutoff delay. Normal "stop" calls from the app though
1026 // do not pay attention to duplicate requests - in effect the
1027 // API does not refcount and a single stop will counter multiple starts.
1028 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001029 for (FeatureUser x : mFeatureUsers) {
1030 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001031 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001032 return 1;
1033 }
1034 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001035 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001036
1037 // TODO - move to MobileDataStateTracker
1038 int usedNetworkType = networkType;
1039 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -08001040 usedNetworkType = convertFeatureToNetworkType(feature);
1041 if (usedNetworkType < 0) {
1042 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001043 }
1044 }
1045 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001046 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001047 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001048 return -1;
1049 }
1050 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001051 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001052 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001053 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001054 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001055 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001056 "others still using it");
1057 return 1;
1058 }
1059 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001060 } else {
1061 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001062 }
1063 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001064 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001065 if (callTeardown) {
1066 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001067 return 1;
1068 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001069 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001070 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001071 }
1072
1073 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001074 * @deprecated use requestRouteToHostAddress instead
1075 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001076 * Ensure that a network route exists to deliver traffic to the specified
1077 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001078 * @param networkType the type of the network over which traffic to the
1079 * specified host is to be routed
1080 * @param hostAddress the IP address of the host to which the route is
1081 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001082 * @return {@code true} on success, {@code false} on failure
1083 */
1084 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001085 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1086
1087 if (inetAddress == null) {
1088 return false;
1089 }
1090
1091 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1092 }
1093
1094 /**
1095 * Ensure that a network route exists to deliver traffic to the specified
1096 * host via the specified network interface.
1097 * @param networkType the type of the network over which traffic to the
1098 * specified host is to be routed
1099 * @param hostAddress the IP address of the host to which the route is
1100 * desired
1101 * @return {@code true} on success, {@code false} on failure
1102 */
1103 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001104 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001105 if (mProtectedNetworks.contains(networkType)) {
1106 enforceConnectivityInternalPermission();
1107 }
1108
The Android Open Source Project28527d22009-03-03 19:31:44 -08001109 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1110 return false;
1111 }
1112 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001113
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001114 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1115 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001116 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001117 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001118 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001119 }
1120 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001121 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001122 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001123 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001124 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001125 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001126 } catch (UnknownHostException e) {}
1127 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001128 }
1129
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001130 private boolean addRoute(LinkProperties p, RouteInfo r) {
1131 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001132 }
1133
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001134 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1135 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1136 }
1137
Robert Greenwalt98107422011-07-22 11:55:33 -07001138 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1139 return modifyRouteToAddress(lp, addr, true);
1140 }
1141
1142 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1143 return modifyRouteToAddress(lp, addr, false);
1144 }
1145
1146 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1147 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1148 if (bestRoute == null) {
1149 bestRoute = RouteInfo.makeHostRoute(addr);
1150 } else {
1151 if (bestRoute.getGateway().equals(addr)) {
1152 // if there is no better route, add the implied hostroute for our gateway
1153 bestRoute = RouteInfo.makeHostRoute(addr);
1154 } else {
1155 // if we will connect to this through another route, add a direct route
1156 // to it's gateway
1157 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1158 }
1159 }
1160 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1161 }
1162
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001163 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1164 boolean doAdd) {
1165 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1166
1167 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1168 loge("Error adding route - too much recursion");
1169 return false;
1170 }
1171
1172 if (r.isHostRoute() == false) {
1173 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1174 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001175 if (bestRoute.getGateway().equals(r.getGateway())) {
1176 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001177 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001178 } else {
1179 // if we will connect to our gateway through another route, add a direct
1180 // route to it's gateway
1181 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001182 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001183 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001184 }
1185 }
1186 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001187 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001188 mAddedRoutes.add(r);
1189 try {
1190 mNetd.addRoute(ifaceName, r);
1191 } catch (Exception e) {
1192 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001193 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001194 return false;
1195 }
1196 } else {
1197 // if we remove this one and there are no more like it, then refcount==0 and
1198 // we can remove it from the table
1199 mAddedRoutes.remove(r);
1200 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001201 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001202 try {
1203 mNetd.removeRoute(ifaceName, r);
1204 } catch (Exception e) {
1205 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001206 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001207 return false;
1208 }
1209 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001210 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001211 }
1212 }
1213 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001214 }
1215
1216 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001217 * @see ConnectivityManager#getMobileDataEnabled()
1218 */
1219 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001220 // TODO: This detail should probably be in DataConnectionTracker's
1221 // which is where we store the value and maybe make this
1222 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001223 enforceAccessPermission();
1224 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1225 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001226 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001227 return retVal;
1228 }
1229
Robert Greenwalt34848c02011-03-25 13:09:25 -07001230 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001231 enforceConnectivityInternalPermission();
1232
Robert Greenwalt34848c02011-03-25 13:09:25 -07001233 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1234 (met ? ENABLED : DISABLED), networkType));
1235 }
1236
1237 private void handleSetDependencyMet(int networkType, boolean met) {
1238 if (mNetTrackers[networkType] != null) {
1239 if (DBG) {
1240 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1241 }
1242 mNetTrackers[networkType].setDependencyMet(met);
1243 }
1244 }
1245
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001246 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1247 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001248 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001249 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001250 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001251
1252 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001253 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001254 }
1255
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001256 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001257 // skip update when we've already applied rules
1258 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1259 if (oldRules == uidRules) return;
1260
1261 mUidRules.put(uid, uidRules);
1262 }
1263
1264 // TODO: dispatch into NMS to push rules towards kernel module
1265 // TODO: notify UID when it has requested targeted updates
1266 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001267
1268 @Override
1269 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1270 // only someone like NPMS should only be calling us
1271 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1272
1273 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001274 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001275 }
1276
1277 synchronized (mRulesLock) {
1278 mMeteredIfaces.clear();
1279 for (String iface : meteredIfaces) {
1280 mMeteredIfaces.add(iface);
1281 }
1282 }
1283 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001284 };
1285
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001286 /**
1287 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1288 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001289 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001290 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001291 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001292
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001293 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001294 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001295 }
1296
1297 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001298 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001299 if (VDBG) {
1300 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001301 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001302 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001303 }
1304 }
1305
The Android Open Source Project28527d22009-03-03 19:31:44 -08001306 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001307 mContext.enforceCallingOrSelfPermission(
1308 android.Manifest.permission.ACCESS_NETWORK_STATE,
1309 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001310 }
1311
1312 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001313 mContext.enforceCallingOrSelfPermission(
1314 android.Manifest.permission.CHANGE_NETWORK_STATE,
1315 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001316 }
1317
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001318 // TODO Make this a special check when it goes public
1319 private void enforceTetherChangePermission() {
1320 mContext.enforceCallingOrSelfPermission(
1321 android.Manifest.permission.CHANGE_NETWORK_STATE,
1322 "ConnectivityService");
1323 }
1324
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001325 private void enforceTetherAccessPermission() {
1326 mContext.enforceCallingOrSelfPermission(
1327 android.Manifest.permission.ACCESS_NETWORK_STATE,
1328 "ConnectivityService");
1329 }
1330
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001331 private void enforceConnectivityInternalPermission() {
1332 mContext.enforceCallingOrSelfPermission(
1333 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1334 "ConnectivityService");
1335 }
1336
The Android Open Source Project28527d22009-03-03 19:31:44 -08001337 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001338 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1339 * network, we ignore it. If it is for the active network, we send out a
1340 * broadcast. But first, we check whether it might be possible to connect
1341 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001342 * @param info the {@code NetworkInfo} for the network
1343 */
1344 private void handleDisconnect(NetworkInfo info) {
1345
Robert Greenwalt2034b912009-08-12 16:08:25 -07001346 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001347
Robert Greenwalt2034b912009-08-12 16:08:25 -07001348 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001349 /*
1350 * If the disconnected network is not the active one, then don't report
1351 * this as a loss of connectivity. What probably happened is that we're
1352 * getting the disconnect for a network that we explicitly disabled
1353 * in accordance with network preference policies.
1354 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001355 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001356 List pids = mNetRequestersPids[prevNetType];
1357 for (int i = 0; i<pids.size(); i++) {
1358 Integer pid = (Integer)pids.get(i);
1359 // will remove them because the net's no longer connected
1360 // need to do this now as only now do we know the pids and
1361 // can properly null things that are no longer referenced.
1362 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001363 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001364 }
1365
The Android Open Source Project28527d22009-03-03 19:31:44 -08001366 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1367 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1368 if (info.isFailover()) {
1369 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1370 info.setFailover(false);
1371 }
1372 if (info.getReason() != null) {
1373 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1374 }
1375 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001376 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1377 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001378 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001379
Robert Greenwalt34848c02011-03-25 13:09:25 -07001380 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001381 tryFailover(prevNetType);
1382 if (mActiveDefaultNetwork != -1) {
1383 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001384 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1385 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001386 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001387 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1388 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001389 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001390 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001391
1392 // Reset interface if no other connections are using the same interface
1393 boolean doReset = true;
1394 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1395 if (linkProperties != null) {
1396 String oldIface = linkProperties.getInterfaceName();
1397 if (TextUtils.isEmpty(oldIface) == false) {
1398 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1399 if (networkStateTracker == null) continue;
1400 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1401 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1402 LinkProperties l = networkStateTracker.getLinkProperties();
1403 if (l == null) continue;
1404 if (oldIface.equals(l.getInterfaceName())) {
1405 doReset = false;
1406 break;
1407 }
1408 }
1409 }
1410 }
1411 }
1412
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001413 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001414 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001415
Wink Saville4f0de1e2011-08-04 15:01:58 -07001416 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001417 /*
1418 * If the failover network is already connected, then immediately send
1419 * out a followup broadcast indicating successful failover
1420 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001421 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001422 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1423 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001424 }
1425 }
1426
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001427 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001428 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001429 * If this is a default network, check if other defaults are available.
1430 * Try to reconnect on all available and let them hash it out when
1431 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001432 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001433 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001434 if (mActiveDefaultNetwork == prevNetType) {
1435 mActiveDefaultNetwork = -1;
1436 }
1437
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001438 // don't signal a reconnect for anything lower or equal priority than our
1439 // current connected default
1440 // TODO - don't filter by priority now - nice optimization but risky
1441// int currentPriority = -1;
1442// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001443// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001444// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001445 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001446 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001447 if (mNetConfigs[checkType] == null) continue;
1448 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001449
1450// Enabling the isAvailable() optimization caused mobile to not get
1451// selected if it was in the middle of error handling. Specifically
1452// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1453// would not be available and we wouldn't get connected to anything.
1454// So removing the isAvailable() optimization below for now. TODO: This
1455// optimization should work and we need to investigate why it doesn't work.
1456// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1457// complete before it is really complete.
1458// if (!mNetTrackers[checkType].isAvailable()) continue;
1459
Robert Greenwalt34848c02011-03-25 13:09:25 -07001460// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001461
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001462 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1463 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1464 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1465 checkInfo.setFailover(true);
1466 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001467 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001468 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001469 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001470 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001471 }
1472
1473 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001474 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1475 }
1476
Wink Saville4f0de1e2011-08-04 15:01:58 -07001477 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1478 sendGeneralBroadcastDelayed(info, ConnectivityManager.CONNECTIVITY_ACTION, delayMs);
1479 }
1480
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001481 private void sendInetConditionBroadcast(NetworkInfo info) {
1482 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1483 }
1484
Wink Saville4f0de1e2011-08-04 15:01:58 -07001485 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001486 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001487 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1488 if (info.isFailover()) {
1489 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1490 info.setFailover(false);
1491 }
1492 if (info.getReason() != null) {
1493 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1494 }
1495 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001496 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1497 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001498 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001499 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001500 return intent;
1501 }
1502
1503 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1504 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1505 }
1506
1507 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1508 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 }
1510
1511 /**
1512 * Called when an attempt to fail over to another network has failed.
1513 * @param info the {@link NetworkInfo} for the failed network
1514 */
1515 private void handleConnectionFailure(NetworkInfo info) {
1516 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001517
Robert Greenwalt2034b912009-08-12 16:08:25 -07001518 String reason = info.getReason();
1519 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001520
Robert Greenwalte981bc52010-10-08 16:35:52 -07001521 String reasonText;
1522 if (reason == null) {
1523 reasonText = ".";
1524 } else {
1525 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001526 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001527 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001528
1529 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1530 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1531 if (getActiveNetworkInfo() == null) {
1532 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1533 }
1534 if (reason != null) {
1535 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1536 }
1537 if (extraInfo != null) {
1538 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1539 }
1540 if (info.isFailover()) {
1541 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1542 info.setFailover(false);
1543 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001544
Robert Greenwalt34848c02011-03-25 13:09:25 -07001545 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001546 tryFailover(info.getType());
1547 if (mActiveDefaultNetwork != -1) {
1548 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001549 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1550 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001551 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001552 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1553 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001554 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001555
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001556 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001557 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001558 /*
1559 * If the failover network is already connected, then immediately send
1560 * out a followup broadcast indicating successful failover
1561 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001562 if (mActiveDefaultNetwork != -1) {
1563 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001564 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001565 }
1566
1567 private void sendStickyBroadcast(Intent intent) {
1568 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001569 if (!mSystemReady) {
1570 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001571 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001572 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001573 if (DBG) {
1574 log("sendStickyBroadcast: NetworkInfo=" +
1575 intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
1576 }
1577
Dianne Hackborna417ff82009-12-08 19:45:14 -08001578 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001579 }
1580 }
1581
Wink Saville4f0de1e2011-08-04 15:01:58 -07001582 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1583 if (delayMs <= 0) {
1584 sendStickyBroadcast(intent);
1585 } else {
1586 if (DBG) log("sendStickyBroadcastDelayed: delayMs=" + delayMs + " intent=" + intent);
1587 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1588 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1589 }
1590 }
1591
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001592 void systemReady() {
1593 synchronized(this) {
1594 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001595 if (mInitialBroadcast != null) {
1596 mContext.sendStickyBroadcast(mInitialBroadcast);
1597 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001598 }
1599 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001600 // load the global proxy at startup
1601 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001602 }
1603
1604 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001605 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001606
1607 // snapshot isFailover, because sendConnectedBroadcast() resets it
1608 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001609 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001610
Robert Greenwalt2034b912009-08-12 16:08:25 -07001611 // if this is a default net and other default is running
1612 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001613 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001614 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1615 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001616 mNetConfigs[mActiveDefaultNetwork].priority >
1617 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001618 mNetworkPreference == mActiveDefaultNetwork) {
1619 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001620 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001621 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001622 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001623 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001624 teardown(thisNet);
1625 return;
1626 } else {
1627 // tear down the other
1628 NetworkStateTracker otherNet =
1629 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001630 if (DBG) {
1631 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001632 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001633 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001634 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001635 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001636 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001637 return;
1638 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001639 }
1640 }
1641 synchronized (ConnectivityService.this) {
1642 // have a new default network, release the transition wakelock in a second
1643 // if it's held. The second pause is to allow apps to reconnect over the
1644 // new network
1645 if (mNetTransitionWakeLock.isHeld()) {
1646 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001647 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001648 mNetTransitionWakeLockSerialNumber, 0),
1649 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001650 }
1651 }
1652 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001653 // this will cause us to come up initially as unconnected and switching
1654 // to connected after our normal pause unless somebody reports us as reall
1655 // disconnected
1656 mDefaultInetConditionPublished = 0;
1657 mDefaultConnectionSequence++;
1658 mInetConditionChangeInFlight = false;
1659 // Don't do this - if we never sign in stay, grey
1660 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001661 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001662 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001663 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001664 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001665 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001666 }
1667
The Android Open Source Project28527d22009-03-03 19:31:44 -08001668 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001669 * After a change in the connectivity state of a network. We're mainly
1670 * concerned with making sure that the list of DNS servers is set up
1671 * according to which networks are connected, and ensuring that the
1672 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001673 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001674 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001675 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1676
The Android Open Source Project28527d22009-03-03 19:31:44 -08001677 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001678 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001679 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001680 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001681 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001682
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001683 LinkProperties curLp = mCurrentLinkProperties[netType];
1684 LinkProperties newLp = null;
1685
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001686 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001687 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001688 if (VDBG) {
1689 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1690 " doReset=" + doReset + " resetMask=" + resetMask +
1691 "\n curLp=" + curLp +
1692 "\n newLp=" + newLp);
1693 }
1694
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001695 if (curLp != null) {
1696 if (curLp.isIdenticalInterfaceName(newLp)) {
1697 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1698 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1699 for (LinkAddress linkAddr : car.removed) {
1700 if (linkAddr.getAddress() instanceof Inet4Address) {
1701 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1702 }
1703 if (linkAddr.getAddress() instanceof Inet6Address) {
1704 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1705 }
Wink Saville051a6642011-07-13 13:44:13 -07001706 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001707 if (DBG) {
1708 log("handleConnectivityChange: addresses changed" +
1709 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1710 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001711 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001712 } else {
1713 if (DBG) {
1714 log("handleConnectivityChange: address are the same reset per doReset" +
1715 " linkProperty[" + netType + "]:" +
1716 " resetMask=" + resetMask);
1717 }
Wink Saville051a6642011-07-13 13:44:13 -07001718 }
1719 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001720 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001721 if (DBG) {
1722 log("handleConnectivityChange: interface not not equivalent reset both" +
1723 " linkProperty[" + netType + "]:" +
1724 " resetMask=" + resetMask);
1725 }
Wink Saville051a6642011-07-13 13:44:13 -07001726 }
Wink Saville051a6642011-07-13 13:44:13 -07001727 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001728 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001729 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001730 }
1731 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001732 if (VDBG) {
1733 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1734 " doReset=" + doReset + " resetMask=" + resetMask +
1735 "\n curLp=" + curLp +
1736 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001737 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001738 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001739 mCurrentLinkProperties[netType] = newLp;
1740 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001741
Wink Saville051a6642011-07-13 13:44:13 -07001742 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001743 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1744 if (linkProperties != null) {
1745 String iface = linkProperties.getInterfaceName();
1746 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001747 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1748 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001749 }
1750 }
1751 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001752
1753 // TODO: Temporary notifying upstread change to Tethering.
1754 // @see bug/4455071
1755 /** Notify TetheringService if interface name has been changed. */
1756 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1757 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1758 if (isTetheringSupported()) {
1759 mTethering.handleTetherIfaceChange();
1760 }
1761 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001762 }
1763
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001764 /**
1765 * Add and remove routes using the old properties (null if not previously connected),
1766 * new properties (null if becoming disconnected). May even be double null, which
1767 * is a noop.
1768 * Uses isLinkDefault to determine if default routes should be set or conversely if
1769 * host routes should be set to the dns servers
1770 */
1771 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1772 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001773 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1774 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001775 if (curLp != null) {
1776 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001777 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001778 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001779 } else if (newLp != null) {
1780 routeDiff.added = newLp.getRoutes();
1781 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001782 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001783
Robert Greenwalt98107422011-07-22 11:55:33 -07001784 for (RouteInfo r : routeDiff.removed) {
1785 if (isLinkDefault || ! r.isDefaultRoute()) {
1786 removeRoute(curLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001787 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001788 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001789
Robert Greenwalt98107422011-07-22 11:55:33 -07001790 for (RouteInfo r : routeDiff.added) {
1791 if (isLinkDefault || ! r.isDefaultRoute()) {
1792 addRoute(newLp, r);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001793 } else {
1794 // many radios add a default route even when we don't want one.
1795 // remove the default route unless somebody else has asked for it
1796 String ifaceName = newLp.getInterfaceName();
1797 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
1798 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1799 try {
1800 mNetd.removeRoute(ifaceName, r);
1801 } catch (Exception e) {
1802 // never crash - catch them all
1803 loge("Exception trying to remove a route: " + e);
1804 }
1805 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001806 }
1807 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001808
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001809 if (!isLinkDefault) {
1810 // handle DNS routes
Robert Greenwalt98107422011-07-22 11:55:33 -07001811 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1812 // no change in routes, check for change in dns themselves
1813 for (InetAddress oldDns : dnsDiff.removed) {
1814 removeRouteToAddress(curLp, oldDns);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001815 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001816 for (InetAddress newDns : dnsDiff.added) {
1817 addRouteToAddress(newLp, newDns);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001818 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001819 } else {
1820 // routes changed - remove all old dns entries and add new
1821 if (curLp != null) {
1822 for (InetAddress oldDns : curLp.getDnses()) {
1823 removeRouteToAddress(curLp, oldDns);
1824 }
1825 }
1826 if (newLp != null) {
1827 for (InetAddress newDns : newLp.getDnses()) {
1828 addRouteToAddress(newLp, newDns);
1829 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001830 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001831 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001832 }
1833 }
1834
1835
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001836 /**
1837 * Reads the network specific TCP buffer sizes from SystemProperties
1838 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1839 * wide use
1840 */
1841 public void updateNetworkSettings(NetworkStateTracker nt) {
1842 String key = nt.getTcpBufferSizesPropName();
1843 String bufferSizes = SystemProperties.get(key);
1844
1845 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001846 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001847
1848 // Setting to default values so we won't be stuck to previous values
1849 key = "net.tcp.buffersize.default";
1850 bufferSizes = SystemProperties.get(key);
1851 }
1852
1853 // Set values in kernel
1854 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001855 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001856 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001857 + "] which comes from [" + key + "]");
1858 }
1859 setBufferSize(bufferSizes);
1860 }
1861 }
1862
1863 /**
1864 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1865 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1866 *
1867 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1868 * writeMin, writeInitial, writeMax"
1869 */
1870 private void setBufferSize(String bufferSizes) {
1871 try {
1872 String[] values = bufferSizes.split(",");
1873
1874 if (values.length == 6) {
1875 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001876 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1877 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1878 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1879 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1880 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1881 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001882 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001883 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001884 }
1885 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001886 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001887 }
1888 }
1889
Robert Greenwalt2034b912009-08-12 16:08:25 -07001890 /**
1891 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1892 * on the highest priority active net which this process requested.
1893 * If there aren't any, clear it out
1894 */
1895 private void reassessPidDns(int myPid, boolean doBump)
1896 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001897 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001898 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001899 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001900 continue;
1901 }
1902 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001903 if (nt.getNetworkInfo().isConnected() &&
1904 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001905 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001906 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001907 List pids = mNetRequestersPids[i];
1908 for (int j=0; j<pids.size(); j++) {
1909 Integer pid = (Integer)pids.get(j);
1910 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001911 Collection<InetAddress> dnses = p.getDnses();
1912 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001913 if (doBump) {
1914 bumpDns();
1915 }
1916 return;
1917 }
1918 }
1919 }
1920 }
1921 // nothing found - delete
1922 for (int i = 1; ; i++) {
1923 String prop = "net.dns" + i + "." + myPid;
1924 if (SystemProperties.get(prop).length() == 0) {
1925 if (doBump) {
1926 bumpDns();
1927 }
1928 return;
1929 }
1930 SystemProperties.set(prop, "");
1931 }
1932 }
1933
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001934 // return true if results in a change
1935 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001936 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001937 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001938 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001939 String dnsString = dns.getHostAddress();
1940 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1941 changed = true;
1942 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1943 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001944 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001945 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001946 }
1947
1948 private void bumpDns() {
1949 /*
1950 * Bump the property that tells the name resolver library to reread
1951 * the DNS server list from the properties.
1952 */
1953 String propVal = SystemProperties.get("net.dnschange");
1954 int n = 0;
1955 if (propVal.length() != 0) {
1956 try {
1957 n = Integer.parseInt(propVal);
1958 } catch (NumberFormatException e) {}
1959 }
1960 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001961 /*
1962 * Tell the VMs to toss their DNS caches
1963 */
1964 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1965 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001966 /*
1967 * Connectivity events can happen before boot has completed ...
1968 */
1969 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001970 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001971 }
1972
Chia-chi Yehcc844502011-07-14 18:01:57 -07001973 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07001974 private boolean updateDns(String network, String iface,
1975 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07001976 boolean changed = false;
1977 int last = 0;
1978 if (dnses.size() == 0 && mDefaultDns != null) {
1979 ++last;
1980 String value = mDefaultDns.getHostAddress();
1981 if (!value.equals(SystemProperties.get("net.dns1"))) {
1982 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001983 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07001984 }
1985 changed = true;
1986 SystemProperties.set("net.dns1", value);
1987 }
1988 } else {
1989 for (InetAddress dns : dnses) {
1990 ++last;
1991 String key = "net.dns" + last;
1992 String value = dns.getHostAddress();
1993 if (!changed && value.equals(SystemProperties.get(key))) {
1994 continue;
1995 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07001996 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07001997 log("adding dns " + value + " for " + network);
1998 }
1999 changed = true;
2000 SystemProperties.set(key, value);
2001 }
2002 }
2003 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2004 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002005 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002006 changed = true;
2007 SystemProperties.set(key, "");
2008 }
2009 mNumDnsEntries = last;
2010
Robert Greenwaltfce71862011-07-25 16:06:25 -07002011 if (changed) {
2012 try {
2013 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2014 mNetd.setDefaultInterfaceForDns(iface);
2015 } catch (Exception e) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002016 loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002017 }
2018 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002019 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2020 SystemProperties.set("net.dns.search", domains);
2021 changed = true;
2022 }
2023 return changed;
2024 }
2025
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002026 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002027 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002028 NetworkStateTracker nt = mNetTrackers[netType];
2029 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002030 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002031 if (p == null) return;
2032 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002033 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002034 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002035 String network = nt.getNetworkInfo().getTypeName();
2036 synchronized (mDnsLock) {
2037 if (!mDnsOverridden) {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002038 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002039 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002040 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002041 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002042 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002043 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002044 NetworkUtils.makeStrings(dnses));
2045 } catch (Exception e) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002046 loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002047 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002048 // set per-pid dns for attached secondary nets
2049 List pids = mNetRequestersPids[netType];
2050 for (int y=0; y< pids.size(); y++) {
2051 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002052 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002053 }
2054 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002055 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002056 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002057 }
2058
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002059 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002060 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2061 NETWORK_RESTORE_DELAY_PROP_NAME);
2062 if(restoreDefaultNetworkDelayStr != null &&
2063 restoreDefaultNetworkDelayStr.length() != 0) {
2064 try {
2065 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2066 } catch (NumberFormatException e) {
2067 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002068 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002069 // if the system property isn't set, use the value for the apn type
2070 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2071
2072 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2073 (mNetConfigs[networkType] != null)) {
2074 ret = mNetConfigs[networkType].restoreTime;
2075 }
2076 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002077 }
2078
2079 @Override
2080 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002081 if (mContext.checkCallingOrSelfPermission(
2082 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002083 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002084 pw.println("Permission Denial: can't dump ConnectivityService " +
2085 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2086 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002087 return;
2088 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002089 pw.println();
2090 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002091 if (nst != null) {
2092 if (nst.getNetworkInfo().isConnected()) {
2093 pw.println("Active network: " + nst.getNetworkInfo().
2094 getTypeName());
2095 }
2096 pw.println(nst.getNetworkInfo());
2097 pw.println(nst);
2098 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002099 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002101
2102 pw.println("Network Requester Pids:");
2103 for (int net : mPriorityList) {
2104 String pidString = net + ": ";
2105 for (Object pid : mNetRequestersPids[net]) {
2106 pidString = pidString + pid.toString() + ", ";
2107 }
2108 pw.println(pidString);
2109 }
2110 pw.println();
2111
2112 pw.println("FeatureUsers:");
2113 for (Object requester : mFeatureUsers) {
2114 pw.println(requester.toString());
2115 }
2116 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002117
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002118 synchronized (this) {
2119 pw.println("NetworkTranstionWakeLock is currently " +
2120 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2121 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2122 }
2123 pw.println();
2124
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002125 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002126
2127 if (mInetLog != null) {
2128 pw.println();
2129 pw.println("Inet condition reports:");
2130 for(int i = 0; i < mInetLog.size(); i++) {
2131 pw.println(mInetLog.get(i));
2132 }
2133 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 }
2135
Robert Greenwalt2034b912009-08-12 16:08:25 -07002136 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002138 public MyHandler(Looper looper) {
2139 super(looper);
2140 }
2141
The Android Open Source Project28527d22009-03-03 19:31:44 -08002142 @Override
2143 public void handleMessage(Message msg) {
2144 NetworkInfo info;
2145 switch (msg.what) {
2146 case NetworkStateTracker.EVENT_STATE_CHANGED:
2147 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002148 int type = info.getType();
2149 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002150
Wink Savillee70c6f52010-12-03 12:01:38 -08002151 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002152 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002153 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154
2155 // Connectivity state changed:
2156 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002157 // [12-9] Network subtype (for mobile network, as defined
2158 // by TelephonyManager)
2159 // [8-3] Detailed state ordinal (as defined by
2160 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 // [2-0] Network type (as defined by ConnectivityManager)
2162 int eventLogParam = (info.getType() & 0x7) |
2163 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2164 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002165 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002166 eventLogParam);
2167
2168 if (info.getDetailedState() ==
2169 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002171 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002172 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002173 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002175 // the logic here is, handle SUSPENDED the same as
2176 // DISCONNECTED. The only difference being we are
2177 // broadcasting an intent with NetworkInfo that's
2178 // suspended. This allows the applications an
2179 // opportunity to handle DISCONNECTED and SUSPENDED
2180 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002181 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002182 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002183 handleConnect(info);
2184 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002185 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002187 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002188 // TODO: Temporary allowing network configuration
2189 // change not resetting sockets.
2190 // @see bug/4455071
2191 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002192 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002193 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002194 String causedBy = null;
2195 synchronized (ConnectivityService.this) {
2196 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2197 mNetTransitionWakeLock.isHeld()) {
2198 mNetTransitionWakeLock.release();
2199 causedBy = mNetTransitionWakeLockCausedBy;
2200 }
2201 }
2202 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002203 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002204 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002205 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002206 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002207 FeatureUser u = (FeatureUser)msg.obj;
2208 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002209 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002210 case EVENT_INET_CONDITION_CHANGE:
2211 {
2212 int netType = msg.arg1;
2213 int condition = msg.arg2;
2214 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002215 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002216 }
2217 case EVENT_INET_CONDITION_HOLD_END:
2218 {
2219 int netType = msg.arg1;
2220 int sequence = msg.arg2;
2221 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002222 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002223 }
2224 case EVENT_SET_NETWORK_PREFERENCE:
2225 {
2226 int preference = msg.arg1;
2227 handleSetNetworkPreference(preference);
2228 break;
2229 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002230 case EVENT_SET_MOBILE_DATA:
2231 {
2232 boolean enabled = (msg.arg1 == ENABLED);
2233 handleSetMobileData(enabled);
2234 break;
2235 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002236 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2237 {
2238 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002239 break;
2240 }
2241 case EVENT_SET_DEPENDENCY_MET:
2242 {
2243 boolean met = (msg.arg1 == ENABLED);
2244 handleSetDependencyMet(msg.arg2, met);
2245 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002246 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002247 case EVENT_RESTORE_DNS:
2248 {
2249 if (mActiveDefaultNetwork != -1) {
2250 handleDnsConfigurationChange(mActiveDefaultNetwork);
2251 }
2252 break;
2253 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002254 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2255 {
2256 Intent intent = (Intent)msg.obj;
2257 log("EVENT_SEND_STICKY_BROADCAST_INTENT: sendStickyBroadcast intent=" + intent);
2258 sendStickyBroadcast(intent);
2259 break;
2260 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002261 }
2262 }
2263 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002264
2265 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002266 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002267 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002268
2269 if (isTetheringSupported()) {
2270 return mTethering.tether(iface);
2271 } else {
2272 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2273 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002274 }
2275
2276 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002277 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002278 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002279
2280 if (isTetheringSupported()) {
2281 return mTethering.untether(iface);
2282 } else {
2283 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2284 }
2285 }
2286
2287 // javadoc from interface
2288 public int getLastTetherError(String iface) {
2289 enforceTetherAccessPermission();
2290
2291 if (isTetheringSupported()) {
2292 return mTethering.getLastTetherError(iface);
2293 } else {
2294 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2295 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002296 }
2297
2298 // TODO - proper iface API for selection by property, inspection, etc
2299 public String[] getTetherableUsbRegexs() {
2300 enforceTetherAccessPermission();
2301 if (isTetheringSupported()) {
2302 return mTethering.getTetherableUsbRegexs();
2303 } else {
2304 return new String[0];
2305 }
2306 }
2307
2308 public String[] getTetherableWifiRegexs() {
2309 enforceTetherAccessPermission();
2310 if (isTetheringSupported()) {
2311 return mTethering.getTetherableWifiRegexs();
2312 } else {
2313 return new String[0];
2314 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002315 }
2316
Danica Chang96567052010-08-11 14:54:43 -07002317 public String[] getTetherableBluetoothRegexs() {
2318 enforceTetherAccessPermission();
2319 if (isTetheringSupported()) {
2320 return mTethering.getTetherableBluetoothRegexs();
2321 } else {
2322 return new String[0];
2323 }
2324 }
2325
Mike Lockwooded4a1742011-07-19 13:04:47 -07002326 public int setUsbTethering(boolean enable) {
2327 enforceTetherAccessPermission();
2328 if (isTetheringSupported()) {
2329 return mTethering.setUsbTethering(enable);
2330 } else {
2331 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2332 }
2333 }
2334
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002335 // TODO - move iface listing, queries, etc to new module
2336 // javadoc from interface
2337 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002338 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002339 return mTethering.getTetherableIfaces();
2340 }
2341
2342 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002343 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002344 return mTethering.getTetheredIfaces();
2345 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002346
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002347 public String[] getTetheringErroredIfaces() {
2348 enforceTetherAccessPermission();
2349 return mTethering.getErroredIfaces();
2350 }
2351
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002352 // if ro.tether.denied = true we default to no tethering
2353 // gservices could set the secure setting to 1 though to enable it on a build where it
2354 // had previously been turned off.
2355 public boolean isTetheringSupported() {
2356 enforceTetherAccessPermission();
2357 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002358 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2359 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2360 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002361 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002362
2363 // An API NetworkStateTrackers can call when they lose their network.
2364 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2365 // whichever happens first. The timer is started by the first caller and not
2366 // restarted by subsequent callers.
2367 public void requestNetworkTransitionWakelock(String forWhom) {
2368 enforceConnectivityInternalPermission();
2369 synchronized (this) {
2370 if (mNetTransitionWakeLock.isHeld()) return;
2371 mNetTransitionWakeLockSerialNumber++;
2372 mNetTransitionWakeLock.acquire();
2373 mNetTransitionWakeLockCausedBy = forWhom;
2374 }
2375 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002376 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002377 mNetTransitionWakeLockSerialNumber, 0),
2378 mNetTransitionWakeLockTimeout);
2379 return;
2380 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002381
Robert Greenwalt986c7412010-09-08 15:24:47 -07002382 // 100 percent is full good, 0 is full bad.
2383 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002384 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002385 mContext.enforceCallingOrSelfPermission(
2386 android.Manifest.permission.STATUS_BAR,
2387 "ConnectivityService");
2388
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002389 if (DBG) {
2390 int pid = getCallingPid();
2391 int uid = getCallingUid();
2392 String s = pid + "(" + uid + ") reports inet is " +
2393 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2394 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2395 mInetLog.add(s);
2396 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2397 mInetLog.remove(0);
2398 }
2399 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002400 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002401 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2402 }
2403
2404 private void handleInetConditionChange(int netType, int condition) {
2405 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002406 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002407 netType + ", condition=" + condition +
2408 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2409 }
2410 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002411 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002412 return;
2413 }
2414 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002415 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002416 return;
2417 }
2418 mDefaultInetCondition = condition;
2419 int delay;
2420 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002421 if (VDBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002422 // setup a new hold to debounce this
2423 if (mDefaultInetCondition > 50) {
2424 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2425 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2426 } else {
2427 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2428 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2429 }
2430 mInetConditionChangeInFlight = true;
2431 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2432 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2433 } else {
2434 // we've set the new condition, when this hold ends that will get
2435 // picked up
Robert Greenwalt78f28112011-08-02 17:18:41 -07002436 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002437 }
2438 }
2439
2440 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002441 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002442 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002443 ", condition =" + mDefaultInetCondition +
2444 ", published condition =" + mDefaultInetConditionPublished);
2445 }
2446 mInetConditionChangeInFlight = false;
2447
2448 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002449 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002450 return;
2451 }
2452 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002453 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002454 return;
2455 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002456 // TODO: Figure out why this optimization sometimes causes a
2457 // change in mDefaultInetCondition to be missed and the
2458 // UI to not be updated.
2459 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2460 // if (DBG) log("no change in condition - aborting");
2461 // return;
2462 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002463 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2464 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002465 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002466 return;
2467 }
2468 mDefaultInetConditionPublished = mDefaultInetCondition;
2469 sendInetConditionBroadcast(networkInfo);
2470 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002471 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002472
2473 public synchronized ProxyProperties getProxy() {
2474 if (mGlobalProxy != null) return mGlobalProxy;
2475 if (mDefaultProxy != null) return mDefaultProxy;
2476 return null;
2477 }
2478
2479 public void setGlobalProxy(ProxyProperties proxyProperties) {
2480 enforceChangePermission();
2481 synchronized (mGlobalProxyLock) {
2482 if (proxyProperties == mGlobalProxy) return;
2483 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2484 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2485
2486 String host = "";
2487 int port = 0;
2488 String exclList = "";
2489 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2490 mGlobalProxy = new ProxyProperties(proxyProperties);
2491 host = mGlobalProxy.getHost();
2492 port = mGlobalProxy.getPort();
2493 exclList = mGlobalProxy.getExclusionList();
2494 } else {
2495 mGlobalProxy = null;
2496 }
2497 ContentResolver res = mContext.getContentResolver();
2498 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2499 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002500 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002501 exclList);
2502 }
2503
2504 if (mGlobalProxy == null) {
2505 proxyProperties = mDefaultProxy;
2506 }
2507 sendProxyBroadcast(proxyProperties);
2508 }
2509
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002510 private void loadGlobalProxy() {
2511 ContentResolver res = mContext.getContentResolver();
2512 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2513 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2514 String exclList = Settings.Secure.getString(res,
2515 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2516 if (!TextUtils.isEmpty(host)) {
2517 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2518 synchronized (mGlobalProxyLock) {
2519 mGlobalProxy = proxyProperties;
2520 }
2521 }
2522 }
2523
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002524 public ProxyProperties getGlobalProxy() {
2525 synchronized (mGlobalProxyLock) {
2526 return mGlobalProxy;
2527 }
2528 }
2529
2530 private void handleApplyDefaultProxy(int type) {
2531 // check if new default - push it out to all VM if so
2532 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2533 synchronized (this) {
2534 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2535 if (mDefaultProxy == proxy) return;
Robert Greenwalt027f5052011-07-29 10:03:37 -07002536 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002537 mDefaultProxy = proxy;
2538 } else {
2539 mDefaultProxy = null;
2540 }
2541 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002542 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002543 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2544 if (mGlobalProxy != null) return;
2545 sendProxyBroadcast(proxy);
2546 }
2547
2548 private void handleDeprecatedGlobalHttpProxy() {
2549 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2550 Settings.Secure.HTTP_PROXY);
2551 if (!TextUtils.isEmpty(proxy)) {
2552 String data[] = proxy.split(":");
2553 String proxyHost = data[0];
2554 int proxyPort = 8080;
2555 if (data.length > 1) {
2556 try {
2557 proxyPort = Integer.parseInt(data[1]);
2558 } catch (NumberFormatException e) {
2559 return;
2560 }
2561 }
2562 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2563 setGlobalProxy(p);
2564 }
2565 }
2566
2567 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002568 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002569 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002570 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002571 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2572 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002573 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002574 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002575 }
2576
2577 private static class SettingsObserver extends ContentObserver {
2578 private int mWhat;
2579 private Handler mHandler;
2580 SettingsObserver(Handler handler, int what) {
2581 super(handler);
2582 mHandler = handler;
2583 mWhat = what;
2584 }
2585
2586 void observe(Context context) {
2587 ContentResolver resolver = context.getContentResolver();
2588 resolver.registerContentObserver(Settings.Secure.getUriFor(
2589 Settings.Secure.HTTP_PROXY), false, this);
2590 }
2591
2592 @Override
2593 public void onChange(boolean selfChange) {
2594 mHandler.obtainMessage(mWhat).sendToTarget();
2595 }
2596 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002597
2598 private void log(String s) {
2599 Slog.d(TAG, s);
2600 }
2601
2602 private void loge(String s) {
2603 Slog.e(TAG, s);
2604 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002605
Wink Savillef6b76692011-02-24 17:58:51 -08002606 int convertFeatureToNetworkType(String feature){
2607 int networkType = -1;
2608 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2609 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2610 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2611 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2612 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2613 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2614 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2615 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2616 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2617 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2618 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2619 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2620 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2621 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2622 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2623 }
2624 return networkType;
2625 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002626
2627 private static <T> T checkNotNull(T value, String message) {
2628 if (value == null) {
2629 throw new NullPointerException(message);
2630 }
2631 return value;
2632 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002633
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002634 /**
2635 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002636 * VpnBuilder and not available in ConnectivityManager. Permissions
2637 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002638 * @hide
2639 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002640 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002641 public boolean protectVpn(ParcelFileDescriptor socket) {
2642 try {
2643 int type = mActiveDefaultNetwork;
2644 if (ConnectivityManager.isNetworkTypeValid(type)) {
2645 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2646 return true;
2647 }
2648 } catch (Exception e) {
2649 // ignore
2650 } finally {
2651 try {
2652 socket.close();
2653 } catch (Exception e) {
2654 // ignore
2655 }
2656 }
2657 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002658 }
2659
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002660 /**
2661 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002662 * and not available in ConnectivityManager. Permissions are checked
2663 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002664 * @hide
2665 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002666 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002667 public boolean prepareVpn(String oldPackage, String newPackage) {
2668 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002669 }
2670
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002671 /**
2672 * Configure a TUN interface and return its file descriptor. Parameters
2673 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002674 * and not available in ConnectivityManager. Permissions are checked in
2675 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002676 * @hide
2677 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002678 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002679 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002680 return mVpn.establish(config);
2681 }
2682
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002683 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002684 * Start legacy VPN and return an intent to VpnDialogs. This method is
2685 * used by VpnSettings and not available in ConnectivityManager.
2686 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002687 * @hide
2688 */
2689 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002690 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2691 mVpn.startLegacyVpn(config, racoon, mtpd);
2692 }
2693
2694 /**
2695 * Return the information of the ongoing legacy VPN. This method is used
2696 * by VpnSettings and not available in ConnectivityManager. Permissions
2697 * are checked in Vpn class.
2698 * @hide
2699 */
2700 @Override
2701 public LegacyVpnInfo getLegacyVpnInfo() {
2702 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002703 }
2704
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002705 /**
2706 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2707 * through NetworkStateTracker since it works differently. For example, it
2708 * needs to override DNS servers but never takes the default routes. It
2709 * relies on another data network, and it could keep existing connections
2710 * alive after reconnecting, switching between networks, or even resuming
2711 * from deep sleep. Calls from applications should be done synchronously
2712 * to avoid race conditions. As these are all hidden APIs, refactoring can
2713 * be done whenever a better abstraction is developed.
2714 */
2715 public class VpnCallback {
2716
2717 private VpnCallback() {
2718 }
2719
Chia-chi Yehcc844502011-07-14 18:01:57 -07002720 public void override(List<String> dnsServers, List<String> searchDomains) {
2721 if (dnsServers == null) {
2722 restore();
2723 return;
2724 }
2725
2726 // Convert DNS servers into addresses.
2727 List<InetAddress> addresses = new ArrayList<InetAddress>();
2728 for (String address : dnsServers) {
2729 // Double check the addresses and remove invalid ones.
2730 try {
2731 addresses.add(InetAddress.parseNumericAddress(address));
2732 } catch (Exception e) {
2733 // ignore
2734 }
2735 }
2736 if (addresses.isEmpty()) {
2737 restore();
2738 return;
2739 }
2740
2741 // Concatenate search domains into a string.
2742 StringBuilder buffer = new StringBuilder();
2743 if (searchDomains != null) {
2744 for (String domain : searchDomains) {
2745 buffer.append(domain).append(' ');
2746 }
2747 }
2748 String domains = buffer.toString().trim();
2749
2750 // Apply DNS changes.
2751 boolean changed = false;
2752 synchronized (mDnsLock) {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002753 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002754 mDnsOverridden = true;
2755 }
2756 if (changed) {
2757 bumpDns();
2758 }
2759
2760 // TODO: temporarily remove http proxy?
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002761 }
2762
Chia-chi Yehcc844502011-07-14 18:01:57 -07002763 public void restore() {
2764 synchronized (mDnsLock) {
2765 if (!mDnsOverridden) {
2766 return;
2767 }
2768 mDnsOverridden = false;
2769 }
2770 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002771 }
2772 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002773}