blob: ce314746c195381a723f4bcadbe8089f17625bfb [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;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080076import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070077import com.android.server.connectivity.Vpn;
Jeff Sharkey21062e72011-05-28 20:56:34 -070078import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070079import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080080
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070082import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080083import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070084import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070085import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070086import java.net.InetAddress;
87import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070088import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070089import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070090import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070091import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070092import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070093import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -080094
95/**
96 * @hide
97 */
98public class ConnectivityService extends IConnectivityManager.Stub {
99
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700100 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700101 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102 private static final String TAG = "ConnectivityService";
103
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700104 private static final boolean LOGD_RULES = false;
105
Robert Greenwalt2034b912009-08-12 16:08:25 -0700106 // how long to wait before switching back to a radio's default network
107 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
108 // system property that can override the above value
109 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
110 "android.telephony.apn-restore";
111
Robert Greenwaltbd492212011-05-06 17:10:53 -0700112 // used in recursive route setting to add gateways for the host for which
113 // a host route was requested.
114 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
115
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800116 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800117 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800118
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700119 private Vpn mVpn;
120
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700121 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
122 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700123 /** Currently active network rules by UID. */
124 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700125 /** Set of ifaces that are costly. */
126 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700127
The Android Open Source Project28527d22009-03-03 19:31:44 -0800128 /**
129 * Sometimes we want to refer to the individual network state
130 * trackers separately, and sometimes we just want to treat them
131 * abstractly.
132 */
133 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700134
135 /**
Wink Saville051a6642011-07-13 13:44:13 -0700136 * The link properties that define the current links
137 */
138 private LinkProperties mCurrentLinkProperties[];
139
140 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700141 * A per Net list of the PID's that requested access to the net
142 * used both as a refcount and for per-PID DNS selection
143 */
144 private List mNetRequestersPids[];
145
Robert Greenwalt2034b912009-08-12 16:08:25 -0700146 // priority order of the nettrackers
147 // (excluding dynamically set mNetworkPreference)
148 // TODO - move mNetworkTypePreference into this
149 private int[] mPriorityList;
150
The Android Open Source Project28527d22009-03-03 19:31:44 -0800151 private Context mContext;
152 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700154 // 0 is full bad, 100 is full good
155 private int mDefaultInetCondition = 0;
156 private int mDefaultInetConditionPublished = 0;
157 private boolean mInetConditionChangeInFlight = false;
158 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159
Chia-chi Yehcc844502011-07-14 18:01:57 -0700160 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800161 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700162 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163
164 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700165 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800166
Robert Greenwalt355205c2011-05-10 15:05:02 -0700167 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700168 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700169
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700170 private static final int ENABLED = 1;
171 private static final int DISABLED = 0;
172
173 // Share the event space with NetworkStateTracker (which can't see this
174 // internal class but sends us events). If you change these, change
175 // NetworkStateTracker.java too.
176 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
177 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
178
179 /**
180 * used internally as a delayed event to make us switch back to the
181 * default network
182 */
183 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
184 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
185
186 /**
187 * used internally to change our mobile data enabled flag
188 */
189 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
190 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
191
192 /**
193 * used internally to change our network preference setting
194 * arg1 = networkType to prefer
195 */
196 private static final int EVENT_SET_NETWORK_PREFERENCE =
197 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
198
199 /**
200 * used internally to synchronize inet condition reports
201 * arg1 = networkType
202 * arg2 = condition (0 bad, 100 good)
203 */
204 private static final int EVENT_INET_CONDITION_CHANGE =
205 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
206
207 /**
208 * used internally to mark the end of inet condition hold periods
209 * arg1 = networkType
210 */
211 private static final int EVENT_INET_CONDITION_HOLD_END =
212 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
213
214 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700215 * used internally to set enable/disable cellular data
216 * arg1 = ENBALED or DISABLED
217 */
218 private static final int EVENT_SET_MOBILE_DATA =
219 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
220
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700221 /**
222 * used internally to clear a wakelock when transitioning
223 * from one net to another
224 */
225 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
226 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
227
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700228 /**
229 * used internally to reload global proxy settings
230 */
231 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
232 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
233
Robert Greenwalt34848c02011-03-25 13:09:25 -0700234 /**
235 * used internally to set external dependency met/unmet
236 * arg1 = ENABLED (met) or DISABLED (unmet)
237 * arg2 = NetworkType
238 */
239 private static final int EVENT_SET_DEPENDENCY_MET =
240 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
241
Chia-chi Yehcc844502011-07-14 18:01:57 -0700242 /**
243 * used internally to restore DNS properties back to the
244 * default network
245 */
246 private static final int EVENT_RESTORE_DNS =
247 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
248
Wink Saville7e4333c2011-08-05 11:40:22 -0700249 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700250 * used internally to send a sticky broadcast delayed.
251 */
252 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville7e4333c2011-08-05 11:40:22 -0700253 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700254
Jeff Sharkey805662d2011-08-19 02:24:24 -0700255 /**
256 * Used internally to
257 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
258 */
259 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
260
Robert Greenwalt2034b912009-08-12 16:08:25 -0700261 private Handler mHandler;
262
263 // list of DeathRecipients used to make sure features are turned off when
264 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500265 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700266
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400267 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800268 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400269
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700270 private PowerManager.WakeLock mNetTransitionWakeLock;
271 private String mNetTransitionWakeLockCausedBy = "";
272 private int mNetTransitionWakeLockSerialNumber;
273 private int mNetTransitionWakeLockTimeout;
274
Robert Greenwalt94daa182010-09-01 11:34:05 -0700275 private InetAddress mDefaultDns;
276
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700277 // this collection is used to refcount the added routes - if there are none left
278 // it's time to remove the route from the route table
279 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
280
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700281 // used in DBG mode to track inet condition reports
282 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
283 private ArrayList mInetLog;
284
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700285 // track the current default http proxy - tell the world if we get a new one (real change)
286 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700287 private Object mDefaultProxyLock = new Object();
288 private boolean mDefaultProxyDisabled = false;
289
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700290 // track the global proxy.
291 private ProxyProperties mGlobalProxy = null;
292 private final Object mGlobalProxyLock = new Object();
293
294 private SettingsObserver mSettingsObserver;
295
Robert Greenwalt34848c02011-03-25 13:09:25 -0700296 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700297 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700298
Robert Greenwalt12c44552009-12-07 11:33:18 -0800299 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700300 public int mSimultaneity;
301 public int mType;
302 public RadioAttributes(String init) {
303 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700304 mType = Integer.parseInt(fragments[0]);
305 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700306 }
307 }
308 RadioAttributes[] mRadioAttributes;
309
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700310 // the set of network types that can only be enabled by system/sig apps
311 List mProtectedNetworks;
312
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700313 public ConnectivityService(Context context, INetworkManagementService netd,
314 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800315 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800316
Wink Saville775aad62010-09-02 19:23:52 -0700317 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
318 handlerThread.start();
319 mHandler = new MyHandler(handlerThread.getLooper());
320
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800321 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800322 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
323 String id = Settings.Secure.getString(context.getContentResolver(),
324 Settings.Secure.ANDROID_ID);
325 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700326 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800327 SystemProperties.set("net.hostname", name);
328 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800329 }
330
Robert Greenwalt94daa182010-09-01 11:34:05 -0700331 // read our default dns server ip
332 String dns = Settings.Secure.getString(context.getContentResolver(),
333 Settings.Secure.DEFAULT_DNS_SERVER);
334 if (dns == null || dns.length() == 0) {
335 dns = context.getResources().getString(
336 com.android.internal.R.string.config_default_dns_server);
337 }
338 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800339 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
340 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800341 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700342 }
343
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700344 mContext = checkNotNull(context, "missing Context");
345 mNetd = checkNotNull(netd, "missing INetworkManagementService");
346 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700347
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700348 try {
349 mPolicyManager.registerListener(mPolicyListener);
350 } catch (RemoteException e) {
351 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700352 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700353 }
354
355 final PowerManager powerManager = (PowerManager) context.getSystemService(
356 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700357 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
358 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
359 com.android.internal.R.integer.config_networkTransitionTimeout);
360
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361 mNetTrackers = new NetworkStateTracker[
362 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700363 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700364
The Android Open Source Project28527d22009-03-03 19:31:44 -0800365 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700366
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700367 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700368 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700369
Robert Greenwalt2034b912009-08-12 16:08:25 -0700370 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700371 String[] raStrings = context.getResources().getStringArray(
372 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 for (String raString : raStrings) {
374 RadioAttributes r = new RadioAttributes(raString);
375 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800376 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700377 continue;
378 }
379 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800380 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 r.mType);
382 continue;
383 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700384 mRadioAttributes[r.mType] = r;
385 }
386
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700387 String[] naStrings = context.getResources().getStringArray(
388 com.android.internal.R.array.networkAttributes);
389 for (String naString : naStrings) {
390 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700391 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700392 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800393 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700394 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700395 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700396 }
Wink Savillef2a62832011-04-07 14:23:45 -0700397 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800398 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700399 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700400 continue;
401 }
Wink Savillef2a62832011-04-07 14:23:45 -0700402 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800403 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700404 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700405 continue;
406 }
Wink Savillef2a62832011-04-07 14:23:45 -0700407 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700408 mNetworksDefined++;
409 } catch(Exception e) {
410 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700411 }
412 }
413
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700414 mProtectedNetworks = new ArrayList<Integer>();
415 int[] protectedNetworks = context.getResources().getIntArray(
416 com.android.internal.R.array.config_protectedNetworks);
417 for (int p : protectedNetworks) {
418 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
419 mProtectedNetworks.add(p);
420 } else {
421 if (DBG) loge("Ignoring protectedNetwork " + p);
422 }
423 }
424
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700425 // high priority first
426 mPriorityList = new int[mNetworksDefined];
427 {
428 int insertionPoint = mNetworksDefined-1;
429 int currentLowest = 0;
430 int nextLowest = 0;
431 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700432 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700433 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700434 if (na.priority < currentLowest) continue;
435 if (na.priority > currentLowest) {
436 if (na.priority < nextLowest || nextLowest == 0) {
437 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700438 }
439 continue;
440 }
Wink Savillef2a62832011-04-07 14:23:45 -0700441 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700442 }
443 currentLowest = nextLowest;
444 nextLowest = 0;
445 }
446 }
447
448 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
449 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700450 mNetRequestersPids[i] = new ArrayList();
451 }
452
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500453 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700454
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700455 mNumDnsEntries = 0;
456
457 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
458 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800459 /*
460 * Create the network state trackers for Wi-Fi and mobile
461 * data. Maybe this could be done with a factory class,
462 * but it's not clear that it's worth it, given that
463 * the number of different network types is not going
464 * to change very often.
465 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700466 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700467 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700468 case ConnectivityManager.TYPE_WIFI:
repo syncf5de5572011-07-29 23:55:49 -0700469 mNetTrackers[netType] = new WifiStateTracker(netType,
470 mNetConfigs[netType].name);
471 mNetTrackers[netType].startMonitoring(context, mHandler);
472 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700473 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700474 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700475 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700476 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700477 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800478 case ConnectivityManager.TYPE_DUMMY:
479 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700480 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800481 mNetTrackers[netType].startMonitoring(context, mHandler);
482 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800483 case ConnectivityManager.TYPE_BLUETOOTH:
484 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800487 case ConnectivityManager.TYPE_ETHERNET:
488 mNetTrackers[netType] = EthernetDataTracker.getInstance();
489 mNetTrackers[netType].startMonitoring(context, mHandler);
490 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700491 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800492 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700493 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700494 continue;
495 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700496 mCurrentLinkProperties[netType] = null;
Robert Greenwalt497ff5e72011-07-15 11:16:45 -0700497 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700498 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800499
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700500 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
501 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
502
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700503 mTethering = new Tethering(mContext, nmService, statsService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700504 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700505 mTethering.getTetherableWifiRegexs().length != 0 ||
506 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700507 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800508
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700509 mVpn = new Vpn(mContext, new VpnCallback());
510
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700511 try {
512 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700513 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700514 } catch (RemoteException e) {
515 loge("Error registering observer :" + e);
516 }
517
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700518 if (DBG) {
519 mInetLog = new ArrayList();
520 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700521
522 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
523 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800524
525 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800526 }
527
528 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700529 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800530 * @param preference the new preference
531 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700532 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800533 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700534
535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800536 }
537
538 public int getNetworkPreference() {
539 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700540 int preference;
541 synchronized(this) {
542 preference = mNetworkPreference;
543 }
544 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800545 }
546
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700547 private void handleSetNetworkPreference(int preference) {
548 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700549 mNetConfigs[preference] != null &&
550 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700551 if (mNetworkPreference != preference) {
552 final ContentResolver cr = mContext.getContentResolver();
553 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
554 synchronized(this) {
555 mNetworkPreference = preference;
556 }
557 enforcePreference();
558 }
559 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800560 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700561
Wink Saville4f0de1e2011-08-04 15:01:58 -0700562 private int getConnectivityChangeDelay() {
563 final ContentResolver cr = mContext.getContentResolver();
564
565 /** Check system properties for the default value then use secure settings value, if any. */
566 int defaultDelay = SystemProperties.getInt(
567 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
568 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
569 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
570 defaultDelay);
571 }
572
The Android Open Source Project28527d22009-03-03 19:31:44 -0800573 private int getPersistedNetworkPreference() {
574 final ContentResolver cr = mContext.getContentResolver();
575
576 final int networkPrefSetting = Settings.Secure
577 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
578 if (networkPrefSetting != -1) {
579 return networkPrefSetting;
580 }
581
582 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
583 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700584
The Android Open Source Project28527d22009-03-03 19:31:44 -0800585 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700586 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800587 * In this method, we only tear down a non-preferred network. Establishing
588 * a connection to the preferred network is taken care of when we handle
589 * the disconnect event from the non-preferred network
590 * (see {@link #handleDisconnect(NetworkInfo)}).
591 */
592 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700593 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800594 return;
595
Robert Greenwalt2034b912009-08-12 16:08:25 -0700596 if (!mNetTrackers[mNetworkPreference].isAvailable())
597 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800598
Robert Greenwalt2034b912009-08-12 16:08:25 -0700599 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700600 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700601 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700602 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800603 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700604 " in enforcePreference");
605 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700606 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800607 }
608 }
609 }
610
611 private boolean teardown(NetworkStateTracker netTracker) {
612 if (netTracker.teardown()) {
613 netTracker.setTeardownRequested(true);
614 return true;
615 } else {
616 return false;
617 }
618 }
619
620 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700621 * Check if UID should be blocked from using the network represented by the
622 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700623 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700624 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
625 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700626
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700627 final boolean networkCostly;
628 final int uidRules;
629 synchronized (mRulesLock) {
630 networkCostly = mMeteredIfaces.contains(iface);
631 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700632 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700633
634 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
635 return true;
636 }
637
638 // no restrictive rules; network is visible
639 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700640 }
641
642 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700643 * Return a filtered {@link NetworkInfo}, potentially marked
644 * {@link DetailedState#BLOCKED} based on
645 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700646 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700647 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
648 NetworkInfo info = tracker.getNetworkInfo();
649 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700650 // network is blocked; clone and override state
651 info = new NetworkInfo(info);
652 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700653 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700654 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700655 }
656
657 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800658 * Return NetworkInfo for the active (i.e., connected) network interface.
659 * It is assumed that at most one network is active at a time. If more
660 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700661 * @return the info for the active network, or {@code null} if none is
662 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800663 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700664 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800665 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700666 enforceAccessPermission();
667 final int uid = Binder.getCallingUid();
668 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800669 }
670
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700671 @Override
672 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
673 enforceConnectivityInternalPermission();
674 return getNetworkInfo(mActiveDefaultNetwork, uid);
675 }
676
677 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800678 public NetworkInfo getNetworkInfo(int networkType) {
679 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700680 final int uid = Binder.getCallingUid();
681 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800682 }
683
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700684 private NetworkInfo getNetworkInfo(int networkType, int uid) {
685 NetworkInfo info = null;
686 if (isNetworkTypeValid(networkType)) {
687 final NetworkStateTracker tracker = mNetTrackers[networkType];
688 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700689 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700690 }
691 }
692 return info;
693 }
694
695 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800696 public NetworkInfo[] getAllNetworkInfo() {
697 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700698 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700699 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700700 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700701 for (NetworkStateTracker tracker : mNetTrackers) {
702 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700703 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700704 }
705 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800706 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700707 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800708 }
709
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700710 @Override
711 public boolean isNetworkSupported(int networkType) {
712 enforceAccessPermission();
713 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
714 }
715
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700716 /**
717 * Return LinkProperties for the active (i.e., connected) default
718 * network interface. It is assumed that at most one default network
719 * is active at a time. If more than one is active, it is indeterminate
720 * which will be returned.
721 * @return the ip properties for the active network, or {@code null} if
722 * none is active
723 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700724 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700725 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700726 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700727 }
728
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700729 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700730 public LinkProperties getLinkProperties(int networkType) {
731 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700732 if (isNetworkTypeValid(networkType)) {
733 final NetworkStateTracker tracker = mNetTrackers[networkType];
734 if (tracker != null) {
735 return tracker.getLinkProperties();
736 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700737 }
738 return null;
739 }
740
Jeff Sharkey21062e72011-05-28 20:56:34 -0700741 @Override
742 public NetworkState[] getAllNetworkState() {
743 enforceAccessPermission();
744 final int uid = Binder.getCallingUid();
745 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700746 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700747 for (NetworkStateTracker tracker : mNetTrackers) {
748 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700749 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700750 result.add(new NetworkState(
751 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
752 }
753 }
754 }
755 return result.toArray(new NetworkState[result.size()]);
756 }
757
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700758 private NetworkState getNetworkStateUnchecked(int networkType) {
759 if (isNetworkTypeValid(networkType)) {
760 final NetworkStateTracker tracker = mNetTrackers[networkType];
761 if (tracker != null) {
762 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
763 tracker.getLinkCapabilities());
764 }
765 }
766 return null;
767 }
768
769 @Override
770 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
771 enforceAccessPermission();
772 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
773 if (state != null) {
774 try {
775 return mPolicyManager.getNetworkQuotaInfo(state);
776 } catch (RemoteException e) {
777 }
778 }
779 return null;
780 }
781
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782 public boolean setRadios(boolean turnOn) {
783 boolean result = true;
784 enforceChangePermission();
785 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700786 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800787 }
788 return result;
789 }
790
791 public boolean setRadio(int netType, boolean turnOn) {
792 enforceChangePermission();
793 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
794 return false;
795 }
796 NetworkStateTracker tracker = mNetTrackers[netType];
797 return tracker != null && tracker.setRadio(turnOn);
798 }
799
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700800 /**
801 * Used to notice when the calling process dies so we can self-expire
802 *
803 * Also used to know if the process has cleaned up after itself when
804 * our auto-expire timer goes off. The timer has a link to an object.
805 *
806 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 private class FeatureUser implements IBinder.DeathRecipient {
808 int mNetworkType;
809 String mFeature;
810 IBinder mBinder;
811 int mPid;
812 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800813 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814
815 FeatureUser(int type, String feature, IBinder binder) {
816 super();
817 mNetworkType = type;
818 mFeature = feature;
819 mBinder = binder;
820 mPid = getCallingPid();
821 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800822 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700823
Robert Greenwalt2034b912009-08-12 16:08:25 -0700824 try {
825 mBinder.linkToDeath(this, 0);
826 } catch (RemoteException e) {
827 binderDied();
828 }
829 }
830
831 void unlinkDeathRecipient() {
832 mBinder.unlinkToDeath(this, 0);
833 }
834
835 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800836 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800837 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
838 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700839 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700840 }
841
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700842 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700843 if (VDBG) {
844 log("ConnectivityService FeatureUser expire(" +
845 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
846 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
847 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700848 stopUsingNetworkFeature(this, false);
849 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800850
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500851 public boolean isSameUser(FeatureUser u) {
852 if (u == null) return false;
853
854 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
855 }
856
857 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
858 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
859 TextUtils.equals(mFeature, feature)) {
860 return true;
861 }
862 return false;
863 }
864
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800865 public String toString() {
866 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
867 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
868 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700869 }
870
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700871 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700872 public int startUsingNetworkFeature(int networkType, String feature,
873 IBinder binder) {
Wink Savillea7d56572011-09-21 11:05:43 -0700874 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800875 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700876 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700878 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700879 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700880 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700883 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700884
repo syncf5de5572011-07-29 23:55:49 -0700885 // TODO - move this into individual networktrackers
886 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700887
888 if (mProtectedNetworks.contains(usedNetworkType)) {
889 enforceConnectivityInternalPermission();
890 }
891
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 NetworkStateTracker network = mNetTrackers[usedNetworkType];
893 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800894 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700895 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700896 NetworkInfo ni = network.getNetworkInfo();
897
898 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800899 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800900 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
901 return Phone.APN_TYPE_NOT_AVAILABLE;
902 } else {
903 // else make the attempt anyway - probably giving REQUEST_STARTED below
904 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700905 }
906
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500907 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
908
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700909 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500910 boolean addToList = true;
911 if (restoreTimer < 0) {
912 // In case there is no timer is specified for the feature,
913 // make sure we don't add duplicate entry with the same request.
914 for (FeatureUser u : mFeatureUsers) {
915 if (u.isSameUser(f)) {
916 // Duplicate user is found. Do not add.
917 addToList = false;
918 break;
919 }
920 }
921 }
922
923 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700924 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
925 // this gets used for per-pid dns when connected
926 mNetRequestersPids[usedNetworkType].add(currentPid);
927 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700928 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700929
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700930 if (restoreTimer >= 0) {
931 mHandler.sendMessageDelayed(
932 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
933 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700934
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700935 if ((ni.isConnectedOrConnecting() == true) &&
936 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700937 if (ni.isConnected() == true) {
938 // add the pid-specific dns
repo sync3035f652011-08-02 13:39:06 -0700939 handleDnsConfigurationChange(usedNetworkType);
Wink Savillea7d56572011-09-21 11:05:43 -0700940 if (VDBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700941 return Phone.APN_ALREADY_ACTIVE;
942 }
Wink Savillea7d56572011-09-21 11:05:43 -0700943 if (VDBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700944 return Phone.APN_REQUEST_STARTED;
945 }
946
947 // check if the radio in play can make another contact
948 // assume if cannot for now
949
Wink Savillea7d56572011-09-21 11:05:43 -0700950 if (DBG) {
951 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
952 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700953 network.reconnect();
954 return Phone.APN_REQUEST_STARTED;
955 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800956 // need to remember this unsupported request so we respond appropriately on stop
957 synchronized(this) {
958 mFeatureUsers.add(f);
959 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
960 // this gets used for per-pid dns when connected
961 mNetRequestersPids[usedNetworkType].add(currentPid);
962 }
963 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700964 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700965 }
966 }
967 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800968 }
969
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700970 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800971 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700972 enforceChangePermission();
973
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700974 int pid = getCallingPid();
975 int uid = getCallingUid();
976
977 FeatureUser u = null;
978 boolean found = false;
979
980 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500981 for (FeatureUser x : mFeatureUsers) {
982 if (x.isSameUser(pid, uid, networkType, feature)) {
983 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700984 found = true;
985 break;
986 }
987 }
988 }
989 if (found && u != null) {
990 // stop regardless of how many other time this proc had called start
991 return stopUsingNetworkFeature(u, true);
992 } else {
993 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -0700994 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700995 return 1;
996 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700997 }
998
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700999 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1000 int networkType = u.mNetworkType;
1001 String feature = u.mFeature;
1002 int pid = u.mPid;
1003 int uid = u.mUid;
1004
1005 NetworkStateTracker tracker = null;
1006 boolean callTeardown = false; // used to carry our decision outside of sync block
1007
Wink Savillea7d56572011-09-21 11:05:43 -07001008 if (VDBG) {
1009 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001010 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001011
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001013 if (DBG) {
1014 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1015 ", net is invalid");
1016 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001017 return -1;
1018 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001019
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001020 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1021 // sync block
1022 synchronized(this) {
1023 // check if this process still has an outstanding start request
1024 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001025 if (VDBG) {
1026 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1027 ", ignoring");
1028 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001029 return 1;
1030 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001031 u.unlinkDeathRecipient();
1032 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1033 // If we care about duplicate requests, check for that here.
1034 //
1035 // This is done to support the extension of a request - the app
1036 // can request we start the network feature again and renew the
1037 // auto-shutoff delay. Normal "stop" calls from the app though
1038 // do not pay attention to duplicate requests - in effect the
1039 // API does not refcount and a single stop will counter multiple starts.
1040 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001041 for (FeatureUser x : mFeatureUsers) {
1042 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001043 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001044 return 1;
1045 }
1046 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001047 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001048
repo syncf5de5572011-07-29 23:55:49 -07001049 // TODO - move to individual network trackers
1050 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1051
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001052 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001053 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001054 if (DBG) {
1055 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1056 " no known tracker for used net type " + usedNetworkType);
1057 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001058 return -1;
1059 }
1060 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001061 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001062 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001063 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001064 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001065 if (VDBG) {
1066 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1067 " others still using it");
1068 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001069 return 1;
1070 }
1071 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001072 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001073 if (DBG) {
1074 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1075 " not a known feature - dropping");
1076 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001077 }
1078 }
Wink Savillea7d56572011-09-21 11:05:43 -07001079
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001080 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001081 if (DBG) {
1082 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1083 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001084 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001085 return 1;
1086 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001087 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001088 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001089 }
1090
1091 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001092 * @deprecated use requestRouteToHostAddress instead
1093 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001094 * Ensure that a network route exists to deliver traffic to the specified
1095 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001096 * @param networkType the type of the network over which traffic to the
1097 * specified host is to be routed
1098 * @param hostAddress the IP address of the host to which the route is
1099 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001100 * @return {@code true} on success, {@code false} on failure
1101 */
1102 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001103 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1104
1105 if (inetAddress == null) {
1106 return false;
1107 }
1108
1109 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1110 }
1111
1112 /**
1113 * Ensure that a network route exists to deliver traffic to the specified
1114 * host via the specified network interface.
1115 * @param networkType the type of the network over which traffic to the
1116 * specified host is to be routed
1117 * @param hostAddress the IP address of the host to which the route is
1118 * desired
1119 * @return {@code true} on success, {@code false} on failure
1120 */
1121 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001122 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001123 if (mProtectedNetworks.contains(networkType)) {
1124 enforceConnectivityInternalPermission();
1125 }
1126
The Android Open Source Project28527d22009-03-03 19:31:44 -08001127 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1128 return false;
1129 }
1130 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001131
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001132 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1133 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001134 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001135 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001136 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001137 }
1138 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001139 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001140 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001141 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001142 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001143 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001144 } catch (UnknownHostException e) {}
1145 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001146 }
1147
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001148 private boolean addRoute(LinkProperties p, RouteInfo r) {
1149 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001150 }
1151
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001152 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1153 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1154 }
1155
Robert Greenwalt98107422011-07-22 11:55:33 -07001156 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1157 return modifyRouteToAddress(lp, addr, true);
1158 }
1159
1160 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1161 return modifyRouteToAddress(lp, addr, false);
1162 }
1163
1164 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1165 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1166 if (bestRoute == null) {
1167 bestRoute = RouteInfo.makeHostRoute(addr);
1168 } else {
1169 if (bestRoute.getGateway().equals(addr)) {
1170 // if there is no better route, add the implied hostroute for our gateway
1171 bestRoute = RouteInfo.makeHostRoute(addr);
1172 } else {
1173 // if we will connect to this through another route, add a direct route
1174 // to it's gateway
1175 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1176 }
1177 }
1178 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1179 }
1180
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001181 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1182 boolean doAdd) {
1183 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1184
1185 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1186 loge("Error adding route - too much recursion");
1187 return false;
1188 }
1189
1190 if (r.isHostRoute() == false) {
1191 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1192 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001193 if (bestRoute.getGateway().equals(r.getGateway())) {
1194 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001195 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001196 } else {
1197 // if we will connect to our gateway through another route, add a direct
1198 // route to it's gateway
1199 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001200 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001201 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001202 }
1203 }
1204 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001205 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001206 mAddedRoutes.add(r);
1207 try {
1208 mNetd.addRoute(ifaceName, r);
1209 } catch (Exception e) {
1210 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001211 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001212 return false;
1213 }
1214 } else {
1215 // if we remove this one and there are no more like it, then refcount==0 and
1216 // we can remove it from the table
1217 mAddedRoutes.remove(r);
1218 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001219 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001220 try {
1221 mNetd.removeRoute(ifaceName, r);
1222 } catch (Exception e) {
1223 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001224 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001225 return false;
1226 }
1227 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001228 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001229 }
1230 }
1231 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001232 }
1233
1234 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001235 * @see ConnectivityManager#getMobileDataEnabled()
1236 */
1237 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001238 // TODO: This detail should probably be in DataConnectionTracker's
1239 // which is where we store the value and maybe make this
1240 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001241 enforceAccessPermission();
1242 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1243 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001244 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001245 return retVal;
1246 }
1247
Robert Greenwalt34848c02011-03-25 13:09:25 -07001248 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001249 enforceConnectivityInternalPermission();
1250
Robert Greenwalt34848c02011-03-25 13:09:25 -07001251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1252 (met ? ENABLED : DISABLED), networkType));
1253 }
1254
1255 private void handleSetDependencyMet(int networkType, boolean met) {
1256 if (mNetTrackers[networkType] != null) {
1257 if (DBG) {
1258 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1259 }
1260 mNetTrackers[networkType].setDependencyMet(met);
1261 }
1262 }
1263
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001264 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1265 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001266 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001267 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001268 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001269
1270 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001271 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001272 }
1273
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001274 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001275 // skip update when we've already applied rules
1276 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1277 if (oldRules == uidRules) return;
1278
1279 mUidRules.put(uid, uidRules);
1280 }
1281
1282 // TODO: dispatch into NMS to push rules towards kernel module
1283 // TODO: notify UID when it has requested targeted updates
1284 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001285
1286 @Override
1287 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1288 // only someone like NPMS should only be calling us
1289 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1290
1291 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001292 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001293 }
1294
1295 synchronized (mRulesLock) {
1296 mMeteredIfaces.clear();
1297 for (String iface : meteredIfaces) {
1298 mMeteredIfaces.add(iface);
1299 }
1300 }
1301 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001302 };
1303
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001304 /**
1305 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1306 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001307 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001308 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001309 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001310
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001311 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001312 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001313 }
1314
1315 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001316 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001317 if (VDBG) {
1318 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001319 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001320 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1321 }
1322 }
1323
1324 @Override
1325 public void setPolicyDataEnable(int networkType, boolean enabled) {
1326 // only someone like NPMS should only be calling us
1327 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1328
1329 mHandler.sendMessage(mHandler.obtainMessage(
1330 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1331 }
1332
1333 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1334 if (isNetworkTypeValid(networkType)) {
1335 final NetworkStateTracker tracker = mNetTrackers[networkType];
1336 if (tracker != null) {
1337 tracker.setPolicyDataEnable(enabled);
1338 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001339 }
1340 }
1341
The Android Open Source Project28527d22009-03-03 19:31:44 -08001342 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001343 mContext.enforceCallingOrSelfPermission(
1344 android.Manifest.permission.ACCESS_NETWORK_STATE,
1345 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001346 }
1347
1348 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001349 mContext.enforceCallingOrSelfPermission(
1350 android.Manifest.permission.CHANGE_NETWORK_STATE,
1351 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001352 }
1353
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001354 // TODO Make this a special check when it goes public
1355 private void enforceTetherChangePermission() {
1356 mContext.enforceCallingOrSelfPermission(
1357 android.Manifest.permission.CHANGE_NETWORK_STATE,
1358 "ConnectivityService");
1359 }
1360
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001361 private void enforceTetherAccessPermission() {
1362 mContext.enforceCallingOrSelfPermission(
1363 android.Manifest.permission.ACCESS_NETWORK_STATE,
1364 "ConnectivityService");
1365 }
1366
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001367 private void enforceConnectivityInternalPermission() {
1368 mContext.enforceCallingOrSelfPermission(
1369 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1370 "ConnectivityService");
1371 }
1372
The Android Open Source Project28527d22009-03-03 19:31:44 -08001373 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001374 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1375 * network, we ignore it. If it is for the active network, we send out a
1376 * broadcast. But first, we check whether it might be possible to connect
1377 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001378 * @param info the {@code NetworkInfo} for the network
1379 */
1380 private void handleDisconnect(NetworkInfo info) {
1381
Robert Greenwalt2034b912009-08-12 16:08:25 -07001382 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001383
Robert Greenwalt2034b912009-08-12 16:08:25 -07001384 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001385 /*
1386 * If the disconnected network is not the active one, then don't report
1387 * this as a loss of connectivity. What probably happened is that we're
1388 * getting the disconnect for a network that we explicitly disabled
1389 * in accordance with network preference policies.
1390 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001391 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001392 List pids = mNetRequestersPids[prevNetType];
1393 for (int i = 0; i<pids.size(); i++) {
1394 Integer pid = (Integer)pids.get(i);
1395 // will remove them because the net's no longer connected
1396 // need to do this now as only now do we know the pids and
1397 // can properly null things that are no longer referenced.
1398 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001399 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001400 }
1401
The Android Open Source Project28527d22009-03-03 19:31:44 -08001402 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1403 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1404 if (info.isFailover()) {
1405 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1406 info.setFailover(false);
1407 }
1408 if (info.getReason() != null) {
1409 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1410 }
1411 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001412 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1413 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001414 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001415
Robert Greenwalt34848c02011-03-25 13:09:25 -07001416 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001417 tryFailover(prevNetType);
1418 if (mActiveDefaultNetwork != -1) {
1419 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001420 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1421 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001422 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001423 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1424 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001425 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001426 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001427
1428 // Reset interface if no other connections are using the same interface
1429 boolean doReset = true;
1430 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1431 if (linkProperties != null) {
1432 String oldIface = linkProperties.getInterfaceName();
1433 if (TextUtils.isEmpty(oldIface) == false) {
1434 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1435 if (networkStateTracker == null) continue;
1436 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1437 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1438 LinkProperties l = networkStateTracker.getLinkProperties();
1439 if (l == null) continue;
1440 if (oldIface.equals(l.getInterfaceName())) {
1441 doReset = false;
1442 break;
1443 }
1444 }
1445 }
1446 }
1447 }
1448
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001449 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001450 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001451
Jeff Sharkey971cd162011-08-29 16:02:57 -07001452 final Intent immediateIntent = new Intent(intent);
1453 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1454 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001455 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001456 /*
1457 * If the failover network is already connected, then immediately send
1458 * out a followup broadcast indicating successful failover
1459 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001460 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001461 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1462 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001463 }
1464 }
1465
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001466 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001467 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001468 * If this is a default network, check if other defaults are available.
1469 * Try to reconnect on all available and let them hash it out when
1470 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001471 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001472 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001473 if (mActiveDefaultNetwork == prevNetType) {
1474 mActiveDefaultNetwork = -1;
1475 }
1476
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001477 // don't signal a reconnect for anything lower or equal priority than our
1478 // current connected default
1479 // TODO - don't filter by priority now - nice optimization but risky
1480// int currentPriority = -1;
1481// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001482// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001483// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001484 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001485 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001486 if (mNetConfigs[checkType] == null) continue;
1487 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001488
1489// Enabling the isAvailable() optimization caused mobile to not get
1490// selected if it was in the middle of error handling. Specifically
1491// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1492// would not be available and we wouldn't get connected to anything.
1493// So removing the isAvailable() optimization below for now. TODO: This
1494// optimization should work and we need to investigate why it doesn't work.
1495// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1496// complete before it is really complete.
1497// if (!mNetTrackers[checkType].isAvailable()) continue;
1498
Robert Greenwalt34848c02011-03-25 13:09:25 -07001499// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001500
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001501 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1502 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1503 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1504 checkInfo.setFailover(true);
1505 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001506 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001507 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001508 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001510 }
1511
1512 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001513 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1514 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001515 }
1516
Wink Saville4f0de1e2011-08-04 15:01:58 -07001517 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001518 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1519 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001520 }
1521
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001522 private void sendInetConditionBroadcast(NetworkInfo info) {
1523 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1524 }
1525
Wink Saville4f0de1e2011-08-04 15:01:58 -07001526 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001527 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001528 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1529 if (info.isFailover()) {
1530 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1531 info.setFailover(false);
1532 }
1533 if (info.getReason() != null) {
1534 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1535 }
1536 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001537 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1538 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001539 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001540 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001541 return intent;
1542 }
1543
1544 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1545 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1546 }
1547
1548 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1549 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001550 }
1551
1552 /**
1553 * Called when an attempt to fail over to another network has failed.
1554 * @param info the {@link NetworkInfo} for the failed network
1555 */
1556 private void handleConnectionFailure(NetworkInfo info) {
1557 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001558
Robert Greenwalt2034b912009-08-12 16:08:25 -07001559 String reason = info.getReason();
1560 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001561
Robert Greenwalte981bc52010-10-08 16:35:52 -07001562 String reasonText;
1563 if (reason == null) {
1564 reasonText = ".";
1565 } else {
1566 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001568 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001569
1570 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1571 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1572 if (getActiveNetworkInfo() == null) {
1573 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1574 }
1575 if (reason != null) {
1576 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1577 }
1578 if (extraInfo != null) {
1579 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1580 }
1581 if (info.isFailover()) {
1582 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1583 info.setFailover(false);
1584 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001585
Robert Greenwalt34848c02011-03-25 13:09:25 -07001586 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001587 tryFailover(info.getType());
1588 if (mActiveDefaultNetwork != -1) {
1589 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001590 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1591 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001592 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001593 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1594 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001595 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001596
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001597 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001598
1599 final Intent immediateIntent = new Intent(intent);
1600 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1601 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001602 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001603 /*
1604 * If the failover network is already connected, then immediately send
1605 * out a followup broadcast indicating successful failover
1606 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001607 if (mActiveDefaultNetwork != -1) {
1608 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001609 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001610 }
1611
1612 private void sendStickyBroadcast(Intent intent) {
1613 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001614 if (!mSystemReady) {
1615 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001616 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001617 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001618 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001619 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001620 }
1621
Dianne Hackborna417ff82009-12-08 19:45:14 -08001622 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001623 }
1624 }
1625
Wink Saville4f0de1e2011-08-04 15:01:58 -07001626 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1627 if (delayMs <= 0) {
1628 sendStickyBroadcast(intent);
1629 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001630 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001631 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1632 + intent.getAction());
1633 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001634 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1635 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1636 }
1637 }
1638
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001639 void systemReady() {
1640 synchronized(this) {
1641 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001642 if (mInitialBroadcast != null) {
1643 mContext.sendStickyBroadcast(mInitialBroadcast);
1644 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001645 }
1646 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001647 // load the global proxy at startup
1648 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001649 }
1650
1651 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001652 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001653
1654 // snapshot isFailover, because sendConnectedBroadcast() resets it
1655 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001656 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001657
Robert Greenwalt2034b912009-08-12 16:08:25 -07001658 // if this is a default net and other default is running
1659 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001660 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001661 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1662 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001663 mNetConfigs[mActiveDefaultNetwork].priority >
1664 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001665 mNetworkPreference == mActiveDefaultNetwork) {
1666 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001667 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001668 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001669 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001670 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001671 teardown(thisNet);
1672 return;
1673 } else {
1674 // tear down the other
1675 NetworkStateTracker otherNet =
1676 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001677 if (DBG) {
1678 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001679 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001680 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001681 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001682 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001683 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001684 return;
1685 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001686 }
1687 }
1688 synchronized (ConnectivityService.this) {
1689 // have a new default network, release the transition wakelock in a second
1690 // if it's held. The second pause is to allow apps to reconnect over the
1691 // new network
1692 if (mNetTransitionWakeLock.isHeld()) {
1693 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001694 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001695 mNetTransitionWakeLockSerialNumber, 0),
1696 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001697 }
1698 }
1699 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001700 // this will cause us to come up initially as unconnected and switching
1701 // to connected after our normal pause unless somebody reports us as reall
1702 // disconnected
1703 mDefaultInetConditionPublished = 0;
1704 mDefaultConnectionSequence++;
1705 mInetConditionChangeInFlight = false;
1706 // Don't do this - if we never sign in stay, grey
1707 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001708 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001709 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001710 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001711 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001712 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001713 }
1714
The Android Open Source Project28527d22009-03-03 19:31:44 -08001715 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001716 * After a change in the connectivity state of a network. We're mainly
1717 * concerned with making sure that the list of DNS servers is set up
1718 * according to which networks are connected, and ensuring that the
1719 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001720 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001721 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001722 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1723
The Android Open Source Project28527d22009-03-03 19:31:44 -08001724 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001725 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001726 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001727 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001728 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001729
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001730 LinkProperties curLp = mCurrentLinkProperties[netType];
1731 LinkProperties newLp = null;
1732
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001733 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001734 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001735 if (VDBG) {
1736 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1737 " doReset=" + doReset + " resetMask=" + resetMask +
1738 "\n curLp=" + curLp +
1739 "\n newLp=" + newLp);
1740 }
1741
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001742 if (curLp != null) {
1743 if (curLp.isIdenticalInterfaceName(newLp)) {
1744 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1745 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1746 for (LinkAddress linkAddr : car.removed) {
1747 if (linkAddr.getAddress() instanceof Inet4Address) {
1748 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1749 }
1750 if (linkAddr.getAddress() instanceof Inet6Address) {
1751 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1752 }
Wink Saville051a6642011-07-13 13:44:13 -07001753 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001754 if (DBG) {
1755 log("handleConnectivityChange: addresses changed" +
1756 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1757 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001758 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001759 } else {
1760 if (DBG) {
1761 log("handleConnectivityChange: address are the same reset per doReset" +
1762 " linkProperty[" + netType + "]:" +
1763 " resetMask=" + resetMask);
1764 }
Wink Saville051a6642011-07-13 13:44:13 -07001765 }
1766 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001767 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001768 if (DBG) {
1769 log("handleConnectivityChange: interface not not equivalent reset both" +
1770 " linkProperty[" + netType + "]:" +
1771 " resetMask=" + resetMask);
1772 }
Wink Saville051a6642011-07-13 13:44:13 -07001773 }
Wink Saville051a6642011-07-13 13:44:13 -07001774 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001775 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07001776 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001777 }
1778 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001779 if (VDBG) {
1780 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1781 " doReset=" + doReset + " resetMask=" + resetMask +
1782 "\n curLp=" + curLp +
1783 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001784 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001786 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001787 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001788
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001789 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001790 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1791 if (linkProperties != null) {
1792 String iface = linkProperties.getInterfaceName();
1793 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001794 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001795 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1796 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001797
1798 // Tell VPN the interface is down. It is a temporary
1799 // but effective fix to make VPN aware of the change.
1800 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1801 mVpn.interfaceStatusChanged(iface, false);
1802 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001803 }
1804 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07001805 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001806 try {
1807 mNetd.flushInterfaceDnsCache(iface);
1808 } catch (Exception e) {
1809 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001810 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001811 }
1812 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001813 }
1814 }
1815 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001816
1817 // TODO: Temporary notifying upstread change to Tethering.
1818 // @see bug/4455071
1819 /** Notify TetheringService if interface name has been changed. */
1820 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1821 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1822 if (isTetheringSupported()) {
1823 mTethering.handleTetherIfaceChange();
1824 }
1825 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001826 }
1827
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001828 /**
1829 * Add and remove routes using the old properties (null if not previously connected),
1830 * new properties (null if becoming disconnected). May even be double null, which
1831 * is a noop.
1832 * Uses isLinkDefault to determine if default routes should be set or conversely if
1833 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001834 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001835 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07001836 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1837 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001838 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001839 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1840 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001841 if (curLp != null) {
1842 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001843 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001844 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001845 } else if (newLp != null) {
1846 routeDiff.added = newLp.getRoutes();
1847 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001848 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001849
Robert Greenwalt8d777252011-08-15 12:31:55 -07001850 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1851
Robert Greenwalt98107422011-07-22 11:55:33 -07001852 for (RouteInfo r : routeDiff.removed) {
1853 if (isLinkDefault || ! r.isDefaultRoute()) {
1854 removeRoute(curLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001855 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001856 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001857
Robert Greenwalt98107422011-07-22 11:55:33 -07001858 for (RouteInfo r : routeDiff.added) {
1859 if (isLinkDefault || ! r.isDefaultRoute()) {
1860 addRoute(newLp, r);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001861 } else {
1862 // many radios add a default route even when we don't want one.
1863 // remove the default route unless somebody else has asked for it
1864 String ifaceName = newLp.getInterfaceName();
1865 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07001866 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001867 try {
1868 mNetd.removeRoute(ifaceName, r);
1869 } catch (Exception e) {
1870 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001871 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001872 }
1873 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001874 }
1875 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001876
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001877 if (!isLinkDefault) {
1878 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07001879 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001880 // routes changed - remove all old dns entries and add new
1881 if (curLp != null) {
1882 for (InetAddress oldDns : curLp.getDnses()) {
1883 removeRouteToAddress(curLp, oldDns);
1884 }
1885 }
1886 if (newLp != null) {
1887 for (InetAddress newDns : newLp.getDnses()) {
1888 addRouteToAddress(newLp, newDns);
1889 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001890 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001891 } else {
1892 // no change in routes, check for change in dns themselves
1893 for (InetAddress oldDns : dnsDiff.removed) {
1894 removeRouteToAddress(curLp, oldDns);
1895 }
1896 for (InetAddress newDns : dnsDiff.added) {
1897 addRouteToAddress(newLp, newDns);
1898 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001899 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001900 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001901 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001902 }
1903
1904
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001905 /**
1906 * Reads the network specific TCP buffer sizes from SystemProperties
1907 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1908 * wide use
1909 */
1910 public void updateNetworkSettings(NetworkStateTracker nt) {
1911 String key = nt.getTcpBufferSizesPropName();
1912 String bufferSizes = SystemProperties.get(key);
1913
1914 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001915 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001916
1917 // Setting to default values so we won't be stuck to previous values
1918 key = "net.tcp.buffersize.default";
1919 bufferSizes = SystemProperties.get(key);
1920 }
1921
1922 // Set values in kernel
1923 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001924 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001925 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001926 + "] which comes from [" + key + "]");
1927 }
1928 setBufferSize(bufferSizes);
1929 }
1930 }
1931
1932 /**
1933 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1934 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1935 *
1936 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1937 * writeMin, writeInitial, writeMax"
1938 */
1939 private void setBufferSize(String bufferSizes) {
1940 try {
1941 String[] values = bufferSizes.split(",");
1942
1943 if (values.length == 6) {
1944 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001945 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1946 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1947 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1948 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1949 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1950 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001951 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001952 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001953 }
1954 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001955 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001956 }
1957 }
1958
Robert Greenwalt2034b912009-08-12 16:08:25 -07001959 /**
1960 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1961 * on the highest priority active net which this process requested.
1962 * If there aren't any, clear it out
1963 */
1964 private void reassessPidDns(int myPid, boolean doBump)
1965 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001966 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001967 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001968 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001969 continue;
1970 }
1971 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001972 if (nt.getNetworkInfo().isConnected() &&
1973 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001974 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001975 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001976 List pids = mNetRequestersPids[i];
1977 for (int j=0; j<pids.size(); j++) {
1978 Integer pid = (Integer)pids.get(j);
1979 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001980 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07001981 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001982 if (doBump) {
1983 bumpDns();
1984 }
1985 return;
1986 }
1987 }
1988 }
1989 }
1990 // nothing found - delete
1991 for (int i = 1; ; i++) {
1992 String prop = "net.dns" + i + "." + myPid;
1993 if (SystemProperties.get(prop).length() == 0) {
1994 if (doBump) {
1995 bumpDns();
1996 }
1997 return;
1998 }
1999 SystemProperties.set(prop, "");
2000 }
2001 }
2002
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002003 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002004 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002005 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002006 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002007 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002008 String dnsString = dns.getHostAddress();
2009 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2010 changed = true;
2011 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2012 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002013 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002014 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002015 }
2016
2017 private void bumpDns() {
2018 /*
2019 * Bump the property that tells the name resolver library to reread
2020 * the DNS server list from the properties.
2021 */
2022 String propVal = SystemProperties.get("net.dnschange");
2023 int n = 0;
2024 if (propVal.length() != 0) {
2025 try {
2026 n = Integer.parseInt(propVal);
2027 } catch (NumberFormatException e) {}
2028 }
2029 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002030 /*
2031 * Tell the VMs to toss their DNS caches
2032 */
2033 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2034 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002035 /*
2036 * Connectivity events can happen before boot has completed ...
2037 */
2038 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002039 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002040 }
2041
Chia-chi Yehcc844502011-07-14 18:01:57 -07002042 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002043 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002044 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002045 boolean changed = false;
2046 int last = 0;
2047 if (dnses.size() == 0 && mDefaultDns != null) {
2048 ++last;
2049 String value = mDefaultDns.getHostAddress();
2050 if (!value.equals(SystemProperties.get("net.dns1"))) {
2051 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002052 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002053 }
2054 changed = true;
2055 SystemProperties.set("net.dns1", value);
2056 }
2057 } else {
2058 for (InetAddress dns : dnses) {
2059 ++last;
2060 String key = "net.dns" + last;
2061 String value = dns.getHostAddress();
2062 if (!changed && value.equals(SystemProperties.get(key))) {
2063 continue;
2064 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002065 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002066 log("adding dns " + value + " for " + network);
2067 }
2068 changed = true;
2069 SystemProperties.set(key, value);
2070 }
2071 }
2072 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2073 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002074 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002075 changed = true;
2076 SystemProperties.set(key, "");
2077 }
2078 mNumDnsEntries = last;
2079
Robert Greenwaltfce71862011-07-25 16:06:25 -07002080 if (changed) {
2081 try {
2082 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2083 mNetd.setDefaultInterfaceForDns(iface);
2084 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002085 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002086 }
2087 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002088 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2089 SystemProperties.set("net.dns.search", domains);
2090 changed = true;
2091 }
2092 return changed;
2093 }
2094
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002095 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002096 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002097 NetworkStateTracker nt = mNetTrackers[netType];
2098 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002099 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002100 if (p == null) return;
2101 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002102 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002103 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002104 String network = nt.getNetworkInfo().getTypeName();
2105 synchronized (mDnsLock) {
2106 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002107 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002108 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002109 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002110 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002111 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002112 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002113 NetworkUtils.makeStrings(dnses));
2114 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002115 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002116 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002117 // set per-pid dns for attached secondary nets
2118 List pids = mNetRequestersPids[netType];
2119 for (int y=0; y< pids.size(); y++) {
2120 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002121 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002122 }
2123 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002124 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002125 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002126 }
2127
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002128 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002129 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2130 NETWORK_RESTORE_DELAY_PROP_NAME);
2131 if(restoreDefaultNetworkDelayStr != null &&
2132 restoreDefaultNetworkDelayStr.length() != 0) {
2133 try {
2134 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2135 } catch (NumberFormatException e) {
2136 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002138 // if the system property isn't set, use the value for the apn type
2139 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2140
2141 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2142 (mNetConfigs[networkType] != null)) {
2143 ret = mNetConfigs[networkType].restoreTime;
2144 }
2145 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 }
2147
2148 @Override
2149 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002150 if (mContext.checkCallingOrSelfPermission(
2151 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002152 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002153 pw.println("Permission Denial: can't dump ConnectivityService " +
2154 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2155 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002156 return;
2157 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002158 pw.println();
2159 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002160 if (nst != null) {
2161 if (nst.getNetworkInfo().isConnected()) {
2162 pw.println("Active network: " + nst.getNetworkInfo().
2163 getTypeName());
2164 }
2165 pw.println(nst.getNetworkInfo());
2166 pw.println(nst);
2167 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002168 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002170
2171 pw.println("Network Requester Pids:");
2172 for (int net : mPriorityList) {
2173 String pidString = net + ": ";
2174 for (Object pid : mNetRequestersPids[net]) {
2175 pidString = pidString + pid.toString() + ", ";
2176 }
2177 pw.println(pidString);
2178 }
2179 pw.println();
2180
2181 pw.println("FeatureUsers:");
2182 for (Object requester : mFeatureUsers) {
2183 pw.println(requester.toString());
2184 }
2185 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002186
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002187 synchronized (this) {
2188 pw.println("NetworkTranstionWakeLock is currently " +
2189 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2190 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2191 }
2192 pw.println();
2193
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002194 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002195
2196 if (mInetLog != null) {
2197 pw.println();
2198 pw.println("Inet condition reports:");
2199 for(int i = 0; i < mInetLog.size(); i++) {
2200 pw.println(mInetLog.get(i));
2201 }
2202 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002203 }
2204
Robert Greenwalt2034b912009-08-12 16:08:25 -07002205 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002206 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002207 public MyHandler(Looper looper) {
2208 super(looper);
2209 }
2210
The Android Open Source Project28527d22009-03-03 19:31:44 -08002211 @Override
2212 public void handleMessage(Message msg) {
2213 NetworkInfo info;
2214 switch (msg.what) {
2215 case NetworkStateTracker.EVENT_STATE_CHANGED:
2216 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002217 int type = info.getType();
2218 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002219
Wink Savillea7d56572011-09-21 11:05:43 -07002220 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2221 (state == NetworkInfo.State.DISCONNECTED)) {
2222 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002223 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002224 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002225 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002226
2227 // Connectivity state changed:
2228 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002229 // [12-9] Network subtype (for mobile network, as defined
2230 // by TelephonyManager)
2231 // [8-3] Detailed state ordinal (as defined by
2232 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002233 // [2-0] Network type (as defined by ConnectivityManager)
2234 int eventLogParam = (info.getType() & 0x7) |
2235 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2236 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002237 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002238 eventLogParam);
2239
2240 if (info.getDetailedState() ==
2241 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002243 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002245 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002246 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002247 // the logic here is, handle SUSPENDED the same as
2248 // DISCONNECTED. The only difference being we are
2249 // broadcasting an intent with NetworkInfo that's
2250 // suspended. This allows the applications an
2251 // opportunity to handle DISCONNECTED and SUSPENDED
2252 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002253 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002254 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255 handleConnect(info);
2256 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002258 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002259 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002260 // TODO: Temporary allowing network configuration
2261 // change not resetting sockets.
2262 // @see bug/4455071
2263 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002265 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002266 String causedBy = null;
2267 synchronized (ConnectivityService.this) {
2268 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2269 mNetTransitionWakeLock.isHeld()) {
2270 mNetTransitionWakeLock.release();
2271 causedBy = mNetTransitionWakeLockCausedBy;
2272 }
2273 }
2274 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002275 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002276 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002277 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002278 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002279 FeatureUser u = (FeatureUser)msg.obj;
2280 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002281 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002282 case EVENT_INET_CONDITION_CHANGE:
2283 {
2284 int netType = msg.arg1;
2285 int condition = msg.arg2;
2286 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002287 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002288 }
2289 case EVENT_INET_CONDITION_HOLD_END:
2290 {
2291 int netType = msg.arg1;
2292 int sequence = msg.arg2;
2293 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002294 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002295 }
2296 case EVENT_SET_NETWORK_PREFERENCE:
2297 {
2298 int preference = msg.arg1;
2299 handleSetNetworkPreference(preference);
2300 break;
2301 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002302 case EVENT_SET_MOBILE_DATA:
2303 {
2304 boolean enabled = (msg.arg1 == ENABLED);
2305 handleSetMobileData(enabled);
2306 break;
2307 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002308 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2309 {
2310 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002311 break;
2312 }
2313 case EVENT_SET_DEPENDENCY_MET:
2314 {
2315 boolean met = (msg.arg1 == ENABLED);
2316 handleSetDependencyMet(msg.arg2, met);
2317 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002318 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002319 case EVENT_RESTORE_DNS:
2320 {
2321 if (mActiveDefaultNetwork != -1) {
2322 handleDnsConfigurationChange(mActiveDefaultNetwork);
2323 }
2324 break;
2325 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002326 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2327 {
2328 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002329 sendStickyBroadcast(intent);
2330 break;
2331 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002332 case EVENT_SET_POLICY_DATA_ENABLE: {
2333 final int networkType = msg.arg1;
2334 final boolean enabled = msg.arg2 == ENABLED;
2335 handleSetPolicyDataEnable(networkType, enabled);
2336 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002337 }
2338 }
2339 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002340
2341 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002342 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002343 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002344
2345 if (isTetheringSupported()) {
2346 return mTethering.tether(iface);
2347 } else {
2348 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2349 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002350 }
2351
2352 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002353 public int untether(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.untether(iface);
2358 } else {
2359 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2360 }
2361 }
2362
2363 // javadoc from interface
2364 public int getLastTetherError(String iface) {
2365 enforceTetherAccessPermission();
2366
2367 if (isTetheringSupported()) {
2368 return mTethering.getLastTetherError(iface);
2369 } else {
2370 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2371 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002372 }
2373
2374 // TODO - proper iface API for selection by property, inspection, etc
2375 public String[] getTetherableUsbRegexs() {
2376 enforceTetherAccessPermission();
2377 if (isTetheringSupported()) {
2378 return mTethering.getTetherableUsbRegexs();
2379 } else {
2380 return new String[0];
2381 }
2382 }
2383
2384 public String[] getTetherableWifiRegexs() {
2385 enforceTetherAccessPermission();
2386 if (isTetheringSupported()) {
2387 return mTethering.getTetherableWifiRegexs();
2388 } else {
2389 return new String[0];
2390 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002391 }
2392
Danica Chang96567052010-08-11 14:54:43 -07002393 public String[] getTetherableBluetoothRegexs() {
2394 enforceTetherAccessPermission();
2395 if (isTetheringSupported()) {
2396 return mTethering.getTetherableBluetoothRegexs();
2397 } else {
2398 return new String[0];
2399 }
2400 }
2401
Mike Lockwooded4a1742011-07-19 13:04:47 -07002402 public int setUsbTethering(boolean enable) {
2403 enforceTetherAccessPermission();
2404 if (isTetheringSupported()) {
2405 return mTethering.setUsbTethering(enable);
2406 } else {
2407 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2408 }
2409 }
2410
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002411 // TODO - move iface listing, queries, etc to new module
2412 // javadoc from interface
2413 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002414 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002415 return mTethering.getTetherableIfaces();
2416 }
2417
2418 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002419 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002420 return mTethering.getTetheredIfaces();
2421 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002422
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002423 @Override
2424 public String[] getTetheredIfacePairs() {
2425 enforceTetherAccessPermission();
2426 return mTethering.getTetheredIfacePairs();
2427 }
2428
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002429 public String[] getTetheringErroredIfaces() {
2430 enforceTetherAccessPermission();
2431 return mTethering.getErroredIfaces();
2432 }
2433
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002434 // if ro.tether.denied = true we default to no tethering
2435 // gservices could set the secure setting to 1 though to enable it on a build where it
2436 // had previously been turned off.
2437 public boolean isTetheringSupported() {
2438 enforceTetherAccessPermission();
2439 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002440 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2441 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2442 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002443 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002444
2445 // An API NetworkStateTrackers can call when they lose their network.
2446 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2447 // whichever happens first. The timer is started by the first caller and not
2448 // restarted by subsequent callers.
2449 public void requestNetworkTransitionWakelock(String forWhom) {
2450 enforceConnectivityInternalPermission();
2451 synchronized (this) {
2452 if (mNetTransitionWakeLock.isHeld()) return;
2453 mNetTransitionWakeLockSerialNumber++;
2454 mNetTransitionWakeLock.acquire();
2455 mNetTransitionWakeLockCausedBy = forWhom;
2456 }
2457 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002458 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002459 mNetTransitionWakeLockSerialNumber, 0),
2460 mNetTransitionWakeLockTimeout);
2461 return;
2462 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002463
Robert Greenwalt986c7412010-09-08 15:24:47 -07002464 // 100 percent is full good, 0 is full bad.
2465 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002466 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002467 mContext.enforceCallingOrSelfPermission(
2468 android.Manifest.permission.STATUS_BAR,
2469 "ConnectivityService");
2470
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002471 if (DBG) {
2472 int pid = getCallingPid();
2473 int uid = getCallingUid();
2474 String s = pid + "(" + uid + ") reports inet is " +
2475 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2476 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2477 mInetLog.add(s);
2478 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2479 mInetLog.remove(0);
2480 }
2481 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002482 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002483 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2484 }
2485
2486 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002487 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002488 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002489 return;
2490 }
2491 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002492 if (DBG) log("handleInetConditionChange: net=" + netType +
2493 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002494 return;
2495 }
Wink Savillea7d56572011-09-21 11:05:43 -07002496 if (VDBG) {
2497 log("handleInetConditionChange: net=" +
2498 netType + ", condition=" + condition +
2499 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2500 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002501 mDefaultInetCondition = condition;
2502 int delay;
2503 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002504 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002505 // setup a new hold to debounce this
2506 if (mDefaultInetCondition > 50) {
2507 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2508 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2509 } else {
2510 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2511 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2512 }
2513 mInetConditionChangeInFlight = true;
2514 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2515 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2516 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002517 // we've set the new condition, when this hold ends that will get picked up
2518 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002519 }
2520 }
2521
2522 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002523 if (DBG) {
2524 log("handleInetConditionHoldEnd: net=" + netType +
2525 ", condition=" + mDefaultInetCondition +
2526 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002527 }
2528 mInetConditionChangeInFlight = false;
2529
2530 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002531 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002532 return;
2533 }
2534 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002535 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002536 return;
2537 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002538 // TODO: Figure out why this optimization sometimes causes a
2539 // change in mDefaultInetCondition to be missed and the
2540 // UI to not be updated.
2541 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2542 // if (DBG) log("no change in condition - aborting");
2543 // return;
2544 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002545 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2546 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002547 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002548 return;
2549 }
2550 mDefaultInetConditionPublished = mDefaultInetCondition;
2551 sendInetConditionBroadcast(networkInfo);
2552 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002553 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002554
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002555 public ProxyProperties getProxy() {
2556 synchronized (mDefaultProxyLock) {
2557 return mDefaultProxyDisabled ? null : mDefaultProxy;
2558 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002559 }
2560
2561 public void setGlobalProxy(ProxyProperties proxyProperties) {
2562 enforceChangePermission();
2563 synchronized (mGlobalProxyLock) {
2564 if (proxyProperties == mGlobalProxy) return;
2565 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2566 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2567
2568 String host = "";
2569 int port = 0;
2570 String exclList = "";
2571 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2572 mGlobalProxy = new ProxyProperties(proxyProperties);
2573 host = mGlobalProxy.getHost();
2574 port = mGlobalProxy.getPort();
2575 exclList = mGlobalProxy.getExclusionList();
2576 } else {
2577 mGlobalProxy = null;
2578 }
2579 ContentResolver res = mContext.getContentResolver();
2580 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2581 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002582 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002583 exclList);
2584 }
2585
2586 if (mGlobalProxy == null) {
2587 proxyProperties = mDefaultProxy;
2588 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002589 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002590 }
2591
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002592 private void loadGlobalProxy() {
2593 ContentResolver res = mContext.getContentResolver();
2594 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2595 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2596 String exclList = Settings.Secure.getString(res,
2597 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2598 if (!TextUtils.isEmpty(host)) {
2599 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2600 synchronized (mGlobalProxyLock) {
2601 mGlobalProxy = proxyProperties;
2602 }
2603 }
2604 }
2605
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002606 public ProxyProperties getGlobalProxy() {
2607 synchronized (mGlobalProxyLock) {
2608 return mGlobalProxy;
2609 }
2610 }
2611
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002612 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2613 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2614 proxy = null;
2615 }
2616 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002617 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2618 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002619 mDefaultProxy = proxy;
2620
2621 if (!mDefaultProxyDisabled) {
2622 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002623 }
2624 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002625 }
2626
2627 private void handleDeprecatedGlobalHttpProxy() {
2628 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2629 Settings.Secure.HTTP_PROXY);
2630 if (!TextUtils.isEmpty(proxy)) {
2631 String data[] = proxy.split(":");
2632 String proxyHost = data[0];
2633 int proxyPort = 8080;
2634 if (data.length > 1) {
2635 try {
2636 proxyPort = Integer.parseInt(data[1]);
2637 } catch (NumberFormatException e) {
2638 return;
2639 }
2640 }
2641 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2642 setGlobalProxy(p);
2643 }
2644 }
2645
2646 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002647 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002648 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002649 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002650 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2651 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002652 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002653 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002654 }
2655
2656 private static class SettingsObserver extends ContentObserver {
2657 private int mWhat;
2658 private Handler mHandler;
2659 SettingsObserver(Handler handler, int what) {
2660 super(handler);
2661 mHandler = handler;
2662 mWhat = what;
2663 }
2664
2665 void observe(Context context) {
2666 ContentResolver resolver = context.getContentResolver();
2667 resolver.registerContentObserver(Settings.Secure.getUriFor(
2668 Settings.Secure.HTTP_PROXY), false, this);
2669 }
2670
2671 @Override
2672 public void onChange(boolean selfChange) {
2673 mHandler.obtainMessage(mWhat).sendToTarget();
2674 }
2675 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002676
2677 private void log(String s) {
2678 Slog.d(TAG, s);
2679 }
2680
2681 private void loge(String s) {
2682 Slog.e(TAG, s);
2683 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002684
repo syncf5de5572011-07-29 23:55:49 -07002685 int convertFeatureToNetworkType(int networkType, String feature) {
2686 int usedNetworkType = networkType;
2687
2688 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2689 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2690 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2691 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2692 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2693 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2694 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2695 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2696 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2697 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2698 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2699 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2700 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2701 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2702 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2703 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2704 } else {
2705 Slog.e(TAG, "Can't match any mobile netTracker!");
2706 }
2707 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2708 if (TextUtils.equals(feature, "p2p")) {
2709 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2710 } else {
2711 Slog.e(TAG, "Can't match any wifi netTracker!");
2712 }
2713 } else {
2714 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002715 }
repo syncf5de5572011-07-29 23:55:49 -07002716 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002717 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002718
2719 private static <T> T checkNotNull(T value, String message) {
2720 if (value == null) {
2721 throw new NullPointerException(message);
2722 }
2723 return value;
2724 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002725
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002726 /**
2727 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002728 * VpnBuilder and not available in ConnectivityManager. Permissions
2729 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002730 * @hide
2731 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002732 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002733 public boolean protectVpn(ParcelFileDescriptor socket) {
2734 try {
2735 int type = mActiveDefaultNetwork;
2736 if (ConnectivityManager.isNetworkTypeValid(type)) {
2737 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2738 return true;
2739 }
2740 } catch (Exception e) {
2741 // ignore
2742 } finally {
2743 try {
2744 socket.close();
2745 } catch (Exception e) {
2746 // ignore
2747 }
2748 }
2749 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002750 }
2751
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002752 /**
2753 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002754 * and not available in ConnectivityManager. Permissions are checked
2755 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002756 * @hide
2757 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002758 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002759 public boolean prepareVpn(String oldPackage, String newPackage) {
2760 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002761 }
2762
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002763 /**
2764 * Configure a TUN interface and return its file descriptor. Parameters
2765 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002766 * and not available in ConnectivityManager. Permissions are checked in
2767 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002768 * @hide
2769 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002770 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002771 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002772 return mVpn.establish(config);
2773 }
2774
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002775 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002776 * Start legacy VPN and return an intent to VpnDialogs. This method is
2777 * used by VpnSettings and not available in ConnectivityManager.
2778 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002779 * @hide
2780 */
2781 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002782 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2783 mVpn.startLegacyVpn(config, racoon, mtpd);
2784 }
2785
2786 /**
2787 * Return the information of the ongoing legacy VPN. This method is used
2788 * by VpnSettings and not available in ConnectivityManager. Permissions
2789 * are checked in Vpn class.
2790 * @hide
2791 */
2792 @Override
2793 public LegacyVpnInfo getLegacyVpnInfo() {
2794 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002795 }
2796
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002797 /**
2798 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2799 * through NetworkStateTracker since it works differently. For example, it
2800 * needs to override DNS servers but never takes the default routes. It
2801 * relies on another data network, and it could keep existing connections
2802 * alive after reconnecting, switching between networks, or even resuming
2803 * from deep sleep. Calls from applications should be done synchronously
2804 * to avoid race conditions. As these are all hidden APIs, refactoring can
2805 * be done whenever a better abstraction is developed.
2806 */
2807 public class VpnCallback {
2808
2809 private VpnCallback() {
2810 }
2811
Chia-chi Yehcc844502011-07-14 18:01:57 -07002812 public void override(List<String> dnsServers, List<String> searchDomains) {
2813 if (dnsServers == null) {
2814 restore();
2815 return;
2816 }
2817
2818 // Convert DNS servers into addresses.
2819 List<InetAddress> addresses = new ArrayList<InetAddress>();
2820 for (String address : dnsServers) {
2821 // Double check the addresses and remove invalid ones.
2822 try {
2823 addresses.add(InetAddress.parseNumericAddress(address));
2824 } catch (Exception e) {
2825 // ignore
2826 }
2827 }
2828 if (addresses.isEmpty()) {
2829 restore();
2830 return;
2831 }
2832
2833 // Concatenate search domains into a string.
2834 StringBuilder buffer = new StringBuilder();
2835 if (searchDomains != null) {
2836 for (String domain : searchDomains) {
2837 buffer.append(domain).append(' ');
2838 }
2839 }
2840 String domains = buffer.toString().trim();
2841
2842 // Apply DNS changes.
2843 boolean changed = false;
2844 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002845 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002846 mDnsOverridden = true;
2847 }
2848 if (changed) {
2849 bumpDns();
2850 }
2851
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002852 // Temporarily disable the default proxy.
2853 synchronized (mDefaultProxyLock) {
2854 mDefaultProxyDisabled = true;
2855 if (mDefaultProxy != null) {
2856 sendProxyBroadcast(null);
2857 }
2858 }
2859
2860 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002861 }
2862
Chia-chi Yehcc844502011-07-14 18:01:57 -07002863 public void restore() {
2864 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002865 if (mDnsOverridden) {
2866 mDnsOverridden = false;
2867 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002868 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002869 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002870 synchronized (mDefaultProxyLock) {
2871 mDefaultProxyDisabled = false;
2872 if (mDefaultProxy != null) {
2873 sendProxyBroadcast(mDefaultProxy);
2874 }
2875 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002876 }
2877 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002878}