blob: e0a2adc0fd70659e44fcb1a2ed448a2fc6df19d6 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070022import static android.net.ConnectivityManager.isNetworkTypeValid;
23import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070024import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080026import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070031import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080033import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080034import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070036import android.net.INetworkPolicyListener;
37import android.net.INetworkPolicyManager;
Wink Savillec9822c52011-07-14 12:23:28 -070038import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080039import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070040import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070042import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070044import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070045import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070046import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070048import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.net.Proxy;
50import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070051import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.wifi.WifiStateTracker;
53import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040054import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070056import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070057import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070058import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Looper;
60import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070061import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070062import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070063import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.ServiceManager;
65import android.os.SystemProperties;
66import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070067import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080069import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070070import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Chia-chi Yeh2e467642011-07-04 03:23:12 -070072import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070073import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070074import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080075import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070076import com.android.server.connectivity.Vpn;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070077import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070078import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070081import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -070083import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070084import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070085import java.net.InetAddress;
86import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070088import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070089import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070090import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070091import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94/**
95 * @hide
96 */
97public class ConnectivityService extends IConnectivityManager.Stub {
98
Robert Greenwaltba175a52010-10-05 19:12:26 -070099 private static final boolean DBG = true;
Wink Savillee8222252011-07-13 13:44:13 -0700100 private static final boolean VDBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final String TAG = "ConnectivityService";
102
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103 private static final boolean LOGD_RULES = false;
104
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105 // how long to wait before switching back to a radio's default network
106 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
107 // system property that can override the above value
108 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
109 "android.telephony.apn-restore";
110
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700111 // used in recursive route setting to add gateways for the host for which
112 // a host route was requested.
113 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
114
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800115 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800116 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800117
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700118 private Vpn mVpn;
119
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
121 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122 /** Currently active network rules by UID. */
123 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700124 /** Set of ifaces that are costly. */
125 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 /**
128 * Sometimes we want to refer to the individual network state
129 * trackers separately, and sometimes we just want to treat them
130 * abstractly.
131 */
132 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700133
134 /**
Wink Savillee8222252011-07-13 13:44:13 -0700135 * The link properties that define the current links
136 */
137 private LinkProperties mCurrentLinkProperties[];
138
139 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700140 * A per Net list of the PID's that requested access to the net
141 * used both as a refcount and for per-PID DNS selection
142 */
143 private List mNetRequestersPids[];
144
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145 // priority order of the nettrackers
146 // (excluding dynamically set mNetworkPreference)
147 // TODO - move mNetworkTypePreference into this
148 private int[] mPriorityList;
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private Context mContext;
151 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700153 // 0 is full bad, 100 is full good
154 private int mDefaultInetCondition = 0;
155 private int mDefaultInetConditionPublished = 0;
156 private boolean mInetConditionChangeInFlight = false;
157 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700159 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700161 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700164 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700166 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700167 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700168
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700169 private static final int ENABLED = 1;
170 private static final int DISABLED = 0;
171
172 // Share the event space with NetworkStateTracker (which can't see this
173 // internal class but sends us events). If you change these, change
174 // NetworkStateTracker.java too.
175 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
176 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
177
178 /**
179 * used internally as a delayed event to make us switch back to the
180 * default network
181 */
182 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
183 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
184
185 /**
186 * used internally to change our mobile data enabled flag
187 */
188 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
189 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
190
191 /**
192 * used internally to change our network preference setting
193 * arg1 = networkType to prefer
194 */
195 private static final int EVENT_SET_NETWORK_PREFERENCE =
196 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
197
198 /**
199 * used internally to synchronize inet condition reports
200 * arg1 = networkType
201 * arg2 = condition (0 bad, 100 good)
202 */
203 private static final int EVENT_INET_CONDITION_CHANGE =
204 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
205
206 /**
207 * used internally to mark the end of inet condition hold periods
208 * arg1 = networkType
209 */
210 private static final int EVENT_INET_CONDITION_HOLD_END =
211 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
212
213 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700214 * used internally to set enable/disable cellular data
215 * arg1 = ENBALED or DISABLED
216 */
217 private static final int EVENT_SET_MOBILE_DATA =
218 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
219
Robert Greenwaltf3331232010-09-24 14:32:21 -0700220 /**
221 * used internally to clear a wakelock when transitioning
222 * from one net to another
223 */
224 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
225 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
226
Robert Greenwalt434203a2010-10-11 16:00:27 -0700227 /**
228 * used internally to reload global proxy settings
229 */
230 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
231 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
232
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700233 /**
234 * used internally to set external dependency met/unmet
235 * arg1 = ENABLED (met) or DISABLED (unmet)
236 * arg2 = NetworkType
237 */
238 private static final int EVENT_SET_DEPENDENCY_MET =
239 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
240
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700241 /**
242 * used internally to restore DNS properties back to the
243 * default network
244 */
245 private static final int EVENT_RESTORE_DNS =
246 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
247
Wink Saville2b30afd2011-08-05 11:40:22 -0700248 /**
Wink Saville628b0852011-08-04 15:01:58 -0700249 * used internally to send a sticky broadcast delayed.
250 */
251 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville2b30afd2011-08-05 11:40:22 -0700252 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville628b0852011-08-04 15:01:58 -0700253
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700254 /**
255 * Used internally to
256 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
257 */
258 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
259
Robert Greenwalt42acef32009-08-12 16:08:25 -0700260 private Handler mHandler;
261
262 // list of DeathRecipients used to make sure features are turned off when
263 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500264 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700265
Mike Lockwood0f79b542009-08-14 14:18:49 -0400266 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800267 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400268
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700269 private PowerManager.WakeLock mNetTransitionWakeLock;
270 private String mNetTransitionWakeLockCausedBy = "";
271 private int mNetTransitionWakeLockSerialNumber;
272 private int mNetTransitionWakeLockTimeout;
273
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700274 private InetAddress mDefaultDns;
275
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700276 // this collection is used to refcount the added routes - if there are none left
277 // it's time to remove the route from the route table
278 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
279
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700280 // used in DBG mode to track inet condition reports
281 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
282 private ArrayList mInetLog;
283
Robert Greenwalt434203a2010-10-11 16:00:27 -0700284 // track the current default http proxy - tell the world if we get a new one (real change)
285 private ProxyProperties mDefaultProxy = null;
286 // track the global proxy.
287 private ProxyProperties mGlobalProxy = null;
288 private final Object mGlobalProxyLock = new Object();
289
290 private SettingsObserver mSettingsObserver;
291
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700292 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700293 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700294
Robert Greenwalt511288a2009-12-07 11:33:18 -0800295 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700296 public int mSimultaneity;
297 public int mType;
298 public RadioAttributes(String init) {
299 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700300 mType = Integer.parseInt(fragments[0]);
301 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700302 }
303 }
304 RadioAttributes[] mRadioAttributes;
305
Robert Greenwalt50393202011-06-21 17:26:14 -0700306 // the set of network types that can only be enabled by system/sig apps
307 List mProtectedNetworks;
308
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700309 public ConnectivityService(
310 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800311 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800312
Wink Savillebb08caf2010-09-02 19:23:52 -0700313 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
314 handlerThread.start();
315 mHandler = new MyHandler(handlerThread.getLooper());
316
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800317 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800318 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
319 String id = Settings.Secure.getString(context.getContentResolver(),
320 Settings.Secure.ANDROID_ID);
321 if (id != null && id.length() > 0) {
322 String name = new String("android_").concat(id);
323 SystemProperties.set("net.hostname", name);
324 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800325 }
326
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700327 // read our default dns server ip
328 String dns = Settings.Secure.getString(context.getContentResolver(),
329 Settings.Secure.DEFAULT_DNS_SERVER);
330 if (dns == null || dns.length() == 0) {
331 dns = context.getResources().getString(
332 com.android.internal.R.string.config_default_dns_server);
333 }
334 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800335 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
336 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800337 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700338 }
339
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700340 mContext = checkNotNull(context, "missing Context");
341 mNetd = checkNotNull(netd, "missing INetworkManagementService");
342 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700343
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700344 try {
345 mPolicyManager.registerListener(mPolicyListener);
346 } catch (RemoteException e) {
347 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700348 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700349 }
350
351 final PowerManager powerManager = (PowerManager) context.getSystemService(
352 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700353 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
354 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
355 com.android.internal.R.integer.config_networkTransitionTimeout);
356
Robert Greenwalt42acef32009-08-12 16:08:25 -0700357 mNetTrackers = new NetworkStateTracker[
358 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700359 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700362
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700363 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700364 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700365
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700367 String[] raStrings = context.getResources().getStringArray(
368 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700369 for (String raString : raStrings) {
370 RadioAttributes r = new RadioAttributes(raString);
371 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800372 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700373 continue;
374 }
375 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800376 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700377 r.mType);
378 continue;
379 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700380 mRadioAttributes[r.mType] = r;
381 }
382
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700383 String[] naStrings = context.getResources().getStringArray(
384 com.android.internal.R.array.networkAttributes);
385 for (String naString : naStrings) {
386 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700387 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700388 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700390 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700391 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700392 }
Wink Saville975c8482011-04-07 14:23:45 -0700393 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800394 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700395 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700396 continue;
397 }
Wink Saville975c8482011-04-07 14:23:45 -0700398 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800399 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700400 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700401 continue;
402 }
Wink Saville975c8482011-04-07 14:23:45 -0700403 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700404 mNetworksDefined++;
405 } catch(Exception e) {
406 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407 }
408 }
409
Robert Greenwalt50393202011-06-21 17:26:14 -0700410 mProtectedNetworks = new ArrayList<Integer>();
411 int[] protectedNetworks = context.getResources().getIntArray(
412 com.android.internal.R.array.config_protectedNetworks);
413 for (int p : protectedNetworks) {
414 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
415 mProtectedNetworks.add(p);
416 } else {
417 if (DBG) loge("Ignoring protectedNetwork " + p);
418 }
419 }
420
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700421 // high priority first
422 mPriorityList = new int[mNetworksDefined];
423 {
424 int insertionPoint = mNetworksDefined-1;
425 int currentLowest = 0;
426 int nextLowest = 0;
427 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700428 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700430 if (na.priority < currentLowest) continue;
431 if (na.priority > currentLowest) {
432 if (na.priority < nextLowest || nextLowest == 0) {
433 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700434 }
435 continue;
436 }
Wink Saville975c8482011-04-07 14:23:45 -0700437 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700438 }
439 currentLowest = nextLowest;
440 nextLowest = 0;
441 }
442 }
443
444 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
445 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700446 mNetRequestersPids[i] = new ArrayList();
447 }
448
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500449 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700450
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700451 mNumDnsEntries = 0;
452
453 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
454 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 /*
456 * Create the network state trackers for Wi-Fi and mobile
457 * data. Maybe this could be done with a factory class,
458 * but it's not clear that it's worth it, given that
459 * the number of different network types is not going
460 * to change very often.
461 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700462 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700463 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700464 case ConnectivityManager.TYPE_WIFI:
repo syncaea743a2011-07-29 23:55:49 -0700465 mNetTrackers[netType] = new WifiStateTracker(netType,
466 mNetConfigs[netType].name);
467 mNetTrackers[netType].startMonitoring(context, mHandler);
468 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700469 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700470 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700471 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700472 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700473 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800474 case ConnectivityManager.TYPE_DUMMY:
475 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700476 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800477 mNetTrackers[netType].startMonitoring(context, mHandler);
478 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800479 case ConnectivityManager.TYPE_BLUETOOTH:
480 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
481 mNetTrackers[netType].startMonitoring(context, mHandler);
482 break;
Benoit Goby19970692010-12-22 14:29:40 -0800483 case ConnectivityManager.TYPE_ETHERNET:
484 mNetTrackers[netType] = EthernetDataTracker.getInstance();
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700487 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800488 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700489 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700490 continue;
491 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700492 mCurrentLinkProperties[netType] = null;
Robert Greenwaltc96e6cc2011-07-15 11:16:45 -0700493 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700494 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800495
Chia-chi Yehc9338302011-05-11 16:35:13 -0700496 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
497 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
498
499 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700500 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700501 mTethering.getTetherableWifiRegexs().length != 0 ||
502 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700503 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800504
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700505 mVpn = new Vpn(mContext, new VpnCallback());
506
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700507 try {
508 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700509 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700510 } catch (RemoteException e) {
511 loge("Error registering observer :" + e);
512 }
513
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700514 if (DBG) {
515 mInetLog = new ArrayList();
516 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700517
518 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
519 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800520
521 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523
524 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700525 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * @param preference the new preference
527 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700528 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700530
531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 }
533
534 public int getNetworkPreference() {
535 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700536 int preference;
537 synchronized(this) {
538 preference = mNetworkPreference;
539 }
540 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700543 private void handleSetNetworkPreference(int preference) {
544 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700545 mNetConfigs[preference] != null &&
546 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700547 if (mNetworkPreference != preference) {
548 final ContentResolver cr = mContext.getContentResolver();
549 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
550 synchronized(this) {
551 mNetworkPreference = preference;
552 }
553 enforcePreference();
554 }
555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700557
Wink Saville628b0852011-08-04 15:01:58 -0700558 private int getConnectivityChangeDelay() {
559 final ContentResolver cr = mContext.getContentResolver();
560
561 /** Check system properties for the default value then use secure settings value, if any. */
562 int defaultDelay = SystemProperties.getInt(
563 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
564 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
565 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
566 defaultDelay);
567 }
568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 private int getPersistedNetworkPreference() {
570 final ContentResolver cr = mContext.getContentResolver();
571
572 final int networkPrefSetting = Settings.Secure
573 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
574 if (networkPrefSetting != -1) {
575 return networkPrefSetting;
576 }
577
578 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
579 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700582 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 * In this method, we only tear down a non-preferred network. Establishing
584 * a connection to the preferred network is taken care of when we handle
585 * the disconnect event from the non-preferred network
586 * (see {@link #handleDisconnect(NetworkInfo)}).
587 */
588 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700589 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 return;
591
Robert Greenwalt42acef32009-08-12 16:08:25 -0700592 if (!mNetTrackers[mNetworkPreference].isAvailable())
593 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594
Robert Greenwalt42acef32009-08-12 16:08:25 -0700595 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700596 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700597 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700598 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800599 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700600 " in enforcePreference");
601 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700602 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
604 }
605 }
606
607 private boolean teardown(NetworkStateTracker netTracker) {
608 if (netTracker.teardown()) {
609 netTracker.setTeardownRequested(true);
610 return true;
611 } else {
612 return false;
613 }
614 }
615
616 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700617 * Check if UID should be blocked from using the network represented by the
618 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700619 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700620 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
621 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700622
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700623 final boolean networkCostly;
624 final int uidRules;
625 synchronized (mRulesLock) {
626 networkCostly = mMeteredIfaces.contains(iface);
627 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700628 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700629
630 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
631 return true;
632 }
633
634 // no restrictive rules; network is visible
635 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700636 }
637
638 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700639 * Return a filtered {@link NetworkInfo}, potentially marked
640 * {@link DetailedState#BLOCKED} based on
641 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700642 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700643 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
644 NetworkInfo info = tracker.getNetworkInfo();
645 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700646 // network is blocked; clone and override state
647 info = new NetworkInfo(info);
648 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700650 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700651 }
652
653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 * Return NetworkInfo for the active (i.e., connected) network interface.
655 * It is assumed that at most one network is active at a time. If more
656 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700657 * @return the info for the active network, or {@code null} if none is
658 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 enforceAccessPermission();
663 final int uid = Binder.getCallingUid();
664 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 }
666
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700667 @Override
668 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
669 enforceConnectivityInternalPermission();
670 return getNetworkInfo(mActiveDefaultNetwork, uid);
671 }
672
673 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 public NetworkInfo getNetworkInfo(int networkType) {
675 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700676 final int uid = Binder.getCallingUid();
677 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
679
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700680 private NetworkInfo getNetworkInfo(int networkType, int uid) {
681 NetworkInfo info = null;
682 if (isNetworkTypeValid(networkType)) {
683 final NetworkStateTracker tracker = mNetTrackers[networkType];
684 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700685 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700686 }
687 }
688 return info;
689 }
690
691 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 public NetworkInfo[] getAllNetworkInfo() {
693 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700694 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700695 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700696 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700697 for (NetworkStateTracker tracker : mNetTrackers) {
698 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700699 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700700 }
701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700703 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
705
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700706 @Override
707 public boolean isNetworkSupported(int networkType) {
708 enforceAccessPermission();
709 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
710 }
711
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700712 /**
713 * Return LinkProperties for the active (i.e., connected) default
714 * network interface. It is assumed that at most one default network
715 * is active at a time. If more than one is active, it is indeterminate
716 * which will be returned.
717 * @return the ip properties for the active network, or {@code null} if
718 * none is active
719 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700720 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700721 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700722 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700723 }
724
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700725 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700726 public LinkProperties getLinkProperties(int networkType) {
727 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 if (isNetworkTypeValid(networkType)) {
729 final NetworkStateTracker tracker = mNetTrackers[networkType];
730 if (tracker != null) {
731 return tracker.getLinkProperties();
732 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700733 }
734 return null;
735 }
736
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700737 @Override
738 public NetworkState[] getAllNetworkState() {
739 enforceAccessPermission();
740 final int uid = Binder.getCallingUid();
741 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700742 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700743 for (NetworkStateTracker tracker : mNetTrackers) {
744 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700745 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700746 result.add(new NetworkState(
747 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
748 }
749 }
750 }
751 return result.toArray(new NetworkState[result.size()]);
752 }
753
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700754 private NetworkState getNetworkStateUnchecked(int networkType) {
755 if (isNetworkTypeValid(networkType)) {
756 final NetworkStateTracker tracker = mNetTrackers[networkType];
757 if (tracker != null) {
758 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
759 tracker.getLinkCapabilities());
760 }
761 }
762 return null;
763 }
764
765 @Override
766 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
767 enforceAccessPermission();
768 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
769 if (state != null) {
770 try {
771 return mPolicyManager.getNetworkQuotaInfo(state);
772 } catch (RemoteException e) {
773 }
774 }
775 return null;
776 }
777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 public boolean setRadios(boolean turnOn) {
779 boolean result = true;
780 enforceChangePermission();
781 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700782 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 }
784 return result;
785 }
786
787 public boolean setRadio(int netType, boolean turnOn) {
788 enforceChangePermission();
789 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
790 return false;
791 }
792 NetworkStateTracker tracker = mNetTrackers[netType];
793 return tracker != null && tracker.setRadio(turnOn);
794 }
795
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700796 /**
797 * Used to notice when the calling process dies so we can self-expire
798 *
799 * Also used to know if the process has cleaned up after itself when
800 * our auto-expire timer goes off. The timer has a link to an object.
801 *
802 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700803 private class FeatureUser implements IBinder.DeathRecipient {
804 int mNetworkType;
805 String mFeature;
806 IBinder mBinder;
807 int mPid;
808 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800809 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700810
811 FeatureUser(int type, String feature, IBinder binder) {
812 super();
813 mNetworkType = type;
814 mFeature = feature;
815 mBinder = binder;
816 mPid = getCallingPid();
817 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800818 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700819
Robert Greenwalt42acef32009-08-12 16:08:25 -0700820 try {
821 mBinder.linkToDeath(this, 0);
822 } catch (RemoteException e) {
823 binderDied();
824 }
825 }
826
827 void unlinkDeathRecipient() {
828 mBinder.unlinkToDeath(this, 0);
829 }
830
831 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800832 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800833 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
834 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700835 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700836 }
837
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700838 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700839 if (VDBG) {
840 log("ConnectivityService FeatureUser expire(" +
841 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
842 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
843 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700844 stopUsingNetworkFeature(this, false);
845 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800846
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500847 public boolean isSameUser(FeatureUser u) {
848 if (u == null) return false;
849
850 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
851 }
852
853 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
854 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
855 TextUtils.equals(mFeature, feature)) {
856 return true;
857 }
858 return false;
859 }
860
Robert Greenwaltb9285352009-12-21 18:24:07 -0800861 public String toString() {
862 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
863 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
864 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700865 }
866
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700867 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700868 public int startUsingNetworkFeature(int networkType, String feature,
869 IBinder binder) {
870 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800871 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700874 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700875 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700876 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700878
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700879 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700880
repo syncaea743a2011-07-29 23:55:49 -0700881 // TODO - move this into individual networktrackers
882 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -0700883
884 if (mProtectedNetworks.contains(usedNetworkType)) {
885 enforceConnectivityInternalPermission();
886 }
887
Robert Greenwalt42acef32009-08-12 16:08:25 -0700888 NetworkStateTracker network = mNetTrackers[usedNetworkType];
889 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800890 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700891 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 NetworkInfo ni = network.getNetworkInfo();
893
894 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800895 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800896 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
897 return Phone.APN_TYPE_NOT_AVAILABLE;
898 } else {
899 // else make the attempt anyway - probably giving REQUEST_STARTED below
900 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700901 }
902
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500903 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
904
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700905 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500906 boolean addToList = true;
907 if (restoreTimer < 0) {
908 // In case there is no timer is specified for the feature,
909 // make sure we don't add duplicate entry with the same request.
910 for (FeatureUser u : mFeatureUsers) {
911 if (u.isSameUser(f)) {
912 // Duplicate user is found. Do not add.
913 addToList = false;
914 break;
915 }
916 }
917 }
918
919 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700920 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
921 // this gets used for per-pid dns when connected
922 mNetRequestersPids[usedNetworkType].add(currentPid);
923 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700924 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700925
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700926 if (restoreTimer >= 0) {
927 mHandler.sendMessageDelayed(
928 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
929 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700930
Robert Greenwalta64bf832009-08-19 20:19:33 -0700931 if ((ni.isConnectedOrConnecting() == true) &&
932 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700933 if (ni.isConnected() == true) {
934 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -0700935 handleDnsConfigurationChange(usedNetworkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800936 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700937 return Phone.APN_ALREADY_ACTIVE;
938 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800939 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700940 return Phone.APN_REQUEST_STARTED;
941 }
942
943 // check if the radio in play can make another contact
944 // assume if cannot for now
945
Wink Savilleed9c02b2010-12-03 12:01:38 -0800946 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700947 network.reconnect();
948 return Phone.APN_REQUEST_STARTED;
949 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800950 // need to remember this unsupported request so we respond appropriately on stop
951 synchronized(this) {
952 mFeatureUsers.add(f);
953 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
954 // this gets used for per-pid dns when connected
955 mNetRequestersPids[usedNetworkType].add(currentPid);
956 }
957 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700958 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700959 }
960 }
961 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
963
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700964 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700966 enforceChangePermission();
967
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700968 int pid = getCallingPid();
969 int uid = getCallingUid();
970
971 FeatureUser u = null;
972 boolean found = false;
973
974 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500975 for (FeatureUser x : mFeatureUsers) {
976 if (x.isSameUser(pid, uid, networkType, feature)) {
977 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700978 found = true;
979 break;
980 }
981 }
982 }
983 if (found && u != null) {
984 // stop regardless of how many other time this proc had called start
985 return stopUsingNetworkFeature(u, true);
986 } else {
987 // none found!
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700988 if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700989 return 1;
990 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700991 }
992
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700993 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
994 int networkType = u.mNetworkType;
995 String feature = u.mFeature;
996 int pid = u.mPid;
997 int uid = u.mUid;
998
999 NetworkStateTracker tracker = null;
1000 boolean callTeardown = false; // used to carry our decision outside of sync block
1001
Robert Greenwalt42acef32009-08-12 16:08:25 -07001002 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001003 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001004 ": " + feature);
1005 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1008 return -1;
1009 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001010
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001011 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1012 // sync block
1013 synchronized(this) {
1014 // check if this process still has an outstanding start request
1015 if (!mFeatureUsers.contains(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001016 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001017 return 1;
1018 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001019 u.unlinkDeathRecipient();
1020 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1021 // If we care about duplicate requests, check for that here.
1022 //
1023 // This is done to support the extension of a request - the app
1024 // can request we start the network feature again and renew the
1025 // auto-shutoff delay. Normal "stop" calls from the app though
1026 // do not pay attention to duplicate requests - in effect the
1027 // API does not refcount and a single stop will counter multiple starts.
1028 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001029 for (FeatureUser x : mFeatureUsers) {
1030 if (x.isSameUser(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001031 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001032 return 1;
1033 }
1034 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001035 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001036
repo syncaea743a2011-07-29 23:55:49 -07001037 // TODO - move to individual network trackers
1038 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1039
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001040 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001041 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001042 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001043 return -1;
1044 }
1045 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001046 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001047 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001048 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001049 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001050 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001051 "others still using it");
1052 return 1;
1053 }
1054 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001055 } else {
1056 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001057 }
1058 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001059 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001060 if (callTeardown) {
1061 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001062 return 1;
1063 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001064 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067
1068 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001069 * @deprecated use requestRouteToHostAddress instead
1070 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 * Ensure that a network route exists to deliver traffic to the specified
1072 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001073 * @param networkType the type of the network over which traffic to the
1074 * specified host is to be routed
1075 * @param hostAddress the IP address of the host to which the route is
1076 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 * @return {@code true} on success, {@code false} on failure
1078 */
1079 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001080 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1081
1082 if (inetAddress == null) {
1083 return false;
1084 }
1085
1086 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1087 }
1088
1089 /**
1090 * Ensure that a network route exists to deliver traffic to the specified
1091 * host via the specified network interface.
1092 * @param networkType the type of the network over which traffic to the
1093 * specified host is to be routed
1094 * @param hostAddress the IP address of the host to which the route is
1095 * desired
1096 * @return {@code true} on success, {@code false} on failure
1097 */
1098 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001100 if (mProtectedNetworks.contains(networkType)) {
1101 enforceConnectivityInternalPermission();
1102 }
1103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1105 return false;
1106 }
1107 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001108
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001109 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1110 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001111 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001112 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001113 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001114 }
1115 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001117 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001118 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001119 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001120 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001121 } catch (UnknownHostException e) {}
1122 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001123 }
1124
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001125 private boolean addRoute(LinkProperties p, RouteInfo r) {
1126 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001127 }
1128
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001129 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1130 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1131 }
1132
Robert Greenwaltad55d352011-07-22 11:55:33 -07001133 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1134 return modifyRouteToAddress(lp, addr, true);
1135 }
1136
1137 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1138 return modifyRouteToAddress(lp, addr, false);
1139 }
1140
1141 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1142 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1143 if (bestRoute == null) {
1144 bestRoute = RouteInfo.makeHostRoute(addr);
1145 } else {
1146 if (bestRoute.getGateway().equals(addr)) {
1147 // if there is no better route, add the implied hostroute for our gateway
1148 bestRoute = RouteInfo.makeHostRoute(addr);
1149 } else {
1150 // if we will connect to this through another route, add a direct route
1151 // to it's gateway
1152 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1153 }
1154 }
1155 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1156 }
1157
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001158 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1159 boolean doAdd) {
1160 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1161
1162 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1163 loge("Error adding route - too much recursion");
1164 return false;
1165 }
1166
1167 if (r.isHostRoute() == false) {
1168 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1169 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001170 if (bestRoute.getGateway().equals(r.getGateway())) {
1171 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001172 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001173 } else {
1174 // if we will connect to our gateway through another route, add a direct
1175 // route to it's gateway
1176 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001177 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001178 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001179 }
1180 }
1181 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001182 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001183 mAddedRoutes.add(r);
1184 try {
1185 mNetd.addRoute(ifaceName, r);
1186 } catch (Exception e) {
1187 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001188 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001189 return false;
1190 }
1191 } else {
1192 // if we remove this one and there are no more like it, then refcount==0 and
1193 // we can remove it from the table
1194 mAddedRoutes.remove(r);
1195 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001196 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001197 try {
1198 mNetd.removeRoute(ifaceName, r);
1199 } catch (Exception e) {
1200 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001201 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001202 return false;
1203 }
1204 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001205 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001206 }
1207 }
1208 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210
1211 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001212 * @see ConnectivityManager#getMobileDataEnabled()
1213 */
1214 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001215 // TODO: This detail should probably be in DataConnectionTracker's
1216 // which is where we store the value and maybe make this
1217 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001218 enforceAccessPermission();
1219 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1220 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001221 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001222 return retVal;
1223 }
1224
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001225 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001226 enforceConnectivityInternalPermission();
1227
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1229 (met ? ENABLED : DISABLED), networkType));
1230 }
1231
1232 private void handleSetDependencyMet(int networkType, boolean met) {
1233 if (mNetTrackers[networkType] != null) {
1234 if (DBG) {
1235 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1236 }
1237 mNetTrackers[networkType].setDependencyMet(met);
1238 }
1239 }
1240
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001241 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1242 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001243 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001245 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001246
1247 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001248 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001249 }
1250
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001251 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001252 // skip update when we've already applied rules
1253 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1254 if (oldRules == uidRules) return;
1255
1256 mUidRules.put(uid, uidRules);
1257 }
1258
1259 // TODO: dispatch into NMS to push rules towards kernel module
1260 // TODO: notify UID when it has requested targeted updates
1261 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001262
1263 @Override
1264 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1265 // only someone like NPMS should only be calling us
1266 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1267
1268 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001269 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001270 }
1271
1272 synchronized (mRulesLock) {
1273 mMeteredIfaces.clear();
1274 for (String iface : meteredIfaces) {
1275 mMeteredIfaces.add(iface);
1276 }
1277 }
1278 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001279 };
1280
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001281 /**
1282 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1283 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001284 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001285 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001286 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001287
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001288 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001289 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001290 }
1291
1292 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001293 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001294 if (VDBG) {
1295 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001296 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001297 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1298 }
1299 }
1300
1301 @Override
1302 public void setPolicyDataEnable(int networkType, boolean enabled) {
1303 // only someone like NPMS should only be calling us
1304 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1305
1306 mHandler.sendMessage(mHandler.obtainMessage(
1307 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1308 }
1309
1310 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1311 if (isNetworkTypeValid(networkType)) {
1312 final NetworkStateTracker tracker = mNetTrackers[networkType];
1313 if (tracker != null) {
1314 tracker.setPolicyDataEnable(enabled);
1315 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001316 }
1317 }
1318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001320 mContext.enforceCallingOrSelfPermission(
1321 android.Manifest.permission.ACCESS_NETWORK_STATE,
1322 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
1325 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001326 mContext.enforceCallingOrSelfPermission(
1327 android.Manifest.permission.CHANGE_NETWORK_STATE,
1328 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001331 // TODO Make this a special check when it goes public
1332 private void enforceTetherChangePermission() {
1333 mContext.enforceCallingOrSelfPermission(
1334 android.Manifest.permission.CHANGE_NETWORK_STATE,
1335 "ConnectivityService");
1336 }
1337
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001338 private void enforceTetherAccessPermission() {
1339 mContext.enforceCallingOrSelfPermission(
1340 android.Manifest.permission.ACCESS_NETWORK_STATE,
1341 "ConnectivityService");
1342 }
1343
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001344 private void enforceConnectivityInternalPermission() {
1345 mContext.enforceCallingOrSelfPermission(
1346 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1347 "ConnectivityService");
1348 }
1349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001351 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1352 * network, we ignore it. If it is for the active network, we send out a
1353 * broadcast. But first, we check whether it might be possible to connect
1354 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 * @param info the {@code NetworkInfo} for the network
1356 */
1357 private void handleDisconnect(NetworkInfo info) {
1358
Robert Greenwalt42acef32009-08-12 16:08:25 -07001359 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360
Robert Greenwalt42acef32009-08-12 16:08:25 -07001361 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 /*
1363 * If the disconnected network is not the active one, then don't report
1364 * this as a loss of connectivity. What probably happened is that we're
1365 * getting the disconnect for a network that we explicitly disabled
1366 * in accordance with network preference policies.
1367 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001368 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001369 List pids = mNetRequestersPids[prevNetType];
1370 for (int i = 0; i<pids.size(); i++) {
1371 Integer pid = (Integer)pids.get(i);
1372 // will remove them because the net's no longer connected
1373 // need to do this now as only now do we know the pids and
1374 // can properly null things that are no longer referenced.
1375 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1380 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1381 if (info.isFailover()) {
1382 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1383 info.setFailover(false);
1384 }
1385 if (info.getReason() != null) {
1386 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1387 }
1388 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001389 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1390 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001392
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001393 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001394 tryFailover(prevNetType);
1395 if (mActiveDefaultNetwork != -1) {
1396 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001397 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1398 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001399 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001400 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1401 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001402 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001403 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001404
1405 // Reset interface if no other connections are using the same interface
1406 boolean doReset = true;
1407 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1408 if (linkProperties != null) {
1409 String oldIface = linkProperties.getInterfaceName();
1410 if (TextUtils.isEmpty(oldIface) == false) {
1411 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1412 if (networkStateTracker == null) continue;
1413 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1414 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1415 LinkProperties l = networkStateTracker.getLinkProperties();
1416 if (l == null) continue;
1417 if (oldIface.equals(l.getInterfaceName())) {
1418 doReset = false;
1419 break;
1420 }
1421 }
1422 }
1423 }
1424 }
1425
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001426 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001427 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001428
Jeff Sharkey961e3042011-08-29 16:02:57 -07001429 final Intent immediateIntent = new Intent(intent);
1430 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1431 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001432 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001433 /*
1434 * If the failover network is already connected, then immediately send
1435 * out a followup broadcast indicating successful failover
1436 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001437 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001438 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1439 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001440 }
1441 }
1442
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001443 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001444 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001445 * If this is a default network, check if other defaults are available.
1446 * Try to reconnect on all available and let them hash it out when
1447 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001448 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001449 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001450 if (mActiveDefaultNetwork == prevNetType) {
1451 mActiveDefaultNetwork = -1;
1452 }
1453
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001454 // don't signal a reconnect for anything lower or equal priority than our
1455 // current connected default
1456 // TODO - don't filter by priority now - nice optimization but risky
1457// int currentPriority = -1;
1458// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001459// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001460// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001461 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001462 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001463 if (mNetConfigs[checkType] == null) continue;
1464 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001465
1466// Enabling the isAvailable() optimization caused mobile to not get
1467// selected if it was in the middle of error handling. Specifically
1468// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1469// would not be available and we wouldn't get connected to anything.
1470// So removing the isAvailable() optimization below for now. TODO: This
1471// optimization should work and we need to investigate why it doesn't work.
1472// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1473// complete before it is really complete.
1474// if (!mNetTrackers[checkType].isAvailable()) continue;
1475
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001476// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001477
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001478 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1479 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1480 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1481 checkInfo.setFailover(true);
1482 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001483 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001484 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488
1489 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001490 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1491 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001492 }
1493
Wink Saville628b0852011-08-04 15:01:58 -07001494 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001495 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1496 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001497 }
1498
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001499 private void sendInetConditionBroadcast(NetworkInfo info) {
1500 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1501 }
1502
Wink Saville628b0852011-08-04 15:01:58 -07001503 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001504 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1506 if (info.isFailover()) {
1507 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1508 info.setFailover(false);
1509 }
1510 if (info.getReason() != null) {
1511 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1512 }
1513 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001514 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1515 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001517 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001518 return intent;
1519 }
1520
1521 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1522 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1523 }
1524
1525 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1526 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528
1529 /**
1530 * Called when an attempt to fail over to another network has failed.
1531 * @param info the {@link NetworkInfo} for the failed network
1532 */
1533 private void handleConnectionFailure(NetworkInfo info) {
1534 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535
Robert Greenwalt42acef32009-08-12 16:08:25 -07001536 String reason = info.getReason();
1537 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001538
Robert Greenwalt572172b2010-10-08 16:35:52 -07001539 String reasonText;
1540 if (reason == null) {
1541 reasonText = ".";
1542 } else {
1543 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001545 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001546
1547 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1548 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1549 if (getActiveNetworkInfo() == null) {
1550 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1551 }
1552 if (reason != null) {
1553 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1554 }
1555 if (extraInfo != null) {
1556 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1557 }
1558 if (info.isFailover()) {
1559 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1560 info.setFailover(false);
1561 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001562
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001563 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001564 tryFailover(info.getType());
1565 if (mActiveDefaultNetwork != -1) {
1566 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001567 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1568 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001569 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001570 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1571 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001572 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001573
Robert Greenwalt029be812010-09-20 18:01:43 -07001574 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001575
1576 final Intent immediateIntent = new Intent(intent);
1577 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1578 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001579 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001580 /*
1581 * If the failover network is already connected, then immediately send
1582 * out a followup broadcast indicating successful failover
1583 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001584 if (mActiveDefaultNetwork != -1) {
1585 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001586 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001587 }
1588
1589 private void sendStickyBroadcast(Intent intent) {
1590 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001591 if (!mSystemReady) {
1592 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001593 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001594 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Saville628b0852011-08-04 15:01:58 -07001595 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001596 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001597 }
1598
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001599 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001600 }
1601 }
1602
Wink Saville628b0852011-08-04 15:01:58 -07001603 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1604 if (delayMs <= 0) {
1605 sendStickyBroadcast(intent);
1606 } else {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001607 if (DBG) {
1608 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1609 + intent.getAction());
1610 }
Wink Saville628b0852011-08-04 15:01:58 -07001611 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1612 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1613 }
1614 }
1615
Mike Lockwood0f79b542009-08-14 14:18:49 -04001616 void systemReady() {
1617 synchronized(this) {
1618 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001619 if (mInitialBroadcast != null) {
1620 mContext.sendStickyBroadcast(mInitialBroadcast);
1621 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001622 }
1623 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001624 // load the global proxy at startup
1625 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
1628 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001629 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630
1631 // snapshot isFailover, because sendConnectedBroadcast() resets it
1632 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001633 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634
Robert Greenwalt42acef32009-08-12 16:08:25 -07001635 // if this is a default net and other default is running
1636 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001637 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001638 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1639 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001640 mNetConfigs[mActiveDefaultNetwork].priority >
1641 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001642 mNetworkPreference == mActiveDefaultNetwork) {
1643 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001644 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001645 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001646 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001647 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001648 teardown(thisNet);
1649 return;
1650 } else {
1651 // tear down the other
1652 NetworkStateTracker otherNet =
1653 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001654 if (DBG) {
1655 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001656 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001657 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001658 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001659 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001660 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001661 return;
1662 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001663 }
1664 }
1665 synchronized (ConnectivityService.this) {
1666 // have a new default network, release the transition wakelock in a second
1667 // if it's held. The second pause is to allow apps to reconnect over the
1668 // new network
1669 if (mNetTransitionWakeLock.isHeld()) {
1670 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001671 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001672 mNetTransitionWakeLockSerialNumber, 0),
1673 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001674 }
1675 }
1676 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001677 // this will cause us to come up initially as unconnected and switching
1678 // to connected after our normal pause unless somebody reports us as reall
1679 // disconnected
1680 mDefaultInetConditionPublished = 0;
1681 mDefaultConnectionSequence++;
1682 mInetConditionChangeInFlight = false;
1683 // Don't do this - if we never sign in stay, grey
1684 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001687 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001688 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001689 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001693 * After a change in the connectivity state of a network. We're mainly
1694 * concerned with making sure that the list of DNS servers is set up
1695 * according to which networks are connected, and ensuring that the
1696 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001698 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001699 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001702 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001703 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001705 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001706
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001707 LinkProperties curLp = mCurrentLinkProperties[netType];
1708 LinkProperties newLp = null;
1709
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001710 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001711 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001712 if (VDBG) {
1713 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1714 " doReset=" + doReset + " resetMask=" + resetMask +
1715 "\n curLp=" + curLp +
1716 "\n newLp=" + newLp);
1717 }
1718
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001719 if (curLp != null) {
1720 if (curLp.isIdenticalInterfaceName(newLp)) {
1721 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1722 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1723 for (LinkAddress linkAddr : car.removed) {
1724 if (linkAddr.getAddress() instanceof Inet4Address) {
1725 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1726 }
1727 if (linkAddr.getAddress() instanceof Inet6Address) {
1728 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1729 }
Wink Savillee8222252011-07-13 13:44:13 -07001730 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001731 if (DBG) {
1732 log("handleConnectivityChange: addresses changed" +
1733 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1734 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001735 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001736 } else {
1737 if (DBG) {
1738 log("handleConnectivityChange: address are the same reset per doReset" +
1739 " linkProperty[" + netType + "]:" +
1740 " resetMask=" + resetMask);
1741 }
Wink Savillee8222252011-07-13 13:44:13 -07001742 }
1743 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001744 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001745 if (DBG) {
1746 log("handleConnectivityChange: interface not not equivalent reset both" +
1747 " linkProperty[" + netType + "]:" +
1748 " resetMask=" + resetMask);
1749 }
Wink Savillee8222252011-07-13 13:44:13 -07001750 }
Wink Savillee8222252011-07-13 13:44:13 -07001751 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001752 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001753 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001754 }
1755 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001756 if (VDBG) {
1757 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1758 " doReset=" + doReset + " resetMask=" + resetMask +
1759 "\n curLp=" + curLp +
1760 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001763 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001764 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001765
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001766 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001767 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1768 if (linkProperties != null) {
1769 String iface = linkProperties.getInterfaceName();
1770 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001771 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001772 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1773 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001774
1775 // Tell VPN the interface is down. It is a temporary
1776 // but effective fix to make VPN aware of the change.
1777 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1778 mVpn.interfaceStatusChanged(iface, false);
1779 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001780 }
1781 if (resetDns) {
1782 if (DBG) log("resetting DNS cache for " + iface);
1783 try {
1784 mNetd.flushInterfaceDnsCache(iface);
1785 } catch (Exception e) {
1786 // never crash - catch them all
1787 loge("Exception resetting dns cache: " + e);
1788 }
1789 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001790 }
1791 }
1792 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001793
1794 // TODO: Temporary notifying upstread change to Tethering.
1795 // @see bug/4455071
1796 /** Notify TetheringService if interface name has been changed. */
1797 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1798 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1799 if (isTetheringSupported()) {
1800 mTethering.handleTetherIfaceChange();
1801 }
1802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001805 /**
1806 * Add and remove routes using the old properties (null if not previously connected),
1807 * new properties (null if becoming disconnected). May even be double null, which
1808 * is a noop.
1809 * Uses isLinkDefault to determine if default routes should be set or conversely if
1810 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07001811 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001812 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07001813 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1814 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001815 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001816 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1817 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001818 if (curLp != null) {
1819 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001820 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001821 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001822 } else if (newLp != null) {
1823 routeDiff.added = newLp.getRoutes();
1824 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001825 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001826
Robert Greenwaltf125a092011-08-15 12:31:55 -07001827 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1828
Robert Greenwaltad55d352011-07-22 11:55:33 -07001829 for (RouteInfo r : routeDiff.removed) {
1830 if (isLinkDefault || ! r.isDefaultRoute()) {
1831 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001832 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001833 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001834
Robert Greenwaltad55d352011-07-22 11:55:33 -07001835 for (RouteInfo r : routeDiff.added) {
1836 if (isLinkDefault || ! r.isDefaultRoute()) {
1837 addRoute(newLp, r);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001838 } else {
1839 // many radios add a default route even when we don't want one.
1840 // remove the default route unless somebody else has asked for it
1841 String ifaceName = newLp.getInterfaceName();
1842 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
1843 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1844 try {
1845 mNetd.removeRoute(ifaceName, r);
1846 } catch (Exception e) {
1847 // never crash - catch them all
1848 loge("Exception trying to remove a route: " + e);
1849 }
1850 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001851 }
1852 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001853
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001854 if (!isLinkDefault) {
1855 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07001856 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001857 // routes changed - remove all old dns entries and add new
1858 if (curLp != null) {
1859 for (InetAddress oldDns : curLp.getDnses()) {
1860 removeRouteToAddress(curLp, oldDns);
1861 }
1862 }
1863 if (newLp != null) {
1864 for (InetAddress newDns : newLp.getDnses()) {
1865 addRouteToAddress(newLp, newDns);
1866 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001867 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001868 } else {
1869 // no change in routes, check for change in dns themselves
1870 for (InetAddress oldDns : dnsDiff.removed) {
1871 removeRouteToAddress(curLp, oldDns);
1872 }
1873 for (InetAddress newDns : dnsDiff.added) {
1874 addRouteToAddress(newLp, newDns);
1875 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001876 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001877 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001878 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001879 }
1880
1881
Irfan Sheriffd649c122010-06-09 15:39:36 -07001882 /**
1883 * Reads the network specific TCP buffer sizes from SystemProperties
1884 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1885 * wide use
1886 */
1887 public void updateNetworkSettings(NetworkStateTracker nt) {
1888 String key = nt.getTcpBufferSizesPropName();
1889 String bufferSizes = SystemProperties.get(key);
1890
1891 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001892 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001893
1894 // Setting to default values so we won't be stuck to previous values
1895 key = "net.tcp.buffersize.default";
1896 bufferSizes = SystemProperties.get(key);
1897 }
1898
1899 // Set values in kernel
1900 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001901 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001902 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001903 + "] which comes from [" + key + "]");
1904 }
1905 setBufferSize(bufferSizes);
1906 }
1907 }
1908
1909 /**
1910 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1911 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1912 *
1913 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1914 * writeMin, writeInitial, writeMax"
1915 */
1916 private void setBufferSize(String bufferSizes) {
1917 try {
1918 String[] values = bufferSizes.split(",");
1919
1920 if (values.length == 6) {
1921 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001922 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1923 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1924 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1925 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1926 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1927 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001928 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001929 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001930 }
1931 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001932 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001933 }
1934 }
1935
Robert Greenwalt42acef32009-08-12 16:08:25 -07001936 /**
1937 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1938 * on the highest priority active net which this process requested.
1939 * If there aren't any, clear it out
1940 */
1941 private void reassessPidDns(int myPid, boolean doBump)
1942 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001943 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001944 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001945 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001946 continue;
1947 }
1948 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001949 if (nt.getNetworkInfo().isConnected() &&
1950 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001951 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001952 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001953 List pids = mNetRequestersPids[i];
1954 for (int j=0; j<pids.size(); j++) {
1955 Integer pid = (Integer)pids.get(j);
1956 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001957 Collection<InetAddress> dnses = p.getDnses();
1958 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001959 if (doBump) {
1960 bumpDns();
1961 }
1962 return;
1963 }
1964 }
1965 }
1966 }
1967 // nothing found - delete
1968 for (int i = 1; ; i++) {
1969 String prop = "net.dns" + i + "." + myPid;
1970 if (SystemProperties.get(prop).length() == 0) {
1971 if (doBump) {
1972 bumpDns();
1973 }
1974 return;
1975 }
1976 SystemProperties.set(prop, "");
1977 }
1978 }
1979
Robert Greenwalt10398722010-12-17 15:20:36 -08001980 // return true if results in a change
1981 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001982 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001983 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001984 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001985 String dnsString = dns.getHostAddress();
1986 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1987 changed = true;
1988 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1989 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001990 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001991 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001992 }
1993
1994 private void bumpDns() {
1995 /*
1996 * Bump the property that tells the name resolver library to reread
1997 * the DNS server list from the properties.
1998 */
1999 String propVal = SystemProperties.get("net.dnschange");
2000 int n = 0;
2001 if (propVal.length() != 0) {
2002 try {
2003 n = Integer.parseInt(propVal);
2004 } catch (NumberFormatException e) {}
2005 }
2006 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002007 /*
2008 * Tell the VMs to toss their DNS caches
2009 */
2010 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2011 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002012 /*
2013 * Connectivity events can happen before boot has completed ...
2014 */
2015 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002016 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002017 }
2018
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002019 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002020 private boolean updateDns(String network, String iface,
2021 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002022 boolean changed = false;
2023 int last = 0;
2024 if (dnses.size() == 0 && mDefaultDns != null) {
2025 ++last;
2026 String value = mDefaultDns.getHostAddress();
2027 if (!value.equals(SystemProperties.get("net.dns1"))) {
2028 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002029 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002030 }
2031 changed = true;
2032 SystemProperties.set("net.dns1", value);
2033 }
2034 } else {
2035 for (InetAddress dns : dnses) {
2036 ++last;
2037 String key = "net.dns" + last;
2038 String value = dns.getHostAddress();
2039 if (!changed && value.equals(SystemProperties.get(key))) {
2040 continue;
2041 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002042 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002043 log("adding dns " + value + " for " + network);
2044 }
2045 changed = true;
2046 SystemProperties.set(key, value);
2047 }
2048 }
2049 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2050 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002051 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002052 changed = true;
2053 SystemProperties.set(key, "");
2054 }
2055 mNumDnsEntries = last;
2056
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002057 if (changed) {
2058 try {
2059 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2060 mNetd.setDefaultInterfaceForDns(iface);
2061 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002062 loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002063 }
2064 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002065 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2066 SystemProperties.set("net.dns.search", domains);
2067 changed = true;
2068 }
2069 return changed;
2070 }
2071
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002072 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002073 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002074 NetworkStateTracker nt = mNetTrackers[netType];
2075 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002076 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002077 if (p == null) return;
2078 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002079 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002080 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002081 String network = nt.getNetworkInfo().getTypeName();
2082 synchronized (mDnsLock) {
2083 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002084 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002085 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002086 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002087 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002088 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002089 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002090 NetworkUtils.makeStrings(dnses));
2091 } catch (Exception e) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002092 loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002093 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002094 // set per-pid dns for attached secondary nets
2095 List pids = mNetRequestersPids[netType];
2096 for (int y=0; y< pids.size(); y++) {
2097 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002098 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 }
2100 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002101 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002103 }
2104
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002105 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002106 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2107 NETWORK_RESTORE_DELAY_PROP_NAME);
2108 if(restoreDefaultNetworkDelayStr != null &&
2109 restoreDefaultNetworkDelayStr.length() != 0) {
2110 try {
2111 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2112 } catch (NumberFormatException e) {
2113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002115 // if the system property isn't set, use the value for the apn type
2116 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2117
2118 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2119 (mNetConfigs[networkType] != null)) {
2120 ret = mNetConfigs[networkType].restoreTime;
2121 }
2122 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124
2125 @Override
2126 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002127 if (mContext.checkCallingOrSelfPermission(
2128 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002130 pw.println("Permission Denial: can't dump ConnectivityService " +
2131 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2132 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 return;
2134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 pw.println();
2136 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002137 if (nst != null) {
2138 if (nst.getNetworkInfo().isConnected()) {
2139 pw.println("Active network: " + nst.getNetworkInfo().
2140 getTypeName());
2141 }
2142 pw.println(nst.getNetworkInfo());
2143 pw.println(nst);
2144 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002147
2148 pw.println("Network Requester Pids:");
2149 for (int net : mPriorityList) {
2150 String pidString = net + ": ";
2151 for (Object pid : mNetRequestersPids[net]) {
2152 pidString = pidString + pid.toString() + ", ";
2153 }
2154 pw.println(pidString);
2155 }
2156 pw.println();
2157
2158 pw.println("FeatureUsers:");
2159 for (Object requester : mFeatureUsers) {
2160 pw.println(requester.toString());
2161 }
2162 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002163
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002164 synchronized (this) {
2165 pw.println("NetworkTranstionWakeLock is currently " +
2166 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2167 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2168 }
2169 pw.println();
2170
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002171 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002172
2173 if (mInetLog != null) {
2174 pw.println();
2175 pw.println("Inet condition reports:");
2176 for(int i = 0; i < mInetLog.size(); i++) {
2177 pw.println(mInetLog.get(i));
2178 }
2179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 }
2181
Robert Greenwalt42acef32009-08-12 16:08:25 -07002182 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002184 public MyHandler(Looper looper) {
2185 super(looper);
2186 }
2187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 @Override
2189 public void handleMessage(Message msg) {
2190 NetworkInfo info;
2191 switch (msg.what) {
2192 case NetworkStateTracker.EVENT_STATE_CHANGED:
2193 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002194 int type = info.getType();
2195 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002196
Wink Savilleed9c02b2010-12-03 12:01:38 -08002197 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002198 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002199 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200
2201 // Connectivity state changed:
2202 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002203 // [12-9] Network subtype (for mobile network, as defined
2204 // by TelephonyManager)
2205 // [8-3] Detailed state ordinal (as defined by
2206 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 // [2-0] Network type (as defined by ConnectivityManager)
2208 int eventLogParam = (info.getType() & 0x7) |
2209 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2210 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002211 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002212 eventLogParam);
2213
2214 if (info.getDetailedState() ==
2215 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002217 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002219 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002221 // the logic here is, handle SUSPENDED the same as
2222 // DISCONNECTED. The only difference being we are
2223 // broadcasting an intent with NetworkInfo that's
2224 // suspended. This allows the applications an
2225 // opportunity to handle DISCONNECTED and SUSPENDED
2226 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002228 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 handleConnect(info);
2230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002233 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002234 // TODO: Temporary allowing network configuration
2235 // change not resetting sockets.
2236 // @see bug/4455071
2237 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002239 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002240 String causedBy = null;
2241 synchronized (ConnectivityService.this) {
2242 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2243 mNetTransitionWakeLock.isHeld()) {
2244 mNetTransitionWakeLock.release();
2245 causedBy = mNetTransitionWakeLockCausedBy;
2246 }
2247 }
2248 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002249 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002250 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002251 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002252 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002253 FeatureUser u = (FeatureUser)msg.obj;
2254 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002255 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002256 case EVENT_INET_CONDITION_CHANGE:
2257 {
2258 int netType = msg.arg1;
2259 int condition = msg.arg2;
2260 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002261 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002262 }
2263 case EVENT_INET_CONDITION_HOLD_END:
2264 {
2265 int netType = msg.arg1;
2266 int sequence = msg.arg2;
2267 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002268 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002269 }
2270 case EVENT_SET_NETWORK_PREFERENCE:
2271 {
2272 int preference = msg.arg1;
2273 handleSetNetworkPreference(preference);
2274 break;
2275 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002276 case EVENT_SET_MOBILE_DATA:
2277 {
2278 boolean enabled = (msg.arg1 == ENABLED);
2279 handleSetMobileData(enabled);
2280 break;
2281 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002282 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2283 {
2284 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002285 break;
2286 }
2287 case EVENT_SET_DEPENDENCY_MET:
2288 {
2289 boolean met = (msg.arg1 == ENABLED);
2290 handleSetDependencyMet(msg.arg2, met);
2291 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002292 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002293 case EVENT_RESTORE_DNS:
2294 {
2295 if (mActiveDefaultNetwork != -1) {
2296 handleDnsConfigurationChange(mActiveDefaultNetwork);
2297 }
2298 break;
2299 }
Wink Saville628b0852011-08-04 15:01:58 -07002300 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2301 {
2302 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002303 sendStickyBroadcast(intent);
2304 break;
2305 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002306 case EVENT_SET_POLICY_DATA_ENABLE: {
2307 final int networkType = msg.arg1;
2308 final boolean enabled = msg.arg2 == ENABLED;
2309 handleSetPolicyDataEnable(networkType, enabled);
2310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312 }
2313 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002314
2315 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002316 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002317 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002318
2319 if (isTetheringSupported()) {
2320 return mTethering.tether(iface);
2321 } else {
2322 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2323 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002324 }
2325
2326 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002327 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002328 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002329
2330 if (isTetheringSupported()) {
2331 return mTethering.untether(iface);
2332 } else {
2333 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2334 }
2335 }
2336
2337 // javadoc from interface
2338 public int getLastTetherError(String iface) {
2339 enforceTetherAccessPermission();
2340
2341 if (isTetheringSupported()) {
2342 return mTethering.getLastTetherError(iface);
2343 } else {
2344 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2345 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002346 }
2347
2348 // TODO - proper iface API for selection by property, inspection, etc
2349 public String[] getTetherableUsbRegexs() {
2350 enforceTetherAccessPermission();
2351 if (isTetheringSupported()) {
2352 return mTethering.getTetherableUsbRegexs();
2353 } else {
2354 return new String[0];
2355 }
2356 }
2357
2358 public String[] getTetherableWifiRegexs() {
2359 enforceTetherAccessPermission();
2360 if (isTetheringSupported()) {
2361 return mTethering.getTetherableWifiRegexs();
2362 } else {
2363 return new String[0];
2364 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002365 }
2366
Danica Chang6fdd0c62010-08-11 14:54:43 -07002367 public String[] getTetherableBluetoothRegexs() {
2368 enforceTetherAccessPermission();
2369 if (isTetheringSupported()) {
2370 return mTethering.getTetherableBluetoothRegexs();
2371 } else {
2372 return new String[0];
2373 }
2374 }
2375
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002376 public int setUsbTethering(boolean enable) {
2377 enforceTetherAccessPermission();
2378 if (isTetheringSupported()) {
2379 return mTethering.setUsbTethering(enable);
2380 } else {
2381 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2382 }
2383 }
2384
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002385 // TODO - move iface listing, queries, etc to new module
2386 // javadoc from interface
2387 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002388 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002389 return mTethering.getTetherableIfaces();
2390 }
2391
2392 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002393 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002394 return mTethering.getTetheredIfaces();
2395 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002396
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002397 @Override
2398 public String[] getTetheredIfacePairs() {
2399 enforceTetherAccessPermission();
2400 return mTethering.getTetheredIfacePairs();
2401 }
2402
Robert Greenwalt5a735062010-03-02 17:25:02 -08002403 public String[] getTetheringErroredIfaces() {
2404 enforceTetherAccessPermission();
2405 return mTethering.getErroredIfaces();
2406 }
2407
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002408 // if ro.tether.denied = true we default to no tethering
2409 // gservices could set the secure setting to 1 though to enable it on a build where it
2410 // had previously been turned off.
2411 public boolean isTetheringSupported() {
2412 enforceTetherAccessPermission();
2413 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002414 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2415 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2416 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002417 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002418
2419 // An API NetworkStateTrackers can call when they lose their network.
2420 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2421 // whichever happens first. The timer is started by the first caller and not
2422 // restarted by subsequent callers.
2423 public void requestNetworkTransitionWakelock(String forWhom) {
2424 enforceConnectivityInternalPermission();
2425 synchronized (this) {
2426 if (mNetTransitionWakeLock.isHeld()) return;
2427 mNetTransitionWakeLockSerialNumber++;
2428 mNetTransitionWakeLock.acquire();
2429 mNetTransitionWakeLockCausedBy = forWhom;
2430 }
2431 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002432 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002433 mNetTransitionWakeLockSerialNumber, 0),
2434 mNetTransitionWakeLockTimeout);
2435 return;
2436 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002437
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002438 // 100 percent is full good, 0 is full bad.
2439 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002440 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002441 mContext.enforceCallingOrSelfPermission(
2442 android.Manifest.permission.STATUS_BAR,
2443 "ConnectivityService");
2444
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002445 if (DBG) {
2446 int pid = getCallingPid();
2447 int uid = getCallingUid();
2448 String s = pid + "(" + uid + ") reports inet is " +
2449 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2450 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2451 mInetLog.add(s);
2452 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2453 mInetLog.remove(0);
2454 }
2455 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002456 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002457 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2458 }
2459
2460 private void handleInetConditionChange(int netType, int condition) {
2461 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002462 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002463 netType + ", condition=" + condition +
2464 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2465 }
2466 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002467 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002468 return;
2469 }
2470 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002471 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002472 return;
2473 }
2474 mDefaultInetCondition = condition;
2475 int delay;
2476 if (mInetConditionChangeInFlight == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002477 if (VDBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002478 // setup a new hold to debounce this
2479 if (mDefaultInetCondition > 50) {
2480 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2481 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2482 } else {
2483 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2484 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2485 }
2486 mInetConditionChangeInFlight = true;
2487 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2488 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2489 } else {
2490 // we've set the new condition, when this hold ends that will get
2491 // picked up
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002492 if (VDBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002493 }
2494 }
2495
2496 private void handleInetConditionHoldEnd(int netType, int sequence) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002497 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002498 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002499 ", condition =" + mDefaultInetCondition +
2500 ", published condition =" + mDefaultInetConditionPublished);
2501 }
2502 mInetConditionChangeInFlight = false;
2503
2504 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002505 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002506 return;
2507 }
2508 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002509 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002510 return;
2511 }
Wink Saville628b0852011-08-04 15:01:58 -07002512 // TODO: Figure out why this optimization sometimes causes a
2513 // change in mDefaultInetCondition to be missed and the
2514 // UI to not be updated.
2515 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2516 // if (DBG) log("no change in condition - aborting");
2517 // return;
2518 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002519 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2520 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002521 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002522 return;
2523 }
2524 mDefaultInetConditionPublished = mDefaultInetCondition;
2525 sendInetConditionBroadcast(networkInfo);
2526 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002527 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002528
2529 public synchronized ProxyProperties getProxy() {
2530 if (mGlobalProxy != null) return mGlobalProxy;
2531 if (mDefaultProxy != null) return mDefaultProxy;
2532 return null;
2533 }
2534
2535 public void setGlobalProxy(ProxyProperties proxyProperties) {
2536 enforceChangePermission();
2537 synchronized (mGlobalProxyLock) {
2538 if (proxyProperties == mGlobalProxy) return;
2539 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2540 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2541
2542 String host = "";
2543 int port = 0;
2544 String exclList = "";
2545 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2546 mGlobalProxy = new ProxyProperties(proxyProperties);
2547 host = mGlobalProxy.getHost();
2548 port = mGlobalProxy.getPort();
2549 exclList = mGlobalProxy.getExclusionList();
2550 } else {
2551 mGlobalProxy = null;
2552 }
2553 ContentResolver res = mContext.getContentResolver();
2554 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2555 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002556 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002557 exclList);
2558 }
2559
2560 if (mGlobalProxy == null) {
2561 proxyProperties = mDefaultProxy;
2562 }
2563 sendProxyBroadcast(proxyProperties);
2564 }
2565
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002566 private void loadGlobalProxy() {
2567 ContentResolver res = mContext.getContentResolver();
2568 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2569 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2570 String exclList = Settings.Secure.getString(res,
2571 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2572 if (!TextUtils.isEmpty(host)) {
2573 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2574 synchronized (mGlobalProxyLock) {
2575 mGlobalProxy = proxyProperties;
2576 }
2577 }
2578 }
2579
Robert Greenwalt434203a2010-10-11 16:00:27 -07002580 public ProxyProperties getGlobalProxy() {
2581 synchronized (mGlobalProxyLock) {
2582 return mGlobalProxy;
2583 }
2584 }
2585
2586 private void handleApplyDefaultProxy(int type) {
2587 // check if new default - push it out to all VM if so
2588 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2589 synchronized (this) {
2590 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2591 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002592 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002593 mDefaultProxy = proxy;
2594 } else {
2595 mDefaultProxy = null;
2596 }
2597 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002598 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002599 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2600 if (mGlobalProxy != null) return;
2601 sendProxyBroadcast(proxy);
2602 }
2603
2604 private void handleDeprecatedGlobalHttpProxy() {
2605 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2606 Settings.Secure.HTTP_PROXY);
2607 if (!TextUtils.isEmpty(proxy)) {
2608 String data[] = proxy.split(":");
2609 String proxyHost = data[0];
2610 int proxyPort = 8080;
2611 if (data.length > 1) {
2612 try {
2613 proxyPort = Integer.parseInt(data[1]);
2614 } catch (NumberFormatException e) {
2615 return;
2616 }
2617 }
2618 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2619 setGlobalProxy(p);
2620 }
2621 }
2622
2623 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002624 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002625 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002626 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002627 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2628 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002629 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002630 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002631 }
2632
2633 private static class SettingsObserver extends ContentObserver {
2634 private int mWhat;
2635 private Handler mHandler;
2636 SettingsObserver(Handler handler, int what) {
2637 super(handler);
2638 mHandler = handler;
2639 mWhat = what;
2640 }
2641
2642 void observe(Context context) {
2643 ContentResolver resolver = context.getContentResolver();
2644 resolver.registerContentObserver(Settings.Secure.getUriFor(
2645 Settings.Secure.HTTP_PROXY), false, this);
2646 }
2647
2648 @Override
2649 public void onChange(boolean selfChange) {
2650 mHandler.obtainMessage(mWhat).sendToTarget();
2651 }
2652 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002653
2654 private void log(String s) {
2655 Slog.d(TAG, s);
2656 }
2657
2658 private void loge(String s) {
2659 Slog.e(TAG, s);
2660 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002661
repo syncaea743a2011-07-29 23:55:49 -07002662 int convertFeatureToNetworkType(int networkType, String feature) {
2663 int usedNetworkType = networkType;
2664
2665 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2666 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2667 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2668 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2669 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2670 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2671 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2672 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2673 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2674 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2675 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2676 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2677 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2678 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2679 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2680 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2681 } else {
2682 Slog.e(TAG, "Can't match any mobile netTracker!");
2683 }
2684 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2685 if (TextUtils.equals(feature, "p2p")) {
2686 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2687 } else {
2688 Slog.e(TAG, "Can't match any wifi netTracker!");
2689 }
2690 } else {
2691 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002692 }
repo syncaea743a2011-07-29 23:55:49 -07002693 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002694 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002695
2696 private static <T> T checkNotNull(T value, String message) {
2697 if (value == null) {
2698 throw new NullPointerException(message);
2699 }
2700 return value;
2701 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002702
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002703 /**
2704 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002705 * VpnBuilder and not available in ConnectivityManager. Permissions
2706 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002707 * @hide
2708 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002709 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002710 public boolean protectVpn(ParcelFileDescriptor socket) {
2711 try {
2712 int type = mActiveDefaultNetwork;
2713 if (ConnectivityManager.isNetworkTypeValid(type)) {
2714 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2715 return true;
2716 }
2717 } catch (Exception e) {
2718 // ignore
2719 } finally {
2720 try {
2721 socket.close();
2722 } catch (Exception e) {
2723 // ignore
2724 }
2725 }
2726 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002727 }
2728
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002729 /**
2730 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002731 * and not available in ConnectivityManager. Permissions are checked
2732 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002733 * @hide
2734 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002735 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002736 public boolean prepareVpn(String oldPackage, String newPackage) {
2737 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002738 }
2739
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002740 /**
2741 * Configure a TUN interface and return its file descriptor. Parameters
2742 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002743 * and not available in ConnectivityManager. Permissions are checked in
2744 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002745 * @hide
2746 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002747 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002748 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002749 return mVpn.establish(config);
2750 }
2751
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002752 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002753 * Start legacy VPN and return an intent to VpnDialogs. This method is
2754 * used by VpnSettings and not available in ConnectivityManager.
2755 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002756 * @hide
2757 */
2758 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002759 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2760 mVpn.startLegacyVpn(config, racoon, mtpd);
2761 }
2762
2763 /**
2764 * Return the information of the ongoing legacy VPN. This method is used
2765 * by VpnSettings and not available in ConnectivityManager. Permissions
2766 * are checked in Vpn class.
2767 * @hide
2768 */
2769 @Override
2770 public LegacyVpnInfo getLegacyVpnInfo() {
2771 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002772 }
2773
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002774 /**
2775 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2776 * through NetworkStateTracker since it works differently. For example, it
2777 * needs to override DNS servers but never takes the default routes. It
2778 * relies on another data network, and it could keep existing connections
2779 * alive after reconnecting, switching between networks, or even resuming
2780 * from deep sleep. Calls from applications should be done synchronously
2781 * to avoid race conditions. As these are all hidden APIs, refactoring can
2782 * be done whenever a better abstraction is developed.
2783 */
2784 public class VpnCallback {
2785
2786 private VpnCallback() {
2787 }
2788
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002789 public void override(List<String> dnsServers, List<String> searchDomains) {
2790 if (dnsServers == null) {
2791 restore();
2792 return;
2793 }
2794
2795 // Convert DNS servers into addresses.
2796 List<InetAddress> addresses = new ArrayList<InetAddress>();
2797 for (String address : dnsServers) {
2798 // Double check the addresses and remove invalid ones.
2799 try {
2800 addresses.add(InetAddress.parseNumericAddress(address));
2801 } catch (Exception e) {
2802 // ignore
2803 }
2804 }
2805 if (addresses.isEmpty()) {
2806 restore();
2807 return;
2808 }
2809
2810 // Concatenate search domains into a string.
2811 StringBuilder buffer = new StringBuilder();
2812 if (searchDomains != null) {
2813 for (String domain : searchDomains) {
2814 buffer.append(domain).append(' ');
2815 }
2816 }
2817 String domains = buffer.toString().trim();
2818
2819 // Apply DNS changes.
2820 boolean changed = false;
2821 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002822 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002823 mDnsOverridden = true;
2824 }
2825 if (changed) {
2826 bumpDns();
2827 }
2828
2829 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002830 }
2831
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002832 public void restore() {
2833 synchronized (mDnsLock) {
2834 if (!mDnsOverridden) {
2835 return;
2836 }
2837 mDnsOverridden = false;
2838 }
2839 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002840 }
2841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842}