blob: 851cb3360476f250296f209b3639b04d3e6f1e4f [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 Sharkey971cd162011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070022import static android.net.ConnectivityManager.isNetworkTypeValid;
23import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070024import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070025
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080026import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080027import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070031import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080033import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080034import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080035import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070036import android.net.INetworkPolicyListener;
37import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070038import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070039import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080040import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070041import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070043import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070045import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070046import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070047import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070049import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070050import android.net.Proxy;
51import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070052import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080053import android.net.wifi.WifiStateTracker;
54import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040055import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080056import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070057import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070058import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070059import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.os.Looper;
61import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070062import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070063import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070064import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.os.ServiceManager;
66import android.os.SystemProperties;
67import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070068import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080070import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070071import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070073import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070074import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070075import com.android.internal.telephony.Phone;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -070076import com.android.server.am.BatteryStatsService;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080077import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070078import com.android.server.connectivity.Vpn;
Jeff Sharkey21062e72011-05-28 20:56:34 -070079import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070080import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080081
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070083import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080084import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070085import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070086import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070087import java.net.InetAddress;
88import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070089import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070090import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070091import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070092import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070093import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070094import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095
96/**
97 * @hide
98 */
99public class ConnectivityService extends IConnectivityManager.Stub {
100
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700101 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700102 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800103 private static final String TAG = "ConnectivityService";
104
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700105 private static final boolean LOGD_RULES = false;
106
Robert Greenwalt2034b912009-08-12 16:08:25 -0700107 // how long to wait before switching back to a radio's default network
108 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
109 // system property that can override the above value
110 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
111 "android.telephony.apn-restore";
112
Robert Greenwaltbd492212011-05-06 17:10:53 -0700113 // used in recursive route setting to add gateways for the host for which
114 // a host route was requested.
115 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
116
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800117 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800118 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800119
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700120 private Vpn mVpn;
121
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700122 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
123 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700124 /** Currently active network rules by UID. */
125 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700126 /** Set of ifaces that are costly. */
127 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700128
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129 /**
130 * Sometimes we want to refer to the individual network state
131 * trackers separately, and sometimes we just want to treat them
132 * abstractly.
133 */
134 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700135
136 /**
Wink Saville051a6642011-07-13 13:44:13 -0700137 * The link properties that define the current links
138 */
139 private LinkProperties mCurrentLinkProperties[];
140
141 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700142 * A per Net list of the PID's that requested access to the net
143 * used both as a refcount and for per-PID DNS selection
144 */
145 private List mNetRequestersPids[];
146
Robert Greenwalt2034b912009-08-12 16:08:25 -0700147 // priority order of the nettrackers
148 // (excluding dynamically set mNetworkPreference)
149 // TODO - move mNetworkTypePreference into this
150 private int[] mPriorityList;
151
The Android Open Source Project28527d22009-03-03 19:31:44 -0800152 private Context mContext;
153 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700154 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700155 // 0 is full bad, 100 is full good
156 private int mDefaultInetCondition = 0;
157 private int mDefaultInetConditionPublished = 0;
158 private boolean mInetConditionChangeInFlight = false;
159 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800160
Chia-chi Yehcc844502011-07-14 18:01:57 -0700161 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700163 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164
165 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700166 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800167
Robert Greenwalt355205c2011-05-10 15:05:02 -0700168 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700169 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700170
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700171 private static final int ENABLED = 1;
172 private static final int DISABLED = 0;
173
174 // Share the event space with NetworkStateTracker (which can't see this
175 // internal class but sends us events). If you change these, change
176 // NetworkStateTracker.java too.
177 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
178 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
179
180 /**
181 * used internally as a delayed event to make us switch back to the
182 * default network
183 */
184 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
185 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
186
187 /**
188 * used internally to change our mobile data enabled flag
189 */
190 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
191 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
192
193 /**
194 * used internally to change our network preference setting
195 * arg1 = networkType to prefer
196 */
197 private static final int EVENT_SET_NETWORK_PREFERENCE =
198 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
199
200 /**
201 * used internally to synchronize inet condition reports
202 * arg1 = networkType
203 * arg2 = condition (0 bad, 100 good)
204 */
205 private static final int EVENT_INET_CONDITION_CHANGE =
206 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
207
208 /**
209 * used internally to mark the end of inet condition hold periods
210 * arg1 = networkType
211 */
212 private static final int EVENT_INET_CONDITION_HOLD_END =
213 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
214
215 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700216 * used internally to set enable/disable cellular data
217 * arg1 = ENBALED or DISABLED
218 */
219 private static final int EVENT_SET_MOBILE_DATA =
220 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
221
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700222 /**
223 * used internally to clear a wakelock when transitioning
224 * from one net to another
225 */
226 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
227 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
228
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700229 /**
230 * used internally to reload global proxy settings
231 */
232 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
233 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
234
Robert Greenwalt34848c02011-03-25 13:09:25 -0700235 /**
236 * used internally to set external dependency met/unmet
237 * arg1 = ENABLED (met) or DISABLED (unmet)
238 * arg2 = NetworkType
239 */
240 private static final int EVENT_SET_DEPENDENCY_MET =
241 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
242
Chia-chi Yehcc844502011-07-14 18:01:57 -0700243 /**
244 * used internally to restore DNS properties back to the
245 * default network
246 */
247 private static final int EVENT_RESTORE_DNS =
248 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
249
Wink Saville7e4333c2011-08-05 11:40:22 -0700250 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700251 * used internally to send a sticky broadcast delayed.
252 */
253 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville7e4333c2011-08-05 11:40:22 -0700254 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700255
Jeff Sharkey805662d2011-08-19 02:24:24 -0700256 /**
257 * Used internally to
258 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
259 */
260 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
261
Robert Greenwalt2034b912009-08-12 16:08:25 -0700262 private Handler mHandler;
263
264 // list of DeathRecipients used to make sure features are turned off when
265 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500266 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700267
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400268 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800269 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400270
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700271 private PowerManager.WakeLock mNetTransitionWakeLock;
272 private String mNetTransitionWakeLockCausedBy = "";
273 private int mNetTransitionWakeLockSerialNumber;
274 private int mNetTransitionWakeLockTimeout;
275
Robert Greenwalt94daa182010-09-01 11:34:05 -0700276 private InetAddress mDefaultDns;
277
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700278 // this collection is used to refcount the added routes - if there are none left
279 // it's time to remove the route from the route table
280 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
281
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700282 // used in DBG mode to track inet condition reports
283 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
284 private ArrayList mInetLog;
285
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700286 // track the current default http proxy - tell the world if we get a new one (real change)
287 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700288 private Object mDefaultProxyLock = new Object();
289 private boolean mDefaultProxyDisabled = false;
290
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700291 // track the global proxy.
292 private ProxyProperties mGlobalProxy = null;
293 private final Object mGlobalProxyLock = new Object();
294
295 private SettingsObserver mSettingsObserver;
296
Robert Greenwalt34848c02011-03-25 13:09:25 -0700297 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700298 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700299
Robert Greenwalt12c44552009-12-07 11:33:18 -0800300 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700301 public int mSimultaneity;
302 public int mType;
303 public RadioAttributes(String init) {
304 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700305 mType = Integer.parseInt(fragments[0]);
306 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700307 }
308 }
309 RadioAttributes[] mRadioAttributes;
310
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700311 // the set of network types that can only be enabled by system/sig apps
312 List mProtectedNetworks;
313
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700314 public ConnectivityService(Context context, INetworkManagementService netd,
315 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800316 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800317
Wink Saville775aad62010-09-02 19:23:52 -0700318 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
319 handlerThread.start();
320 mHandler = new MyHandler(handlerThread.getLooper());
321
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800322 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800323 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
324 String id = Settings.Secure.getString(context.getContentResolver(),
325 Settings.Secure.ANDROID_ID);
326 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700327 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800328 SystemProperties.set("net.hostname", name);
329 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800330 }
331
Robert Greenwalt94daa182010-09-01 11:34:05 -0700332 // read our default dns server ip
333 String dns = Settings.Secure.getString(context.getContentResolver(),
334 Settings.Secure.DEFAULT_DNS_SERVER);
335 if (dns == null || dns.length() == 0) {
336 dns = context.getResources().getString(
337 com.android.internal.R.string.config_default_dns_server);
338 }
339 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800340 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
341 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800342 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700343 }
344
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700345 mContext = checkNotNull(context, "missing Context");
346 mNetd = checkNotNull(netd, "missing INetworkManagementService");
347 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700348
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700349 try {
350 mPolicyManager.registerListener(mPolicyListener);
351 } catch (RemoteException e) {
352 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700353 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700354 }
355
356 final PowerManager powerManager = (PowerManager) context.getSystemService(
357 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700358 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
359 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
360 com.android.internal.R.integer.config_networkTransitionTimeout);
361
Robert Greenwalt2034b912009-08-12 16:08:25 -0700362 mNetTrackers = new NetworkStateTracker[
363 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700364 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700365
The Android Open Source Project28527d22009-03-03 19:31:44 -0800366 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700367
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700368 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700369 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700370
Robert Greenwalt2034b912009-08-12 16:08:25 -0700371 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700372 String[] raStrings = context.getResources().getStringArray(
373 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700374 for (String raString : raStrings) {
375 RadioAttributes r = new RadioAttributes(raString);
376 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800377 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700378 continue;
379 }
380 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800381 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700382 r.mType);
383 continue;
384 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700385 mRadioAttributes[r.mType] = r;
386 }
387
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700388 String[] naStrings = context.getResources().getStringArray(
389 com.android.internal.R.array.networkAttributes);
390 for (String naString : naStrings) {
391 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700392 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700393 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800394 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700395 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700396 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700397 }
Wink Savillef2a62832011-04-07 14:23:45 -0700398 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800399 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700400 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700401 continue;
402 }
Wink Savillef2a62832011-04-07 14:23:45 -0700403 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800404 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700405 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700406 continue;
407 }
Wink Savillef2a62832011-04-07 14:23:45 -0700408 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700409 mNetworksDefined++;
410 } catch(Exception e) {
411 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700412 }
413 }
414
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700415 mProtectedNetworks = new ArrayList<Integer>();
416 int[] protectedNetworks = context.getResources().getIntArray(
417 com.android.internal.R.array.config_protectedNetworks);
418 for (int p : protectedNetworks) {
419 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
420 mProtectedNetworks.add(p);
421 } else {
422 if (DBG) loge("Ignoring protectedNetwork " + p);
423 }
424 }
425
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700426 // high priority first
427 mPriorityList = new int[mNetworksDefined];
428 {
429 int insertionPoint = mNetworksDefined-1;
430 int currentLowest = 0;
431 int nextLowest = 0;
432 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700433 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700434 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700435 if (na.priority < currentLowest) continue;
436 if (na.priority > currentLowest) {
437 if (na.priority < nextLowest || nextLowest == 0) {
438 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700439 }
440 continue;
441 }
Wink Savillef2a62832011-04-07 14:23:45 -0700442 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700443 }
444 currentLowest = nextLowest;
445 nextLowest = 0;
446 }
447 }
448
449 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
450 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700451 mNetRequestersPids[i] = new ArrayList();
452 }
453
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500454 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700455
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 mNumDnsEntries = 0;
457
458 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
459 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800460 /*
461 * Create the network state trackers for Wi-Fi and mobile
462 * data. Maybe this could be done with a factory class,
463 * but it's not clear that it's worth it, given that
464 * the number of different network types is not going
465 * to change very often.
466 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700467 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700468 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700469 case ConnectivityManager.TYPE_WIFI:
repo syncf5de5572011-07-29 23:55:49 -0700470 mNetTrackers[netType] = new WifiStateTracker(netType,
471 mNetConfigs[netType].name);
472 mNetTrackers[netType].startMonitoring(context, mHandler);
473 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700474 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700475 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700476 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700477 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700478 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800479 case ConnectivityManager.TYPE_DUMMY:
480 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700481 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800482 mNetTrackers[netType].startMonitoring(context, mHandler);
483 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800484 case ConnectivityManager.TYPE_BLUETOOTH:
485 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
486 mNetTrackers[netType].startMonitoring(context, mHandler);
487 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800488 case ConnectivityManager.TYPE_ETHERNET:
489 mNetTrackers[netType] = EthernetDataTracker.getInstance();
490 mNetTrackers[netType].startMonitoring(context, mHandler);
491 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700492 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800493 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700494 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700495 continue;
496 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700497 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700498 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700499 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800500
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700501 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
502 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
503
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700504 mTethering = new Tethering(mContext, nmService, statsService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700505 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700506 mTethering.getTetherableWifiRegexs().length != 0 ||
507 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700508 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800509
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700510 mVpn = new Vpn(mContext, new VpnCallback());
511
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700512 try {
513 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700514 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700515 } catch (RemoteException e) {
516 loge("Error registering observer :" + e);
517 }
518
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700519 if (DBG) {
520 mInetLog = new ArrayList();
521 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700522
523 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
524 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800525
526 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800527 }
528
529 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700530 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800531 * @param preference the new preference
532 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700533 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800534 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700535
536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800537 }
538
539 public int getNetworkPreference() {
540 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700541 int preference;
542 synchronized(this) {
543 preference = mNetworkPreference;
544 }
545 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800546 }
547
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700548 private void handleSetNetworkPreference(int preference) {
549 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700550 mNetConfigs[preference] != null &&
551 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700552 if (mNetworkPreference != preference) {
553 final ContentResolver cr = mContext.getContentResolver();
554 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
555 synchronized(this) {
556 mNetworkPreference = preference;
557 }
558 enforcePreference();
559 }
560 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800561 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700562
Wink Saville4f0de1e2011-08-04 15:01:58 -0700563 private int getConnectivityChangeDelay() {
564 final ContentResolver cr = mContext.getContentResolver();
565
566 /** Check system properties for the default value then use secure settings value, if any. */
567 int defaultDelay = SystemProperties.getInt(
568 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
569 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
570 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
571 defaultDelay);
572 }
573
The Android Open Source Project28527d22009-03-03 19:31:44 -0800574 private int getPersistedNetworkPreference() {
575 final ContentResolver cr = mContext.getContentResolver();
576
577 final int networkPrefSetting = Settings.Secure
578 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
579 if (networkPrefSetting != -1) {
580 return networkPrefSetting;
581 }
582
583 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
584 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700585
The Android Open Source Project28527d22009-03-03 19:31:44 -0800586 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700587 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800588 * In this method, we only tear down a non-preferred network. Establishing
589 * a connection to the preferred network is taken care of when we handle
590 * the disconnect event from the non-preferred network
591 * (see {@link #handleDisconnect(NetworkInfo)}).
592 */
593 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700594 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800595 return;
596
Robert Greenwalt2034b912009-08-12 16:08:25 -0700597 if (!mNetTrackers[mNetworkPreference].isAvailable())
598 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800599
Robert Greenwalt2034b912009-08-12 16:08:25 -0700600 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700601 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700602 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700603 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800604 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700605 " in enforcePreference");
606 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700607 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800608 }
609 }
610 }
611
612 private boolean teardown(NetworkStateTracker netTracker) {
613 if (netTracker.teardown()) {
614 netTracker.setTeardownRequested(true);
615 return true;
616 } else {
617 return false;
618 }
619 }
620
621 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700622 * Check if UID should be blocked from using the network represented by the
623 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700624 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700625 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
626 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700627
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700628 final boolean networkCostly;
629 final int uidRules;
630 synchronized (mRulesLock) {
631 networkCostly = mMeteredIfaces.contains(iface);
632 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700633 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700634
635 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
636 return true;
637 }
638
639 // no restrictive rules; network is visible
640 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700641 }
642
643 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700644 * Return a filtered {@link NetworkInfo}, potentially marked
645 * {@link DetailedState#BLOCKED} based on
646 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700647 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700648 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
649 NetworkInfo info = tracker.getNetworkInfo();
650 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700651 // network is blocked; clone and override state
652 info = new NetworkInfo(info);
653 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700654 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700655 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700656 }
657
658 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800659 * Return NetworkInfo for the active (i.e., connected) network interface.
660 * It is assumed that at most one network is active at a time. If more
661 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700662 * @return the info for the active network, or {@code null} if none is
663 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800664 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700665 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800666 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700667 enforceAccessPermission();
668 final int uid = Binder.getCallingUid();
669 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800670 }
671
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700672 @Override
673 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
674 enforceConnectivityInternalPermission();
675 return getNetworkInfo(mActiveDefaultNetwork, uid);
676 }
677
678 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800679 public NetworkInfo getNetworkInfo(int networkType) {
680 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700681 final int uid = Binder.getCallingUid();
682 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800683 }
684
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700685 private NetworkInfo getNetworkInfo(int networkType, int uid) {
686 NetworkInfo info = null;
687 if (isNetworkTypeValid(networkType)) {
688 final NetworkStateTracker tracker = mNetTrackers[networkType];
689 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700690 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700691 }
692 }
693 return info;
694 }
695
696 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800697 public NetworkInfo[] getAllNetworkInfo() {
698 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700699 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700700 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700701 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700702 for (NetworkStateTracker tracker : mNetTrackers) {
703 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700704 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700705 }
706 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800707 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700708 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800709 }
710
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700711 @Override
712 public boolean isNetworkSupported(int networkType) {
713 enforceAccessPermission();
714 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
715 }
716
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700717 /**
718 * Return LinkProperties for the active (i.e., connected) default
719 * network interface. It is assumed that at most one default network
720 * is active at a time. If more than one is active, it is indeterminate
721 * which will be returned.
722 * @return the ip properties for the active network, or {@code null} if
723 * none is active
724 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700725 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700726 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700727 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700728 }
729
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700730 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700731 public LinkProperties getLinkProperties(int networkType) {
732 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700733 if (isNetworkTypeValid(networkType)) {
734 final NetworkStateTracker tracker = mNetTrackers[networkType];
735 if (tracker != null) {
736 return tracker.getLinkProperties();
737 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700738 }
739 return null;
740 }
741
Jeff Sharkey21062e72011-05-28 20:56:34 -0700742 @Override
743 public NetworkState[] getAllNetworkState() {
744 enforceAccessPermission();
745 final int uid = Binder.getCallingUid();
746 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700747 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700748 for (NetworkStateTracker tracker : mNetTrackers) {
749 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700750 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700751 result.add(new NetworkState(
752 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
753 }
754 }
755 }
756 return result.toArray(new NetworkState[result.size()]);
757 }
758
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700759 private NetworkState getNetworkStateUnchecked(int networkType) {
760 if (isNetworkTypeValid(networkType)) {
761 final NetworkStateTracker tracker = mNetTrackers[networkType];
762 if (tracker != null) {
763 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
764 tracker.getLinkCapabilities());
765 }
766 }
767 return null;
768 }
769
770 @Override
771 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
772 enforceAccessPermission();
773 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
774 if (state != null) {
775 try {
776 return mPolicyManager.getNetworkQuotaInfo(state);
777 } catch (RemoteException e) {
778 }
779 }
780 return null;
781 }
782
The Android Open Source Project28527d22009-03-03 19:31:44 -0800783 public boolean setRadios(boolean turnOn) {
784 boolean result = true;
785 enforceChangePermission();
786 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700787 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800788 }
789 return result;
790 }
791
792 public boolean setRadio(int netType, boolean turnOn) {
793 enforceChangePermission();
794 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
795 return false;
796 }
797 NetworkStateTracker tracker = mNetTrackers[netType];
798 return tracker != null && tracker.setRadio(turnOn);
799 }
800
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700801 /**
802 * Used to notice when the calling process dies so we can self-expire
803 *
804 * Also used to know if the process has cleaned up after itself when
805 * our auto-expire timer goes off. The timer has a link to an object.
806 *
807 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700808 private class FeatureUser implements IBinder.DeathRecipient {
809 int mNetworkType;
810 String mFeature;
811 IBinder mBinder;
812 int mPid;
813 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800814 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700815
816 FeatureUser(int type, String feature, IBinder binder) {
817 super();
818 mNetworkType = type;
819 mFeature = feature;
820 mBinder = binder;
821 mPid = getCallingPid();
822 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800823 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700824
Robert Greenwalt2034b912009-08-12 16:08:25 -0700825 try {
826 mBinder.linkToDeath(this, 0);
827 } catch (RemoteException e) {
828 binderDied();
829 }
830 }
831
832 void unlinkDeathRecipient() {
833 mBinder.unlinkToDeath(this, 0);
834 }
835
836 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800837 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800838 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
839 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700840 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700841 }
842
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700843 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700844 if (VDBG) {
845 log("ConnectivityService FeatureUser expire(" +
846 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
847 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
848 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700849 stopUsingNetworkFeature(this, false);
850 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800851
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500852 public boolean isSameUser(FeatureUser u) {
853 if (u == null) return false;
854
855 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
856 }
857
858 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
859 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
860 TextUtils.equals(mFeature, feature)) {
861 return true;
862 }
863 return false;
864 }
865
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800866 public String toString() {
867 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
868 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
869 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700870 }
871
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700872 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700873 public int startUsingNetworkFeature(int networkType, String feature,
874 IBinder binder) {
Wink Savillea7d56572011-09-21 11:05:43 -0700875 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800876 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700877 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800878 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700879 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700880 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700881 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800882 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700883
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700884 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700885
repo syncf5de5572011-07-29 23:55:49 -0700886 // TODO - move this into individual networktrackers
887 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700888
889 if (mProtectedNetworks.contains(usedNetworkType)) {
890 enforceConnectivityInternalPermission();
891 }
892
Robert Greenwalt2034b912009-08-12 16:08:25 -0700893 NetworkStateTracker network = mNetTrackers[usedNetworkType];
894 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800895 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700896 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700897 NetworkInfo ni = network.getNetworkInfo();
898
899 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800900 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800901 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
902 return Phone.APN_TYPE_NOT_AVAILABLE;
903 } else {
904 // else make the attempt anyway - probably giving REQUEST_STARTED below
905 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700906 }
907
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500908 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
909
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700910 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500911 boolean addToList = true;
912 if (restoreTimer < 0) {
913 // In case there is no timer is specified for the feature,
914 // make sure we don't add duplicate entry with the same request.
915 for (FeatureUser u : mFeatureUsers) {
916 if (u.isSameUser(f)) {
917 // Duplicate user is found. Do not add.
918 addToList = false;
919 break;
920 }
921 }
922 }
923
924 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700925 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
926 // this gets used for per-pid dns when connected
927 mNetRequestersPids[usedNetworkType].add(currentPid);
928 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700929 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700930
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700931 if (restoreTimer >= 0) {
932 mHandler.sendMessageDelayed(
933 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
934 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700935
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700936 if ((ni.isConnectedOrConnecting() == true) &&
937 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700938 if (ni.isConnected() == true) {
939 // add the pid-specific dns
repo sync3035f652011-08-02 13:39:06 -0700940 handleDnsConfigurationChange(usedNetworkType);
Wink Savillea7d56572011-09-21 11:05:43 -0700941 if (VDBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700942 return Phone.APN_ALREADY_ACTIVE;
943 }
Wink Savillea7d56572011-09-21 11:05:43 -0700944 if (VDBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700945 return Phone.APN_REQUEST_STARTED;
946 }
947
948 // check if the radio in play can make another contact
949 // assume if cannot for now
950
Wink Savillea7d56572011-09-21 11:05:43 -0700951 if (DBG) {
952 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
953 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700954 network.reconnect();
955 return Phone.APN_REQUEST_STARTED;
956 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800957 // need to remember this unsupported request so we respond appropriately on stop
958 synchronized(this) {
959 mFeatureUsers.add(f);
960 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
961 // this gets used for per-pid dns when connected
962 mNetRequestersPids[usedNetworkType].add(currentPid);
963 }
964 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700965 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700966 }
967 }
968 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800969 }
970
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700971 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800972 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700973 enforceChangePermission();
974
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700975 int pid = getCallingPid();
976 int uid = getCallingUid();
977
978 FeatureUser u = null;
979 boolean found = false;
980
981 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500982 for (FeatureUser x : mFeatureUsers) {
983 if (x.isSameUser(pid, uid, networkType, feature)) {
984 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700985 found = true;
986 break;
987 }
988 }
989 }
990 if (found && u != null) {
991 // stop regardless of how many other time this proc had called start
992 return stopUsingNetworkFeature(u, true);
993 } else {
994 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -0700995 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700996 return 1;
997 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700998 }
999
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001000 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1001 int networkType = u.mNetworkType;
1002 String feature = u.mFeature;
1003 int pid = u.mPid;
1004 int uid = u.mUid;
1005
1006 NetworkStateTracker tracker = null;
1007 boolean callTeardown = false; // used to carry our decision outside of sync block
1008
Wink Savillea7d56572011-09-21 11:05:43 -07001009 if (VDBG) {
1010 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001011 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001012
The Android Open Source Project28527d22009-03-03 19:31:44 -08001013 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001014 if (DBG) {
1015 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1016 ", net is invalid");
1017 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001018 return -1;
1019 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001020
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001021 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1022 // sync block
1023 synchronized(this) {
1024 // check if this process still has an outstanding start request
1025 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001026 if (VDBG) {
1027 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1028 ", ignoring");
1029 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001030 return 1;
1031 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001032 u.unlinkDeathRecipient();
1033 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1034 // If we care about duplicate requests, check for that here.
1035 //
1036 // This is done to support the extension of a request - the app
1037 // can request we start the network feature again and renew the
1038 // auto-shutoff delay. Normal "stop" calls from the app though
1039 // do not pay attention to duplicate requests - in effect the
1040 // API does not refcount and a single stop will counter multiple starts.
1041 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001042 for (FeatureUser x : mFeatureUsers) {
1043 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001044 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001045 return 1;
1046 }
1047 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001048 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001049
repo syncf5de5572011-07-29 23:55:49 -07001050 // TODO - move to individual network trackers
1051 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1052
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001053 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001054 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001055 if (DBG) {
1056 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1057 " no known tracker for used net type " + usedNetworkType);
1058 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001059 return -1;
1060 }
1061 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001062 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001063 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001064 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001065 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001066 if (VDBG) {
1067 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1068 " others still using it");
1069 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001070 return 1;
1071 }
1072 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001073 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001074 if (DBG) {
1075 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1076 " not a known feature - dropping");
1077 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001078 }
1079 }
Wink Savillea7d56572011-09-21 11:05:43 -07001080
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001081 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001082 if (DBG) {
1083 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1084 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001085 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001086 return 1;
1087 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001088 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001089 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001090 }
1091
1092 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001093 * @deprecated use requestRouteToHostAddress instead
1094 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001095 * Ensure that a network route exists to deliver traffic to the specified
1096 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001097 * @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
The Android Open Source Project28527d22009-03-03 19:31:44 -08001101 * @return {@code true} on success, {@code false} on failure
1102 */
1103 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001104 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1105
1106 if (inetAddress == null) {
1107 return false;
1108 }
1109
1110 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1111 }
1112
1113 /**
1114 * Ensure that a network route exists to deliver traffic to the specified
1115 * host via the specified network interface.
1116 * @param networkType the type of the network over which traffic to the
1117 * specified host is to be routed
1118 * @param hostAddress the IP address of the host to which the route is
1119 * desired
1120 * @return {@code true} on success, {@code false} on failure
1121 */
1122 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001123 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001124 if (mProtectedNetworks.contains(networkType)) {
1125 enforceConnectivityInternalPermission();
1126 }
1127
The Android Open Source Project28527d22009-03-03 19:31:44 -08001128 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1129 return false;
1130 }
1131 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001132
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001133 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1134 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001135 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001136 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001137 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001138 }
1139 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001140 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001141 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001142 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001143 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001144 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001145 } catch (UnknownHostException e) {}
1146 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001147 }
1148
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001149 private boolean addRoute(LinkProperties p, RouteInfo r) {
1150 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001151 }
1152
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001153 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1154 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1155 }
1156
Robert Greenwalt98107422011-07-22 11:55:33 -07001157 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1158 return modifyRouteToAddress(lp, addr, true);
1159 }
1160
1161 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1162 return modifyRouteToAddress(lp, addr, false);
1163 }
1164
1165 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1166 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1167 if (bestRoute == null) {
1168 bestRoute = RouteInfo.makeHostRoute(addr);
1169 } else {
1170 if (bestRoute.getGateway().equals(addr)) {
1171 // if there is no better route, add the implied hostroute for our gateway
1172 bestRoute = RouteInfo.makeHostRoute(addr);
1173 } else {
1174 // if we will connect to this through another route, add a direct route
1175 // to it's gateway
1176 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1177 }
1178 }
1179 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1180 }
1181
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001182 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1183 boolean doAdd) {
1184 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1185
1186 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1187 loge("Error adding route - too much recursion");
1188 return false;
1189 }
1190
1191 if (r.isHostRoute() == false) {
1192 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1193 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001194 if (bestRoute.getGateway().equals(r.getGateway())) {
1195 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001196 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001197 } else {
1198 // if we will connect to our gateway through another route, add a direct
1199 // route to it's gateway
1200 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001201 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001202 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001203 }
1204 }
1205 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001206 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001207 mAddedRoutes.add(r);
1208 try {
1209 mNetd.addRoute(ifaceName, r);
1210 } catch (Exception e) {
1211 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001212 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001213 return false;
1214 }
1215 } else {
1216 // if we remove this one and there are no more like it, then refcount==0 and
1217 // we can remove it from the table
1218 mAddedRoutes.remove(r);
1219 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001220 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001221 try {
1222 mNetd.removeRoute(ifaceName, r);
1223 } catch (Exception e) {
1224 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001225 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001226 return false;
1227 }
1228 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001229 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001230 }
1231 }
1232 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001233 }
1234
1235 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001236 * @see ConnectivityManager#getMobileDataEnabled()
1237 */
1238 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001239 // TODO: This detail should probably be in DataConnectionTracker's
1240 // which is where we store the value and maybe make this
1241 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001242 enforceAccessPermission();
1243 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1244 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001245 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001246 return retVal;
1247 }
1248
Robert Greenwalt34848c02011-03-25 13:09:25 -07001249 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001250 enforceConnectivityInternalPermission();
1251
Robert Greenwalt34848c02011-03-25 13:09:25 -07001252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1253 (met ? ENABLED : DISABLED), networkType));
1254 }
1255
1256 private void handleSetDependencyMet(int networkType, boolean met) {
1257 if (mNetTrackers[networkType] != null) {
1258 if (DBG) {
1259 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1260 }
1261 mNetTrackers[networkType].setDependencyMet(met);
1262 }
1263 }
1264
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001265 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1266 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001267 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001268 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001269 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001270
1271 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001272 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001273 }
1274
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001275 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001276 // skip update when we've already applied rules
1277 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1278 if (oldRules == uidRules) return;
1279
1280 mUidRules.put(uid, uidRules);
1281 }
1282
1283 // TODO: dispatch into NMS to push rules towards kernel module
1284 // TODO: notify UID when it has requested targeted updates
1285 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001286
1287 @Override
1288 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1289 // only someone like NPMS should only be calling us
1290 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1291
1292 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001293 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001294 }
1295
1296 synchronized (mRulesLock) {
1297 mMeteredIfaces.clear();
1298 for (String iface : meteredIfaces) {
1299 mMeteredIfaces.add(iface);
1300 }
1301 }
1302 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001303 };
1304
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001305 /**
1306 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1307 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001308 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001309 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001310 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001311
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001312 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001313 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001314 }
1315
1316 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001317 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001318 if (VDBG) {
1319 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001320 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001321 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1322 }
1323 }
1324
1325 @Override
1326 public void setPolicyDataEnable(int networkType, boolean enabled) {
1327 // only someone like NPMS should only be calling us
1328 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1329
1330 mHandler.sendMessage(mHandler.obtainMessage(
1331 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1332 }
1333
1334 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1335 if (isNetworkTypeValid(networkType)) {
1336 final NetworkStateTracker tracker = mNetTrackers[networkType];
1337 if (tracker != null) {
1338 tracker.setPolicyDataEnable(enabled);
1339 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001340 }
1341 }
1342
The Android Open Source Project28527d22009-03-03 19:31:44 -08001343 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001344 mContext.enforceCallingOrSelfPermission(
1345 android.Manifest.permission.ACCESS_NETWORK_STATE,
1346 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001347 }
1348
1349 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001350 mContext.enforceCallingOrSelfPermission(
1351 android.Manifest.permission.CHANGE_NETWORK_STATE,
1352 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001353 }
1354
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001355 // TODO Make this a special check when it goes public
1356 private void enforceTetherChangePermission() {
1357 mContext.enforceCallingOrSelfPermission(
1358 android.Manifest.permission.CHANGE_NETWORK_STATE,
1359 "ConnectivityService");
1360 }
1361
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001362 private void enforceTetherAccessPermission() {
1363 mContext.enforceCallingOrSelfPermission(
1364 android.Manifest.permission.ACCESS_NETWORK_STATE,
1365 "ConnectivityService");
1366 }
1367
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001368 private void enforceConnectivityInternalPermission() {
1369 mContext.enforceCallingOrSelfPermission(
1370 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1371 "ConnectivityService");
1372 }
1373
The Android Open Source Project28527d22009-03-03 19:31:44 -08001374 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001375 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1376 * network, we ignore it. If it is for the active network, we send out a
1377 * broadcast. But first, we check whether it might be possible to connect
1378 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001379 * @param info the {@code NetworkInfo} for the network
1380 */
1381 private void handleDisconnect(NetworkInfo info) {
1382
Robert Greenwalt2034b912009-08-12 16:08:25 -07001383 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001384
Robert Greenwalt2034b912009-08-12 16:08:25 -07001385 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001386 /*
1387 * If the disconnected network is not the active one, then don't report
1388 * this as a loss of connectivity. What probably happened is that we're
1389 * getting the disconnect for a network that we explicitly disabled
1390 * in accordance with network preference policies.
1391 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001392 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001393 List pids = mNetRequestersPids[prevNetType];
1394 for (int i = 0; i<pids.size(); i++) {
1395 Integer pid = (Integer)pids.get(i);
1396 // will remove them because the net's no longer connected
1397 // need to do this now as only now do we know the pids and
1398 // can properly null things that are no longer referenced.
1399 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001400 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001401 }
1402
The Android Open Source Project28527d22009-03-03 19:31:44 -08001403 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1404 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1405 if (info.isFailover()) {
1406 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1407 info.setFailover(false);
1408 }
1409 if (info.getReason() != null) {
1410 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1411 }
1412 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001413 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1414 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001415 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001416
Robert Greenwalt34848c02011-03-25 13:09:25 -07001417 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001418 tryFailover(prevNetType);
1419 if (mActiveDefaultNetwork != -1) {
1420 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001421 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1422 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001423 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001424 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1425 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001426 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001427 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001428
1429 // Reset interface if no other connections are using the same interface
1430 boolean doReset = true;
1431 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1432 if (linkProperties != null) {
1433 String oldIface = linkProperties.getInterfaceName();
1434 if (TextUtils.isEmpty(oldIface) == false) {
1435 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1436 if (networkStateTracker == null) continue;
1437 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1438 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1439 LinkProperties l = networkStateTracker.getLinkProperties();
1440 if (l == null) continue;
1441 if (oldIface.equals(l.getInterfaceName())) {
1442 doReset = false;
1443 break;
1444 }
1445 }
1446 }
1447 }
1448 }
1449
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001450 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001451 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001452
Jeff Sharkey971cd162011-08-29 16:02:57 -07001453 final Intent immediateIntent = new Intent(intent);
1454 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1455 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001456 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001457 /*
1458 * If the failover network is already connected, then immediately send
1459 * out a followup broadcast indicating successful failover
1460 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001461 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001462 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1463 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001464 }
1465 }
1466
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001467 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001468 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001469 * If this is a default network, check if other defaults are available.
1470 * Try to reconnect on all available and let them hash it out when
1471 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001472 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001473 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001474 if (mActiveDefaultNetwork == prevNetType) {
1475 mActiveDefaultNetwork = -1;
1476 }
1477
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001478 // don't signal a reconnect for anything lower or equal priority than our
1479 // current connected default
1480 // TODO - don't filter by priority now - nice optimization but risky
1481// int currentPriority = -1;
1482// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001483// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001484// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001485 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001486 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001487 if (mNetConfigs[checkType] == null) continue;
1488 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001489
1490// Enabling the isAvailable() optimization caused mobile to not get
1491// selected if it was in the middle of error handling. Specifically
1492// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1493// would not be available and we wouldn't get connected to anything.
1494// So removing the isAvailable() optimization below for now. TODO: This
1495// optimization should work and we need to investigate why it doesn't work.
1496// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1497// complete before it is really complete.
1498// if (!mNetTrackers[checkType].isAvailable()) continue;
1499
Robert Greenwalt34848c02011-03-25 13:09:25 -07001500// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001501
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001502 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1503 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1504 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1505 checkInfo.setFailover(true);
1506 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001507 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001508 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001509 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001510 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 }
1512
1513 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001514 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1515 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001516 }
1517
Wink Saville4f0de1e2011-08-04 15:01:58 -07001518 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001519 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1520 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001521 }
1522
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001523 private void sendInetConditionBroadcast(NetworkInfo info) {
1524 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1525 }
1526
Wink Saville4f0de1e2011-08-04 15:01:58 -07001527 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001528 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001529 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1530 if (info.isFailover()) {
1531 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1532 info.setFailover(false);
1533 }
1534 if (info.getReason() != null) {
1535 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1536 }
1537 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001538 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1539 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001540 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001541 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001542 return intent;
1543 }
1544
1545 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1546 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1547 }
1548
1549 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1550 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001551 }
1552
1553 /**
1554 * Called when an attempt to fail over to another network has failed.
1555 * @param info the {@link NetworkInfo} for the failed network
1556 */
1557 private void handleConnectionFailure(NetworkInfo info) {
1558 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001559
Robert Greenwalt2034b912009-08-12 16:08:25 -07001560 String reason = info.getReason();
1561 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001562
Robert Greenwalte981bc52010-10-08 16:35:52 -07001563 String reasonText;
1564 if (reason == null) {
1565 reasonText = ".";
1566 } else {
1567 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001568 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001569 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001570
1571 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1572 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1573 if (getActiveNetworkInfo() == null) {
1574 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1575 }
1576 if (reason != null) {
1577 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1578 }
1579 if (extraInfo != null) {
1580 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1581 }
1582 if (info.isFailover()) {
1583 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1584 info.setFailover(false);
1585 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001586
Robert Greenwalt34848c02011-03-25 13:09:25 -07001587 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001588 tryFailover(info.getType());
1589 if (mActiveDefaultNetwork != -1) {
1590 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001591 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1592 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001593 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001594 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1595 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001596 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001597
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001598 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001599
1600 final Intent immediateIntent = new Intent(intent);
1601 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1602 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001603 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001604 /*
1605 * If the failover network is already connected, then immediately send
1606 * out a followup broadcast indicating successful failover
1607 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001608 if (mActiveDefaultNetwork != -1) {
1609 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001610 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001611 }
1612
1613 private void sendStickyBroadcast(Intent intent) {
1614 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001615 if (!mSystemReady) {
1616 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001617 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001618 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001619 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001620 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001621 }
1622
Dianne Hackborna417ff82009-12-08 19:45:14 -08001623 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001624 }
1625 }
1626
Wink Saville4f0de1e2011-08-04 15:01:58 -07001627 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1628 if (delayMs <= 0) {
1629 sendStickyBroadcast(intent);
1630 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001631 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001632 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1633 + intent.getAction());
1634 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001635 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1636 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1637 }
1638 }
1639
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001640 void systemReady() {
1641 synchronized(this) {
1642 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001643 if (mInitialBroadcast != null) {
1644 mContext.sendStickyBroadcast(mInitialBroadcast);
1645 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001646 }
1647 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001648 // load the global proxy at startup
1649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001650 }
1651
1652 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001653 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001654
1655 // snapshot isFailover, because sendConnectedBroadcast() resets it
1656 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001657 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001658
Robert Greenwalt2034b912009-08-12 16:08:25 -07001659 // if this is a default net and other default is running
1660 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001661 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001662 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1663 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001664 mNetConfigs[mActiveDefaultNetwork].priority >
1665 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001666 mNetworkPreference == mActiveDefaultNetwork) {
1667 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001668 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001669 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001670 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001671 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001672 teardown(thisNet);
1673 return;
1674 } else {
1675 // tear down the other
1676 NetworkStateTracker otherNet =
1677 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001678 if (DBG) {
1679 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001680 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001681 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001682 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001683 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001684 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001685 return;
1686 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001687 }
1688 }
1689 synchronized (ConnectivityService.this) {
1690 // have a new default network, release the transition wakelock in a second
1691 // if it's held. The second pause is to allow apps to reconnect over the
1692 // new network
1693 if (mNetTransitionWakeLock.isHeld()) {
1694 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001695 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001696 mNetTransitionWakeLockSerialNumber, 0),
1697 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001698 }
1699 }
1700 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001701 // this will cause us to come up initially as unconnected and switching
1702 // to connected after our normal pause unless somebody reports us as reall
1703 // disconnected
1704 mDefaultInetConditionPublished = 0;
1705 mDefaultConnectionSequence++;
1706 mInetConditionChangeInFlight = false;
1707 // Don't do this - if we never sign in stay, grey
1708 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001709 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001710 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001711 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001712 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001713 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001714
1715 // notify battery stats service about this network
1716 final String iface = thisNet.getLinkProperties().getInterfaceName();
1717 if (iface != null) {
1718 try {
1719 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1720 } catch (RemoteException e) {
1721 // ignored; service lives in system_server
1722 }
1723 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001724 }
1725
The Android Open Source Project28527d22009-03-03 19:31:44 -08001726 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001727 * After a change in the connectivity state of a network. We're mainly
1728 * concerned with making sure that the list of DNS servers is set up
1729 * according to which networks are connected, and ensuring that the
1730 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001731 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001732 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001733 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1734
The Android Open Source Project28527d22009-03-03 19:31:44 -08001735 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001736 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001737 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001738 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001739 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001740
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001741 LinkProperties curLp = mCurrentLinkProperties[netType];
1742 LinkProperties newLp = null;
1743
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001744 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001745 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001746 if (VDBG) {
1747 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1748 " doReset=" + doReset + " resetMask=" + resetMask +
1749 "\n curLp=" + curLp +
1750 "\n newLp=" + newLp);
1751 }
1752
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001753 if (curLp != null) {
1754 if (curLp.isIdenticalInterfaceName(newLp)) {
1755 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1756 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1757 for (LinkAddress linkAddr : car.removed) {
1758 if (linkAddr.getAddress() instanceof Inet4Address) {
1759 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1760 }
1761 if (linkAddr.getAddress() instanceof Inet6Address) {
1762 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1763 }
Wink Saville051a6642011-07-13 13:44:13 -07001764 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001765 if (DBG) {
1766 log("handleConnectivityChange: addresses changed" +
1767 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1768 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001769 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001770 } else {
1771 if (DBG) {
1772 log("handleConnectivityChange: address are the same reset per doReset" +
1773 " linkProperty[" + netType + "]:" +
1774 " resetMask=" + resetMask);
1775 }
Wink Saville051a6642011-07-13 13:44:13 -07001776 }
1777 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001778 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001779 if (DBG) {
1780 log("handleConnectivityChange: interface not not equivalent reset both" +
1781 " linkProperty[" + netType + "]:" +
1782 " resetMask=" + resetMask);
1783 }
Wink Saville051a6642011-07-13 13:44:13 -07001784 }
Wink Saville051a6642011-07-13 13:44:13 -07001785 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001786 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07001787 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001788 }
1789 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001790 if (VDBG) {
1791 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1792 " doReset=" + doReset + " resetMask=" + resetMask +
1793 "\n curLp=" + curLp +
1794 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001795 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001796 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001797 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001798 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001799
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001800 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001801 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1802 if (linkProperties != null) {
1803 String iface = linkProperties.getInterfaceName();
1804 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001805 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001806 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1807 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001808
1809 // Tell VPN the interface is down. It is a temporary
1810 // but effective fix to make VPN aware of the change.
1811 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1812 mVpn.interfaceStatusChanged(iface, false);
1813 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001814 }
1815 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07001816 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001817 try {
1818 mNetd.flushInterfaceDnsCache(iface);
1819 } catch (Exception e) {
1820 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001821 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001822 }
1823 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001824 }
1825 }
1826 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001827
1828 // TODO: Temporary notifying upstread change to Tethering.
1829 // @see bug/4455071
1830 /** Notify TetheringService if interface name has been changed. */
1831 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1832 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1833 if (isTetheringSupported()) {
1834 mTethering.handleTetherIfaceChange();
1835 }
1836 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001837 }
1838
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001839 /**
1840 * Add and remove routes using the old properties (null if not previously connected),
1841 * new properties (null if becoming disconnected). May even be double null, which
1842 * is a noop.
1843 * Uses isLinkDefault to determine if default routes should be set or conversely if
1844 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001845 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001846 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07001847 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1848 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001849 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001850 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1851 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001852 if (curLp != null) {
1853 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001854 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001855 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001856 } else if (newLp != null) {
1857 routeDiff.added = newLp.getRoutes();
1858 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001859 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001860
Robert Greenwalt8d777252011-08-15 12:31:55 -07001861 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1862
Robert Greenwalt98107422011-07-22 11:55:33 -07001863 for (RouteInfo r : routeDiff.removed) {
1864 if (isLinkDefault || ! r.isDefaultRoute()) {
1865 removeRoute(curLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001866 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001867 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001868
Robert Greenwalt98107422011-07-22 11:55:33 -07001869 for (RouteInfo r : routeDiff.added) {
1870 if (isLinkDefault || ! r.isDefaultRoute()) {
1871 addRoute(newLp, r);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001872 } else {
1873 // many radios add a default route even when we don't want one.
1874 // remove the default route unless somebody else has asked for it
1875 String ifaceName = newLp.getInterfaceName();
1876 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07001877 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001878 try {
1879 mNetd.removeRoute(ifaceName, r);
1880 } catch (Exception e) {
1881 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001882 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001883 }
1884 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001885 }
1886 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001887
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001888 if (!isLinkDefault) {
1889 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07001890 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001891 // routes changed - remove all old dns entries and add new
1892 if (curLp != null) {
1893 for (InetAddress oldDns : curLp.getDnses()) {
1894 removeRouteToAddress(curLp, oldDns);
1895 }
1896 }
1897 if (newLp != null) {
1898 for (InetAddress newDns : newLp.getDnses()) {
1899 addRouteToAddress(newLp, newDns);
1900 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001901 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001902 } else {
1903 // no change in routes, check for change in dns themselves
1904 for (InetAddress oldDns : dnsDiff.removed) {
1905 removeRouteToAddress(curLp, oldDns);
1906 }
1907 for (InetAddress newDns : dnsDiff.added) {
1908 addRouteToAddress(newLp, newDns);
1909 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001910 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001911 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001912 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001913 }
1914
1915
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001916 /**
1917 * Reads the network specific TCP buffer sizes from SystemProperties
1918 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1919 * wide use
1920 */
1921 public void updateNetworkSettings(NetworkStateTracker nt) {
1922 String key = nt.getTcpBufferSizesPropName();
1923 String bufferSizes = SystemProperties.get(key);
1924
1925 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001926 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001927
1928 // Setting to default values so we won't be stuck to previous values
1929 key = "net.tcp.buffersize.default";
1930 bufferSizes = SystemProperties.get(key);
1931 }
1932
1933 // Set values in kernel
1934 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001935 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001936 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001937 + "] which comes from [" + key + "]");
1938 }
1939 setBufferSize(bufferSizes);
1940 }
1941 }
1942
1943 /**
1944 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1945 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1946 *
1947 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1948 * writeMin, writeInitial, writeMax"
1949 */
1950 private void setBufferSize(String bufferSizes) {
1951 try {
1952 String[] values = bufferSizes.split(",");
1953
1954 if (values.length == 6) {
1955 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001956 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1957 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1958 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1959 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1960 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1961 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001962 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001963 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001964 }
1965 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001966 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001967 }
1968 }
1969
Robert Greenwalt2034b912009-08-12 16:08:25 -07001970 /**
1971 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1972 * on the highest priority active net which this process requested.
1973 * If there aren't any, clear it out
1974 */
1975 private void reassessPidDns(int myPid, boolean doBump)
1976 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001977 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001978 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001979 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001980 continue;
1981 }
1982 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001983 if (nt.getNetworkInfo().isConnected() &&
1984 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001985 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001986 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001987 List pids = mNetRequestersPids[i];
1988 for (int j=0; j<pids.size(); j++) {
1989 Integer pid = (Integer)pids.get(j);
1990 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001991 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07001992 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001993 if (doBump) {
1994 bumpDns();
1995 }
1996 return;
1997 }
1998 }
1999 }
2000 }
2001 // nothing found - delete
2002 for (int i = 1; ; i++) {
2003 String prop = "net.dns" + i + "." + myPid;
2004 if (SystemProperties.get(prop).length() == 0) {
2005 if (doBump) {
2006 bumpDns();
2007 }
2008 return;
2009 }
2010 SystemProperties.set(prop, "");
2011 }
2012 }
2013
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002014 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002015 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002016 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002017 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002018 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002019 String dnsString = dns.getHostAddress();
2020 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2021 changed = true;
2022 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2023 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002024 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002025 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002026 }
2027
2028 private void bumpDns() {
2029 /*
2030 * Bump the property that tells the name resolver library to reread
2031 * the DNS server list from the properties.
2032 */
2033 String propVal = SystemProperties.get("net.dnschange");
2034 int n = 0;
2035 if (propVal.length() != 0) {
2036 try {
2037 n = Integer.parseInt(propVal);
2038 } catch (NumberFormatException e) {}
2039 }
2040 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002041 /*
2042 * Tell the VMs to toss their DNS caches
2043 */
2044 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2045 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002046 /*
2047 * Connectivity events can happen before boot has completed ...
2048 */
2049 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002050 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002051 }
2052
Chia-chi Yehcc844502011-07-14 18:01:57 -07002053 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002054 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002055 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002056 boolean changed = false;
2057 int last = 0;
2058 if (dnses.size() == 0 && mDefaultDns != null) {
2059 ++last;
2060 String value = mDefaultDns.getHostAddress();
2061 if (!value.equals(SystemProperties.get("net.dns1"))) {
2062 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002063 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002064 }
2065 changed = true;
2066 SystemProperties.set("net.dns1", value);
2067 }
2068 } else {
2069 for (InetAddress dns : dnses) {
2070 ++last;
2071 String key = "net.dns" + last;
2072 String value = dns.getHostAddress();
2073 if (!changed && value.equals(SystemProperties.get(key))) {
2074 continue;
2075 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002076 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002077 log("adding dns " + value + " for " + network);
2078 }
2079 changed = true;
2080 SystemProperties.set(key, value);
2081 }
2082 }
2083 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2084 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002085 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002086 changed = true;
2087 SystemProperties.set(key, "");
2088 }
2089 mNumDnsEntries = last;
2090
Robert Greenwaltfce71862011-07-25 16:06:25 -07002091 if (changed) {
2092 try {
2093 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2094 mNetd.setDefaultInterfaceForDns(iface);
2095 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002096 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002097 }
2098 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002099 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2100 SystemProperties.set("net.dns.search", domains);
2101 changed = true;
2102 }
2103 return changed;
2104 }
2105
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002106 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002107 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002108 NetworkStateTracker nt = mNetTrackers[netType];
2109 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002110 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002111 if (p == null) return;
2112 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002113 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002114 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002115 String network = nt.getNetworkInfo().getTypeName();
2116 synchronized (mDnsLock) {
2117 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002118 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002119 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002120 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002121 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002122 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002123 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002124 NetworkUtils.makeStrings(dnses));
2125 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002126 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002127 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002128 // set per-pid dns for attached secondary nets
2129 List pids = mNetRequestersPids[netType];
2130 for (int y=0; y< pids.size(); y++) {
2131 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002132 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002133 }
2134 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002135 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002136 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002137 }
2138
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002139 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002140 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2141 NETWORK_RESTORE_DELAY_PROP_NAME);
2142 if(restoreDefaultNetworkDelayStr != null &&
2143 restoreDefaultNetworkDelayStr.length() != 0) {
2144 try {
2145 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2146 } catch (NumberFormatException e) {
2147 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002148 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002149 // if the system property isn't set, use the value for the apn type
2150 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2151
2152 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2153 (mNetConfigs[networkType] != null)) {
2154 ret = mNetConfigs[networkType].restoreTime;
2155 }
2156 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002157 }
2158
2159 @Override
2160 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002161 if (mContext.checkCallingOrSelfPermission(
2162 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002163 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002164 pw.println("Permission Denial: can't dump ConnectivityService " +
2165 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2166 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002167 return;
2168 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 pw.println();
2170 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002171 if (nst != null) {
2172 if (nst.getNetworkInfo().isConnected()) {
2173 pw.println("Active network: " + nst.getNetworkInfo().
2174 getTypeName());
2175 }
2176 pw.println(nst.getNetworkInfo());
2177 pw.println(nst);
2178 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002179 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002180 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002181
2182 pw.println("Network Requester Pids:");
2183 for (int net : mPriorityList) {
2184 String pidString = net + ": ";
2185 for (Object pid : mNetRequestersPids[net]) {
2186 pidString = pidString + pid.toString() + ", ";
2187 }
2188 pw.println(pidString);
2189 }
2190 pw.println();
2191
2192 pw.println("FeatureUsers:");
2193 for (Object requester : mFeatureUsers) {
2194 pw.println(requester.toString());
2195 }
2196 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002197
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002198 synchronized (this) {
2199 pw.println("NetworkTranstionWakeLock is currently " +
2200 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2201 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2202 }
2203 pw.println();
2204
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002205 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002206
2207 if (mInetLog != null) {
2208 pw.println();
2209 pw.println("Inet condition reports:");
2210 for(int i = 0; i < mInetLog.size(); i++) {
2211 pw.println(mInetLog.get(i));
2212 }
2213 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002214 }
2215
Robert Greenwalt2034b912009-08-12 16:08:25 -07002216 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002217 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002218 public MyHandler(Looper looper) {
2219 super(looper);
2220 }
2221
The Android Open Source Project28527d22009-03-03 19:31:44 -08002222 @Override
2223 public void handleMessage(Message msg) {
2224 NetworkInfo info;
2225 switch (msg.what) {
2226 case NetworkStateTracker.EVENT_STATE_CHANGED:
2227 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002228 int type = info.getType();
2229 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002230
Wink Savillea7d56572011-09-21 11:05:43 -07002231 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2232 (state == NetworkInfo.State.DISCONNECTED)) {
2233 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002234 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002235 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002236 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002237
2238 // Connectivity state changed:
2239 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002240 // [12-9] Network subtype (for mobile network, as defined
2241 // by TelephonyManager)
2242 // [8-3] Detailed state ordinal (as defined by
2243 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 // [2-0] Network type (as defined by ConnectivityManager)
2245 int eventLogParam = (info.getType() & 0x7) |
2246 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2247 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002248 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002249 eventLogParam);
2250
2251 if (info.getDetailedState() ==
2252 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002253 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002254 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002256 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002258 // the logic here is, handle SUSPENDED the same as
2259 // DISCONNECTED. The only difference being we are
2260 // broadcasting an intent with NetworkInfo that's
2261 // suspended. This allows the applications an
2262 // opportunity to handle DISCONNECTED and SUSPENDED
2263 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002265 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002266 handleConnect(info);
2267 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002268 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002269 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002270 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002271 // TODO: Temporary allowing network configuration
2272 // change not resetting sockets.
2273 // @see bug/4455071
2274 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002275 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002276 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002277 String causedBy = null;
2278 synchronized (ConnectivityService.this) {
2279 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2280 mNetTransitionWakeLock.isHeld()) {
2281 mNetTransitionWakeLock.release();
2282 causedBy = mNetTransitionWakeLockCausedBy;
2283 }
2284 }
2285 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002286 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002287 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002288 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002289 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002290 FeatureUser u = (FeatureUser)msg.obj;
2291 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002292 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002293 case EVENT_INET_CONDITION_CHANGE:
2294 {
2295 int netType = msg.arg1;
2296 int condition = msg.arg2;
2297 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002298 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002299 }
2300 case EVENT_INET_CONDITION_HOLD_END:
2301 {
2302 int netType = msg.arg1;
2303 int sequence = msg.arg2;
2304 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002305 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002306 }
2307 case EVENT_SET_NETWORK_PREFERENCE:
2308 {
2309 int preference = msg.arg1;
2310 handleSetNetworkPreference(preference);
2311 break;
2312 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002313 case EVENT_SET_MOBILE_DATA:
2314 {
2315 boolean enabled = (msg.arg1 == ENABLED);
2316 handleSetMobileData(enabled);
2317 break;
2318 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002319 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2320 {
2321 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002322 break;
2323 }
2324 case EVENT_SET_DEPENDENCY_MET:
2325 {
2326 boolean met = (msg.arg1 == ENABLED);
2327 handleSetDependencyMet(msg.arg2, met);
2328 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002329 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002330 case EVENT_RESTORE_DNS:
2331 {
2332 if (mActiveDefaultNetwork != -1) {
2333 handleDnsConfigurationChange(mActiveDefaultNetwork);
2334 }
2335 break;
2336 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002337 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2338 {
2339 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002340 sendStickyBroadcast(intent);
2341 break;
2342 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002343 case EVENT_SET_POLICY_DATA_ENABLE: {
2344 final int networkType = msg.arg1;
2345 final boolean enabled = msg.arg2 == ENABLED;
2346 handleSetPolicyDataEnable(networkType, enabled);
2347 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002348 }
2349 }
2350 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002351
2352 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002353 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002354 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002355
2356 if (isTetheringSupported()) {
2357 return mTethering.tether(iface);
2358 } else {
2359 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2360 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002361 }
2362
2363 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002364 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002365 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002366
2367 if (isTetheringSupported()) {
2368 return mTethering.untether(iface);
2369 } else {
2370 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2371 }
2372 }
2373
2374 // javadoc from interface
2375 public int getLastTetherError(String iface) {
2376 enforceTetherAccessPermission();
2377
2378 if (isTetheringSupported()) {
2379 return mTethering.getLastTetherError(iface);
2380 } else {
2381 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2382 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002383 }
2384
2385 // TODO - proper iface API for selection by property, inspection, etc
2386 public String[] getTetherableUsbRegexs() {
2387 enforceTetherAccessPermission();
2388 if (isTetheringSupported()) {
2389 return mTethering.getTetherableUsbRegexs();
2390 } else {
2391 return new String[0];
2392 }
2393 }
2394
2395 public String[] getTetherableWifiRegexs() {
2396 enforceTetherAccessPermission();
2397 if (isTetheringSupported()) {
2398 return mTethering.getTetherableWifiRegexs();
2399 } else {
2400 return new String[0];
2401 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002402 }
2403
Danica Chang96567052010-08-11 14:54:43 -07002404 public String[] getTetherableBluetoothRegexs() {
2405 enforceTetherAccessPermission();
2406 if (isTetheringSupported()) {
2407 return mTethering.getTetherableBluetoothRegexs();
2408 } else {
2409 return new String[0];
2410 }
2411 }
2412
Mike Lockwooded4a1742011-07-19 13:04:47 -07002413 public int setUsbTethering(boolean enable) {
2414 enforceTetherAccessPermission();
2415 if (isTetheringSupported()) {
2416 return mTethering.setUsbTethering(enable);
2417 } else {
2418 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2419 }
2420 }
2421
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002422 // TODO - move iface listing, queries, etc to new module
2423 // javadoc from interface
2424 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002425 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002426 return mTethering.getTetherableIfaces();
2427 }
2428
2429 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002430 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002431 return mTethering.getTetheredIfaces();
2432 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002433
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002434 @Override
2435 public String[] getTetheredIfacePairs() {
2436 enforceTetherAccessPermission();
2437 return mTethering.getTetheredIfacePairs();
2438 }
2439
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002440 public String[] getTetheringErroredIfaces() {
2441 enforceTetherAccessPermission();
2442 return mTethering.getErroredIfaces();
2443 }
2444
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002445 // if ro.tether.denied = true we default to no tethering
2446 // gservices could set the secure setting to 1 though to enable it on a build where it
2447 // had previously been turned off.
2448 public boolean isTetheringSupported() {
2449 enforceTetherAccessPermission();
2450 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002451 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2452 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt274518a2011-10-27 14:50:27 -07002453 // Short term disabling of Tethering if DUN is required.
2454 // TODO - fix multi-connection tethering using policy-base routing
2455 int[] upstreamConnTypes = mTethering.getUpstreamIfaceTypes();
2456 for (int i : upstreamConnTypes) {
2457 if (i == ConnectivityManager.TYPE_MOBILE_DUN) return false;
2458 }
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002459 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002460 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002461
2462 // An API NetworkStateTrackers can call when they lose their network.
2463 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2464 // whichever happens first. The timer is started by the first caller and not
2465 // restarted by subsequent callers.
2466 public void requestNetworkTransitionWakelock(String forWhom) {
2467 enforceConnectivityInternalPermission();
2468 synchronized (this) {
2469 if (mNetTransitionWakeLock.isHeld()) return;
2470 mNetTransitionWakeLockSerialNumber++;
2471 mNetTransitionWakeLock.acquire();
2472 mNetTransitionWakeLockCausedBy = forWhom;
2473 }
2474 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002475 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002476 mNetTransitionWakeLockSerialNumber, 0),
2477 mNetTransitionWakeLockTimeout);
2478 return;
2479 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002480
Robert Greenwalt986c7412010-09-08 15:24:47 -07002481 // 100 percent is full good, 0 is full bad.
2482 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002483 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002484 mContext.enforceCallingOrSelfPermission(
2485 android.Manifest.permission.STATUS_BAR,
2486 "ConnectivityService");
2487
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002488 if (DBG) {
2489 int pid = getCallingPid();
2490 int uid = getCallingUid();
2491 String s = pid + "(" + uid + ") reports inet is " +
2492 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2493 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2494 mInetLog.add(s);
2495 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2496 mInetLog.remove(0);
2497 }
2498 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002499 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002500 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2501 }
2502
2503 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002504 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002505 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002506 return;
2507 }
2508 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002509 if (DBG) log("handleInetConditionChange: net=" + netType +
2510 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002511 return;
2512 }
Wink Savillea7d56572011-09-21 11:05:43 -07002513 if (VDBG) {
2514 log("handleInetConditionChange: net=" +
2515 netType + ", condition=" + condition +
2516 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2517 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002518 mDefaultInetCondition = condition;
2519 int delay;
2520 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002521 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002522 // setup a new hold to debounce this
2523 if (mDefaultInetCondition > 50) {
2524 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2525 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2526 } else {
2527 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2528 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2529 }
2530 mInetConditionChangeInFlight = true;
2531 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2532 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2533 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002534 // we've set the new condition, when this hold ends that will get picked up
2535 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002536 }
2537 }
2538
2539 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002540 if (DBG) {
2541 log("handleInetConditionHoldEnd: net=" + netType +
2542 ", condition=" + mDefaultInetCondition +
2543 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002544 }
2545 mInetConditionChangeInFlight = false;
2546
2547 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002548 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002549 return;
2550 }
2551 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002552 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002553 return;
2554 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002555 // TODO: Figure out why this optimization sometimes causes a
2556 // change in mDefaultInetCondition to be missed and the
2557 // UI to not be updated.
2558 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2559 // if (DBG) log("no change in condition - aborting");
2560 // return;
2561 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002562 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2563 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002564 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002565 return;
2566 }
2567 mDefaultInetConditionPublished = mDefaultInetCondition;
2568 sendInetConditionBroadcast(networkInfo);
2569 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002570 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002571
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002572 public ProxyProperties getProxy() {
2573 synchronized (mDefaultProxyLock) {
2574 return mDefaultProxyDisabled ? null : mDefaultProxy;
2575 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002576 }
2577
2578 public void setGlobalProxy(ProxyProperties proxyProperties) {
2579 enforceChangePermission();
2580 synchronized (mGlobalProxyLock) {
2581 if (proxyProperties == mGlobalProxy) return;
2582 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2583 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2584
2585 String host = "";
2586 int port = 0;
2587 String exclList = "";
2588 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2589 mGlobalProxy = new ProxyProperties(proxyProperties);
2590 host = mGlobalProxy.getHost();
2591 port = mGlobalProxy.getPort();
2592 exclList = mGlobalProxy.getExclusionList();
2593 } else {
2594 mGlobalProxy = null;
2595 }
2596 ContentResolver res = mContext.getContentResolver();
2597 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2598 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002599 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002600 exclList);
2601 }
2602
2603 if (mGlobalProxy == null) {
2604 proxyProperties = mDefaultProxy;
2605 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002606 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002607 }
2608
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002609 private void loadGlobalProxy() {
2610 ContentResolver res = mContext.getContentResolver();
2611 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2612 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2613 String exclList = Settings.Secure.getString(res,
2614 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2615 if (!TextUtils.isEmpty(host)) {
2616 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2617 synchronized (mGlobalProxyLock) {
2618 mGlobalProxy = proxyProperties;
2619 }
2620 }
2621 }
2622
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002623 public ProxyProperties getGlobalProxy() {
2624 synchronized (mGlobalProxyLock) {
2625 return mGlobalProxy;
2626 }
2627 }
2628
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002629 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2630 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2631 proxy = null;
2632 }
2633 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002634 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2635 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002636 mDefaultProxy = proxy;
2637
2638 if (!mDefaultProxyDisabled) {
2639 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002640 }
2641 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002642 }
2643
2644 private void handleDeprecatedGlobalHttpProxy() {
2645 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2646 Settings.Secure.HTTP_PROXY);
2647 if (!TextUtils.isEmpty(proxy)) {
2648 String data[] = proxy.split(":");
2649 String proxyHost = data[0];
2650 int proxyPort = 8080;
2651 if (data.length > 1) {
2652 try {
2653 proxyPort = Integer.parseInt(data[1]);
2654 } catch (NumberFormatException e) {
2655 return;
2656 }
2657 }
2658 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2659 setGlobalProxy(p);
2660 }
2661 }
2662
2663 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002664 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002665 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002666 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002667 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2668 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002669 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002670 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002671 }
2672
2673 private static class SettingsObserver extends ContentObserver {
2674 private int mWhat;
2675 private Handler mHandler;
2676 SettingsObserver(Handler handler, int what) {
2677 super(handler);
2678 mHandler = handler;
2679 mWhat = what;
2680 }
2681
2682 void observe(Context context) {
2683 ContentResolver resolver = context.getContentResolver();
2684 resolver.registerContentObserver(Settings.Secure.getUriFor(
2685 Settings.Secure.HTTP_PROXY), false, this);
2686 }
2687
2688 @Override
2689 public void onChange(boolean selfChange) {
2690 mHandler.obtainMessage(mWhat).sendToTarget();
2691 }
2692 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002693
2694 private void log(String s) {
2695 Slog.d(TAG, s);
2696 }
2697
2698 private void loge(String s) {
2699 Slog.e(TAG, s);
2700 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002701
repo syncf5de5572011-07-29 23:55:49 -07002702 int convertFeatureToNetworkType(int networkType, String feature) {
2703 int usedNetworkType = networkType;
2704
2705 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2706 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2707 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2708 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2709 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2710 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2711 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2712 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2713 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2714 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2715 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2716 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2717 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2718 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2719 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2720 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2721 } else {
2722 Slog.e(TAG, "Can't match any mobile netTracker!");
2723 }
2724 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2725 if (TextUtils.equals(feature, "p2p")) {
2726 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2727 } else {
2728 Slog.e(TAG, "Can't match any wifi netTracker!");
2729 }
2730 } else {
2731 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002732 }
repo syncf5de5572011-07-29 23:55:49 -07002733 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002734 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002735
2736 private static <T> T checkNotNull(T value, String message) {
2737 if (value == null) {
2738 throw new NullPointerException(message);
2739 }
2740 return value;
2741 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002742
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002743 /**
2744 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002745 * VpnBuilder and not available in ConnectivityManager. Permissions
2746 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002747 * @hide
2748 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002749 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002750 public boolean protectVpn(ParcelFileDescriptor socket) {
2751 try {
2752 int type = mActiveDefaultNetwork;
2753 if (ConnectivityManager.isNetworkTypeValid(type)) {
2754 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2755 return true;
2756 }
2757 } catch (Exception e) {
2758 // ignore
2759 } finally {
2760 try {
2761 socket.close();
2762 } catch (Exception e) {
2763 // ignore
2764 }
2765 }
2766 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002767 }
2768
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002769 /**
2770 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002771 * and not available in ConnectivityManager. Permissions are checked
2772 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002773 * @hide
2774 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002775 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002776 public boolean prepareVpn(String oldPackage, String newPackage) {
2777 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002778 }
2779
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002780 /**
2781 * Configure a TUN interface and return its file descriptor. Parameters
2782 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002783 * and not available in ConnectivityManager. Permissions are checked in
2784 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002785 * @hide
2786 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002787 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002788 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002789 return mVpn.establish(config);
2790 }
2791
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002792 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002793 * Start legacy VPN and return an intent to VpnDialogs. This method is
2794 * used by VpnSettings and not available in ConnectivityManager.
2795 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002796 * @hide
2797 */
2798 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002799 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2800 mVpn.startLegacyVpn(config, racoon, mtpd);
2801 }
2802
2803 /**
2804 * Return the information of the ongoing legacy VPN. This method is used
2805 * by VpnSettings and not available in ConnectivityManager. Permissions
2806 * are checked in Vpn class.
2807 * @hide
2808 */
2809 @Override
2810 public LegacyVpnInfo getLegacyVpnInfo() {
2811 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002812 }
2813
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002814 /**
2815 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2816 * through NetworkStateTracker since it works differently. For example, it
2817 * needs to override DNS servers but never takes the default routes. It
2818 * relies on another data network, and it could keep existing connections
2819 * alive after reconnecting, switching between networks, or even resuming
2820 * from deep sleep. Calls from applications should be done synchronously
2821 * to avoid race conditions. As these are all hidden APIs, refactoring can
2822 * be done whenever a better abstraction is developed.
2823 */
2824 public class VpnCallback {
2825
2826 private VpnCallback() {
2827 }
2828
Chia-chi Yehcc844502011-07-14 18:01:57 -07002829 public void override(List<String> dnsServers, List<String> searchDomains) {
2830 if (dnsServers == null) {
2831 restore();
2832 return;
2833 }
2834
2835 // Convert DNS servers into addresses.
2836 List<InetAddress> addresses = new ArrayList<InetAddress>();
2837 for (String address : dnsServers) {
2838 // Double check the addresses and remove invalid ones.
2839 try {
2840 addresses.add(InetAddress.parseNumericAddress(address));
2841 } catch (Exception e) {
2842 // ignore
2843 }
2844 }
2845 if (addresses.isEmpty()) {
2846 restore();
2847 return;
2848 }
2849
2850 // Concatenate search domains into a string.
2851 StringBuilder buffer = new StringBuilder();
2852 if (searchDomains != null) {
2853 for (String domain : searchDomains) {
2854 buffer.append(domain).append(' ');
2855 }
2856 }
2857 String domains = buffer.toString().trim();
2858
2859 // Apply DNS changes.
2860 boolean changed = false;
2861 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002862 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002863 mDnsOverridden = true;
2864 }
2865 if (changed) {
2866 bumpDns();
2867 }
2868
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002869 // Temporarily disable the default proxy.
2870 synchronized (mDefaultProxyLock) {
2871 mDefaultProxyDisabled = true;
2872 if (mDefaultProxy != null) {
2873 sendProxyBroadcast(null);
2874 }
2875 }
2876
2877 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002878 }
2879
Chia-chi Yehcc844502011-07-14 18:01:57 -07002880 public void restore() {
2881 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002882 if (mDnsOverridden) {
2883 mDnsOverridden = false;
2884 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002885 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002886 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002887 synchronized (mDefaultProxyLock) {
2888 mDefaultProxyDisabled = false;
2889 if (mDefaultProxy != null) {
2890 sendProxyBroadcast(mDefaultProxy);
2891 }
2892 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002893 }
2894 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002895}