blob: c31cde7094246a3b868987383b8012d5b1507acd [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 Sharkey69ddab42012-08-25 00:05:46 -070019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1a303952011-06-16 13:04:20 -070020import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070021import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070022import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
23import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
25import static android.net.ConnectivityManager.TYPE_DUMMY;
26import static android.net.ConnectivityManager.TYPE_ETHERNET;
27import static android.net.ConnectivityManager.TYPE_MOBILE;
28import static android.net.ConnectivityManager.TYPE_WIFI;
29import static android.net.ConnectivityManager.TYPE_WIMAX;
30import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.ConnectivityManager.isNetworkTypeValid;
32import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Irfan Sheriff9538bdd2012-09-20 09:32:41 -070035import android.app.Activity;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080036import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070037import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.ContentResolver;
39import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090040import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.PackageManager;
tk.mun148c7d02011-10-13 22:51:57 +090044import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070046import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080048import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080049import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070051import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import android.net.INetworkPolicyListener;
53import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070054import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070055import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070062import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070063import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070065import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070066import android.net.Proxy;
67import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070068import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090070import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040072import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070074import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070075import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070076import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Looper;
78import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070079import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070080import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070081import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070082import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070084import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070086import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070088import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070089import android.security.KeyStore;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080092import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070093import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Chia-chi Yeh2e467642011-07-04 03:23:12 -070095import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070096import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070097import com.android.internal.net.VpnProfile;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -070099import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700100import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700101import com.android.server.am.BatteryStatsService;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800102import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700103import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700104import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700105import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700106import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700107import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700108
tk.mun148c7d02011-10-13 22:51:57 +0900109import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700112import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900114import java.lang.reflect.Constructor;
Wink Savillec9822c52011-07-14 12:23:28 -0700115import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700116import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700117import java.net.InetAddress;
118import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700121import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700122import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700123import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700124import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
126/**
127 * @hide
128 */
129public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700130 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Robert Greenwaltba175a52010-10-05 19:12:26 -0700132 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700133 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135 private static final boolean LOGD_RULES = false;
136
Jeff Sharkey899223b2012-08-04 15:24:58 -0700137 // TODO: create better separation between radio types and network types
138
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139 // how long to wait before switching back to a radio's default network
140 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
141 // system property that can override the above value
142 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
143 "android.telephony.apn-restore";
144
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700145 // used in recursive route setting to add gateways for the host for which
146 // a host route was requested.
147 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
148
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800149 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800150 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800151
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700152 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700153
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700154 private Vpn mVpn;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700156
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700157 private boolean mLockdownEnabled;
158 private LockdownVpnTracker mLockdownTracker;
159
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
161 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700162 /** Currently active network rules by UID. */
163 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164 /** Set of ifaces that are costly. */
165 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
168 * Sometimes we want to refer to the individual network state
169 * trackers separately, and sometimes we just want to treat them
170 * abstractly.
171 */
172 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700173
Irfan Sheriffda6da092012-08-16 12:49:23 -0700174 /* Handles captive portal check on a network */
175 private CaptivePortalTracker mCaptivePortalTracker;
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 /**
Wink Savillee8222252011-07-13 13:44:13 -0700178 * The link properties that define the current links
179 */
180 private LinkProperties mCurrentLinkProperties[];
181
182 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700183 * A per Net list of the PID's that requested access to the net
184 * used both as a refcount and for per-PID DNS selection
185 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200186 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700187
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188 // priority order of the nettrackers
189 // (excluding dynamically set mNetworkPreference)
190 // TODO - move mNetworkTypePreference into this
191 private int[] mPriorityList;
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
194 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700195 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700196 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000197 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700198 private int mDefaultInetConditionPublished = 0;
199 private boolean mInetConditionChangeInFlight = false;
200 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700202 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800203 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700204 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700207 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700209 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700211
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700212 private static final int ENABLED = 1;
213 private static final int DISABLED = 0;
214
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700215 private static final boolean ADD = true;
216 private static final boolean REMOVE = false;
217
218 private static final boolean TO_DEFAULT_TABLE = true;
219 private static final boolean TO_SECONDARY_TABLE = false;
220
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700221 /**
222 * used internally as a delayed event to make us switch back to the
223 * default network
224 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700225 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226
227 /**
228 * used internally to change our mobile data enabled flag
229 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700230 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700231
232 /**
233 * used internally to change our network preference setting
234 * arg1 = networkType to prefer
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
239 * used internally to synchronize inet condition reports
240 * arg1 = networkType
241 * arg2 = condition (0 bad, 100 good)
242 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700243 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244
245 /**
246 * used internally to mark the end of inet condition hold periods
247 * arg1 = networkType
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700250
251 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252 * used internally to set enable/disable cellular data
253 * arg1 = ENBALED or DISABLED
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256
Robert Greenwaltf3331232010-09-24 14:32:21 -0700257 /**
258 * used internally to clear a wakelock when transitioning
259 * from one net to another
260 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700261 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700262
Robert Greenwalt434203a2010-10-11 16:00:27 -0700263 /**
264 * used internally to reload global proxy settings
265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700267
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700268 /**
269 * used internally to set external dependency met/unmet
270 * arg1 = ENABLED (met) or DISABLED (unmet)
271 * arg2 = NetworkType
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700274
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700275 /**
276 * used internally to restore DNS properties back to the
277 * default network
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700280
Wink Saville2b30afd2011-08-05 11:40:22 -0700281 /**
Wink Saville628b0852011-08-04 15:01:58 -0700282 * used internally to send a sticky broadcast delayed.
283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700285
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700286 /**
287 * Used internally to
288 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700291
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700292 private static final int EVENT_VPN_STATE_CHANGED = 14;
293
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 /** Handler used for internal events. */
295 private InternalHandler mHandler;
296 /** Handler used for incoming {@link NetworkStateTracker} events. */
297 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700298
299 // list of DeathRecipients used to make sure features are turned off when
300 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500301 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700302
Mike Lockwood0f79b542009-08-14 14:18:49 -0400303 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800304 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400305
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700306 private PowerManager.WakeLock mNetTransitionWakeLock;
307 private String mNetTransitionWakeLockCausedBy = "";
308 private int mNetTransitionWakeLockSerialNumber;
309 private int mNetTransitionWakeLockTimeout;
310
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700311 private InetAddress mDefaultDns;
312
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700313 // this collection is used to refcount the added routes - if there are none left
314 // it's time to remove the route from the route table
315 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
316
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700317 // used in DBG mode to track inet condition reports
318 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
319 private ArrayList mInetLog;
320
Robert Greenwalt434203a2010-10-11 16:00:27 -0700321 // track the current default http proxy - tell the world if we get a new one (real change)
322 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700323 private Object mDefaultProxyLock = new Object();
324 private boolean mDefaultProxyDisabled = false;
325
Robert Greenwalt434203a2010-10-11 16:00:27 -0700326 // track the global proxy.
327 private ProxyProperties mGlobalProxy = null;
328 private final Object mGlobalProxyLock = new Object();
329
330 private SettingsObserver mSettingsObserver;
331
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700332 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700333 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700334
Robert Greenwalt511288a2009-12-07 11:33:18 -0800335 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700336 public int mSimultaneity;
337 public int mType;
338 public RadioAttributes(String init) {
339 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700340 mType = Integer.parseInt(fragments[0]);
341 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700342 }
343 }
344 RadioAttributes[] mRadioAttributes;
345
Robert Greenwalt50393202011-06-21 17:26:14 -0700346 // the set of network types that can only be enabled by system/sig apps
347 List mProtectedNetworks;
348
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700349 public ConnectivityService(Context context, INetworkManagementService netd,
350 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700351 // Currently, omitting a NetworkFactory will create one internally
352 // TODO: create here when we have cleaner WiMAX support
353 this(context, netd, statsService, policyManager, null);
354 }
355
Jeff Sharkey899223b2012-08-04 15:24:58 -0700356 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700357 INetworkStatsService statsService, INetworkPolicyManager policyManager,
358 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800359 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800360
Wink Savillebb08caf2010-09-02 19:23:52 -0700361 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
362 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700363 mHandler = new InternalHandler(handlerThread.getLooper());
364 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700365
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700366 if (netFactory == null) {
367 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
368 }
369
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800370 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800371 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
372 String id = Settings.Secure.getString(context.getContentResolver(),
373 Settings.Secure.ANDROID_ID);
374 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700375 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800376 SystemProperties.set("net.hostname", name);
377 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800378 }
379
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700380 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700381 String dns = Settings.Global.getString(context.getContentResolver(),
382 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700383 if (dns == null || dns.length() == 0) {
384 dns = context.getResources().getString(
385 com.android.internal.R.string.config_default_dns_server);
386 }
387 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800388 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
389 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800390 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700391 }
392
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700393 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700394 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700395 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700396 mKeyStore = KeyStore.getInstance();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700397
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700398 try {
399 mPolicyManager.registerListener(mPolicyListener);
400 } catch (RemoteException e) {
401 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700402 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700403 }
404
405 final PowerManager powerManager = (PowerManager) context.getSystemService(
406 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700407 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
408 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
409 com.android.internal.R.integer.config_networkTransitionTimeout);
410
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411 mNetTrackers = new NetworkStateTracker[
412 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700413 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700414
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700415 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700416 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700417
Robert Greenwalt42acef32009-08-12 16:08:25 -0700418 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700419 String[] raStrings = context.getResources().getStringArray(
420 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700421 for (String raString : raStrings) {
422 RadioAttributes r = new RadioAttributes(raString);
423 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800424 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700425 continue;
426 }
427 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800428 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 r.mType);
430 continue;
431 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700432 mRadioAttributes[r.mType] = r;
433 }
434
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 String[] naStrings = context.getResources().getStringArray(
436 com.android.internal.R.array.networkAttributes);
437 for (String naString : naStrings) {
438 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700439 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700440 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800441 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700442 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700443 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700444 }
Wink Saville975c8482011-04-07 14:23:45 -0700445 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800446 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700447 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700448 continue;
449 }
Wink Saville975c8482011-04-07 14:23:45 -0700450 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800451 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700452 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700453 continue;
454 }
Wink Saville975c8482011-04-07 14:23:45 -0700455 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700456 mNetworksDefined++;
457 } catch(Exception e) {
458 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700459 }
460 }
461
Robert Greenwalt50393202011-06-21 17:26:14 -0700462 mProtectedNetworks = new ArrayList<Integer>();
463 int[] protectedNetworks = context.getResources().getIntArray(
464 com.android.internal.R.array.config_protectedNetworks);
465 for (int p : protectedNetworks) {
466 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
467 mProtectedNetworks.add(p);
468 } else {
469 if (DBG) loge("Ignoring protectedNetwork " + p);
470 }
471 }
472
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700473 // high priority first
474 mPriorityList = new int[mNetworksDefined];
475 {
476 int insertionPoint = mNetworksDefined-1;
477 int currentLowest = 0;
478 int nextLowest = 0;
479 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700480 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700481 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700482 if (na.priority < currentLowest) continue;
483 if (na.priority > currentLowest) {
484 if (na.priority < nextLowest || nextLowest == 0) {
485 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700486 }
487 continue;
488 }
Wink Saville975c8482011-04-07 14:23:45 -0700489 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700490 }
491 currentLowest = nextLowest;
492 nextLowest = 0;
493 }
494 }
495
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800496 // Update mNetworkPreference according to user mannually first then overlay config.xml
497 mNetworkPreference = getPersistedNetworkPreference();
498 if (mNetworkPreference == -1) {
499 for (int n : mPriorityList) {
500 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
501 mNetworkPreference = n;
502 break;
503 }
504 }
505 if (mNetworkPreference == -1) {
506 throw new IllegalStateException(
507 "You should set at least one default Network in config.xml!");
508 }
509 }
510
Mattias Falk8b47b362011-08-23 14:15:13 +0200511 mNetRequestersPids =
512 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700513 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200514 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700515 }
516
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500517 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700518
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700519 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
520 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700521
522 // Create and start trackers for hard-coded networks
523 for (int targetNetworkType : mPriorityList) {
524 final NetworkConfig config = mNetConfigs[targetNetworkType];
525 final NetworkStateTracker tracker;
526 try {
527 tracker = netFactory.createTracker(targetNetworkType, config);
528 mNetTrackers[targetNetworkType] = tracker;
529 } catch (IllegalArgumentException e) {
530 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
531 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700532 continue;
533 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700534
535 tracker.startMonitoring(context, mTrackerHandler);
536 if (config.isDefault()) {
537 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800538 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700539 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800540
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700541 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700542 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700543 mTethering.getTetherableWifiRegexs().length != 0 ||
544 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700545 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800546
Jeff Sharkey899223b2012-08-04 15:24:58 -0700547 mVpn = new Vpn(mContext, mVpnCallback, mNetd);
548 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700549
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700550 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700551 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700552 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700553 } catch (RemoteException e) {
554 loge("Error registering observer :" + e);
555 }
556
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700557 if (DBG) {
558 mInetLog = new ArrayList();
559 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700560
561 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
562 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800563
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700564 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800565 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700567
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700568 /**
569 * Factory that creates {@link NetworkStateTracker} instances using given
570 * {@link NetworkConfig}.
571 */
572 public interface NetworkFactory {
573 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
574 }
575
576 private static class DefaultNetworkFactory implements NetworkFactory {
577 private final Context mContext;
578 private final Handler mTrackerHandler;
579
580 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
581 mContext = context;
582 mTrackerHandler = trackerHandler;
583 }
584
585 @Override
586 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
587 switch (config.radio) {
588 case TYPE_WIFI:
589 return new WifiStateTracker(targetNetworkType, config.name);
590 case TYPE_MOBILE:
591 return new MobileDataStateTracker(targetNetworkType, config.name);
592 case TYPE_DUMMY:
593 return new DummyDataStateTracker(targetNetworkType, config.name);
594 case TYPE_BLUETOOTH:
595 return BluetoothTetheringDataTracker.getInstance();
596 case TYPE_WIMAX:
597 return makeWimaxStateTracker(mContext, mTrackerHandler);
598 case TYPE_ETHERNET:
599 return EthernetDataTracker.getInstance();
600 default:
601 throw new IllegalArgumentException(
602 "Trying to create a NetworkStateTracker for an unknown radio type: "
603 + config.radio);
604 }
605 }
606 }
607
608 /**
609 * Loads external WiMAX library and registers as system service, returning a
610 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
611 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
612 */
613 private static NetworkStateTracker makeWimaxStateTracker(
614 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700615 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900616 DexClassLoader wimaxClassLoader;
617 Class wimaxStateTrackerClass = null;
618 Class wimaxServiceClass = null;
619 Class wimaxManagerClass;
620 String wimaxJarLocation;
621 String wimaxLibLocation;
622 String wimaxManagerClassName;
623 String wimaxServiceClassName;
624 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625
tk.mun148c7d02011-10-13 22:51:57 +0900626 NetworkStateTracker wimaxStateTracker = null;
627
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700628 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900629 com.android.internal.R.bool.config_wimaxEnabled);
630
631 if (isWimaxEnabled) {
632 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700633 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900634 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700635 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900636 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700637 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900638 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700639 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900640 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700641 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900642 com.android.internal.R.string.config_wimaxStateTrackerClassname);
643
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800644 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900645 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700646 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900647 wimaxLibLocation, ClassLoader.getSystemClassLoader());
648
649 try {
650 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
651 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
652 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
653 } catch (ClassNotFoundException ex) {
654 loge("Exception finding Wimax classes: " + ex.toString());
655 return null;
656 }
657 } catch(Resources.NotFoundException ex) {
658 loge("Wimax Resources does not exist!!! ");
659 return null;
660 }
661
662 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800663 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900664
665 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
666 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700667 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
668 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900669
670 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
671 (new Class[] {Context.class, wimaxStateTrackerClass});
672 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700673 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900674 wmxSrvConst.setAccessible(false);
675
676 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
677
678 } catch(Exception ex) {
679 loge("Exception creating Wimax classes: " + ex.toString());
680 return null;
681 }
682 } else {
683 loge("Wimax is not enabled or not added to the network attributes!!! ");
684 return null;
685 }
686
687 return wimaxStateTracker;
688 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700691 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 * @param preference the new preference
693 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700694 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700696
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700697 mHandler.sendMessage(
698 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 }
700
701 public int getNetworkPreference() {
702 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700703 int preference;
704 synchronized(this) {
705 preference = mNetworkPreference;
706 }
707 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
709
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700710 private void handleSetNetworkPreference(int preference) {
711 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700712 mNetConfigs[preference] != null &&
713 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700714 if (mNetworkPreference != preference) {
715 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700716 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700717 synchronized(this) {
718 mNetworkPreference = preference;
719 }
720 enforcePreference();
721 }
722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700724
Wink Saville628b0852011-08-04 15:01:58 -0700725 private int getConnectivityChangeDelay() {
726 final ContentResolver cr = mContext.getContentResolver();
727
728 /** Check system properties for the default value then use secure settings value, if any. */
729 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700730 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
731 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
732 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700733 defaultDelay);
734 }
735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 private int getPersistedNetworkPreference() {
737 final ContentResolver cr = mContext.getContentResolver();
738
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700739 final int networkPrefSetting = Settings.Global
740 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800742 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700746 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 * In this method, we only tear down a non-preferred network. Establishing
748 * a connection to the preferred network is taken care of when we handle
749 * the disconnect event from the non-preferred network
750 * (see {@link #handleDisconnect(NetworkInfo)}).
751 */
752 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700753 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 return;
755
Robert Greenwalt42acef32009-08-12 16:08:25 -0700756 if (!mNetTrackers[mNetworkPreference].isAvailable())
757 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758
Robert Greenwalt42acef32009-08-12 16:08:25 -0700759 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700761 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700762 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800763 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700764 " in enforcePreference");
765 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700766 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 }
768 }
769 }
770
771 private boolean teardown(NetworkStateTracker netTracker) {
772 if (netTracker.teardown()) {
773 netTracker.setTeardownRequested(true);
774 return true;
775 } else {
776 return false;
777 }
778 }
779
780 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700781 * Check if UID should be blocked from using the network represented by the
782 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700783 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700784 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
785 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700786
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700787 final boolean networkCostly;
788 final int uidRules;
789 synchronized (mRulesLock) {
790 networkCostly = mMeteredIfaces.contains(iface);
791 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700792 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700793
794 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
795 return true;
796 }
797
798 // no restrictive rules; network is visible
799 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700800 }
801
802 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700803 * Return a filtered {@link NetworkInfo}, potentially marked
804 * {@link DetailedState#BLOCKED} based on
805 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700806 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700807 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
808 NetworkInfo info = tracker.getNetworkInfo();
809 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700810 // network is blocked; clone and override state
811 info = new NetworkInfo(info);
812 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700813 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700814 if (mLockdownTracker != null) {
815 info = mLockdownTracker.augmentNetworkInfo(info);
816 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700817 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700818 }
819
820 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 * Return NetworkInfo for the active (i.e., connected) network interface.
822 * It is assumed that at most one network is active at a time. If more
823 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700824 * @return the info for the active network, or {@code null} if none is
825 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700827 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700829 enforceAccessPermission();
830 final int uid = Binder.getCallingUid();
831 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700834 public NetworkInfo getActiveNetworkInfoUnfiltered() {
835 enforceAccessPermission();
836 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
837 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
838 if (tracker != null) {
839 return tracker.getNetworkInfo();
840 }
841 }
842 return null;
843 }
844
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700845 @Override
846 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
847 enforceConnectivityInternalPermission();
848 return getNetworkInfo(mActiveDefaultNetwork, uid);
849 }
850
851 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 public NetworkInfo getNetworkInfo(int networkType) {
853 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700854 final int uid = Binder.getCallingUid();
855 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700858 private NetworkInfo getNetworkInfo(int networkType, int uid) {
859 NetworkInfo info = null;
860 if (isNetworkTypeValid(networkType)) {
861 final NetworkStateTracker tracker = mNetTrackers[networkType];
862 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700863 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700864 }
865 }
866 return info;
867 }
868
869 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 public NetworkInfo[] getAllNetworkInfo() {
871 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700872 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700873 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700874 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 for (NetworkStateTracker tracker : mNetTrackers) {
876 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700877 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700878 }
879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700881 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
883
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700884 @Override
885 public boolean isNetworkSupported(int networkType) {
886 enforceAccessPermission();
887 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
888 }
889
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700890 /**
891 * Return LinkProperties for the active (i.e., connected) default
892 * network interface. It is assumed that at most one default network
893 * is active at a time. If more than one is active, it is indeterminate
894 * which will be returned.
895 * @return the ip properties for the active network, or {@code null} if
896 * none is active
897 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700898 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700899 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700900 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700901 }
902
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700903 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700904 public LinkProperties getLinkProperties(int networkType) {
905 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700906 if (isNetworkTypeValid(networkType)) {
907 final NetworkStateTracker tracker = mNetTrackers[networkType];
908 if (tracker != null) {
909 return tracker.getLinkProperties();
910 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700911 }
912 return null;
913 }
914
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700915 @Override
916 public NetworkState[] getAllNetworkState() {
917 enforceAccessPermission();
918 final int uid = Binder.getCallingUid();
919 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700920 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700921 for (NetworkStateTracker tracker : mNetTrackers) {
922 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700923 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700924 result.add(new NetworkState(
925 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
926 }
927 }
928 }
929 return result.toArray(new NetworkState[result.size()]);
930 }
931
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700932 private NetworkState getNetworkStateUnchecked(int networkType) {
933 if (isNetworkTypeValid(networkType)) {
934 final NetworkStateTracker tracker = mNetTrackers[networkType];
935 if (tracker != null) {
936 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
937 tracker.getLinkCapabilities());
938 }
939 }
940 return null;
941 }
942
943 @Override
944 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
945 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700946
947 final long token = Binder.clearCallingIdentity();
948 try {
949 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
950 if (state != null) {
951 try {
952 return mPolicyManager.getNetworkQuotaInfo(state);
953 } catch (RemoteException e) {
954 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700955 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700956 return null;
957 } finally {
958 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700959 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700960 }
961
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700962 @Override
963 public boolean isActiveNetworkMetered() {
964 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700965 final long token = Binder.clearCallingIdentity();
966 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700967 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700968 } finally {
969 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700970 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700971 }
972
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700973 private boolean isNetworkMeteredUnchecked(int networkType) {
974 final NetworkState state = getNetworkStateUnchecked(networkType);
975 if (state != null) {
976 try {
977 return mPolicyManager.isNetworkMetered(state);
978 } catch (RemoteException e) {
979 }
980 }
981 return false;
982 }
983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 public boolean setRadios(boolean turnOn) {
985 boolean result = true;
986 enforceChangePermission();
987 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700988 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990 return result;
991 }
992
993 public boolean setRadio(int netType, boolean turnOn) {
994 enforceChangePermission();
995 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
996 return false;
997 }
998 NetworkStateTracker tracker = mNetTrackers[netType];
999 return tracker != null && tracker.setRadio(turnOn);
1000 }
1001
Jeff Sharkey216c1812012-08-05 14:29:23 -07001002 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1003 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001004 public void interfaceClassDataActivityChanged(String label, boolean active) {
1005 int deviceType = Integer.parseInt(label);
1006 sendDataActivityBroadcast(deviceType, active);
1007 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001008 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001009
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001010 /**
1011 * Used to notice when the calling process dies so we can self-expire
1012 *
1013 * Also used to know if the process has cleaned up after itself when
1014 * our auto-expire timer goes off. The timer has a link to an object.
1015 *
1016 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001017 private class FeatureUser implements IBinder.DeathRecipient {
1018 int mNetworkType;
1019 String mFeature;
1020 IBinder mBinder;
1021 int mPid;
1022 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001023 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001024
1025 FeatureUser(int type, String feature, IBinder binder) {
1026 super();
1027 mNetworkType = type;
1028 mFeature = feature;
1029 mBinder = binder;
1030 mPid = getCallingPid();
1031 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001032 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001033
Robert Greenwalt42acef32009-08-12 16:08:25 -07001034 try {
1035 mBinder.linkToDeath(this, 0);
1036 } catch (RemoteException e) {
1037 binderDied();
1038 }
1039 }
1040
1041 void unlinkDeathRecipient() {
1042 mBinder.unlinkToDeath(this, 0);
1043 }
1044
1045 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001046 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001047 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1048 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001049 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001050 }
1051
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001052 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001053 if (VDBG) {
1054 log("ConnectivityService FeatureUser expire(" +
1055 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1056 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1057 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001058 stopUsingNetworkFeature(this, false);
1059 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001060
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001061 public boolean isSameUser(FeatureUser u) {
1062 if (u == null) return false;
1063
1064 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1065 }
1066
1067 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1068 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1069 TextUtils.equals(mFeature, feature)) {
1070 return true;
1071 }
1072 return false;
1073 }
1074
Robert Greenwaltb9285352009-12-21 18:24:07 -08001075 public String toString() {
1076 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1077 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1078 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001079 }
1080
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001081 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001082 public int startUsingNetworkFeature(int networkType, String feature,
1083 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001084 long startTime = 0;
1085 if (DBG) {
1086 startTime = SystemClock.elapsedRealtime();
1087 }
Wink Savillec9acde92011-09-21 11:05:43 -07001088 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001089 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1090 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001093 try {
1094 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1095 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001096 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001097 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001098
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001099 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001100
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001101 // TODO - move this into individual networktrackers
1102 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001103
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001104 if (mLockdownEnabled) {
1105 // Since carrier APNs usually aren't available from VPN
1106 // endpoint, mark them as unavailable.
1107 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1108 }
1109
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001110 if (mProtectedNetworks.contains(usedNetworkType)) {
1111 enforceConnectivityInternalPermission();
1112 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001113
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001114 // if UID is restricted, don't allow them to bring up metered APNs
1115 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1116 final int uidRules;
1117 synchronized (mRulesLock) {
1118 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1119 }
1120 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001121 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001122 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001123
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001124 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1125 if (network != null) {
1126 Integer currentPid = new Integer(getCallingPid());
1127 if (usedNetworkType != networkType) {
1128 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001129
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001130 if (ni.isAvailable() == false) {
1131 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1132 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001133 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001134 } else {
1135 // else make the attempt anyway - probably giving REQUEST_STARTED below
1136 if (DBG) {
1137 log("special network not available, but try anyway ni=" +
1138 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001139 }
1140 }
1141 }
1142
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001143 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001144
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001145 synchronized(this) {
1146 boolean addToList = true;
1147 if (restoreTimer < 0) {
1148 // In case there is no timer is specified for the feature,
1149 // make sure we don't add duplicate entry with the same request.
1150 for (FeatureUser u : mFeatureUsers) {
1151 if (u.isSameUser(f)) {
1152 // Duplicate user is found. Do not add.
1153 addToList = false;
1154 break;
1155 }
1156 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001157 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001158
1159 if (addToList) mFeatureUsers.add(f);
1160 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1161 // this gets used for per-pid dns when connected
1162 mNetRequestersPids[usedNetworkType].add(currentPid);
1163 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001164 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001165
1166 if (restoreTimer >= 0) {
1167 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1168 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1169 }
1170
1171 if ((ni.isConnectedOrConnecting() == true) &&
1172 !network.isTeardownRequested()) {
1173 if (ni.isConnected() == true) {
1174 final long token = Binder.clearCallingIdentity();
1175 try {
1176 // add the pid-specific dns
1177 handleDnsConfigurationChange(usedNetworkType);
1178 if (VDBG) log("special network already active");
1179 } finally {
1180 Binder.restoreCallingIdentity(token);
1181 }
Wink Savillea639b312012-07-10 12:37:54 -07001182 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001183 }
1184 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001185 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001186 }
1187
1188 // check if the radio in play can make another contact
1189 // assume if cannot for now
1190
1191 if (DBG) {
1192 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1193 feature);
1194 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001195 if (network.reconnect()) {
1196 return PhoneConstants.APN_REQUEST_STARTED;
1197 } else {
1198 return PhoneConstants.APN_REQUEST_FAILED;
1199 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001200 } else {
1201 // need to remember this unsupported request so we respond appropriately on stop
1202 synchronized(this) {
1203 mFeatureUsers.add(f);
1204 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1205 // this gets used for per-pid dns when connected
1206 mNetRequestersPids[usedNetworkType].add(currentPid);
1207 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001208 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001209 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001210 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001211 }
Wink Savillea639b312012-07-10 12:37:54 -07001212 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001213 } finally {
1214 if (DBG) {
1215 final long execTime = SystemClock.elapsedRealtime() - startTime;
1216 if (execTime > 250) {
1217 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1218 } else {
1219 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1220 }
1221 }
1222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001225 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001227 enforceChangePermission();
1228
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001229 int pid = getCallingPid();
1230 int uid = getCallingUid();
1231
1232 FeatureUser u = null;
1233 boolean found = false;
1234
1235 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001236 for (FeatureUser x : mFeatureUsers) {
1237 if (x.isSameUser(pid, uid, networkType, feature)) {
1238 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001239 found = true;
1240 break;
1241 }
1242 }
1243 }
1244 if (found && u != null) {
1245 // stop regardless of how many other time this proc had called start
1246 return stopUsingNetworkFeature(u, true);
1247 } else {
1248 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001249 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001250 return 1;
1251 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001252 }
1253
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001254 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1255 int networkType = u.mNetworkType;
1256 String feature = u.mFeature;
1257 int pid = u.mPid;
1258 int uid = u.mUid;
1259
1260 NetworkStateTracker tracker = null;
1261 boolean callTeardown = false; // used to carry our decision outside of sync block
1262
Wink Savillec9acde92011-09-21 11:05:43 -07001263 if (VDBG) {
1264 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001265 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001268 if (DBG) {
1269 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1270 ", net is invalid");
1271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 return -1;
1273 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001274
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001275 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1276 // sync block
1277 synchronized(this) {
1278 // check if this process still has an outstanding start request
1279 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001280 if (VDBG) {
1281 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1282 ", ignoring");
1283 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001284 return 1;
1285 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001286 u.unlinkDeathRecipient();
1287 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1288 // If we care about duplicate requests, check for that here.
1289 //
1290 // This is done to support the extension of a request - the app
1291 // can request we start the network feature again and renew the
1292 // auto-shutoff delay. Normal "stop" calls from the app though
1293 // do not pay attention to duplicate requests - in effect the
1294 // API does not refcount and a single stop will counter multiple starts.
1295 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001296 for (FeatureUser x : mFeatureUsers) {
1297 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001298 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001299 return 1;
1300 }
1301 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001302 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001303
repo syncaea743a2011-07-29 23:55:49 -07001304 // TODO - move to individual network trackers
1305 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1306
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001307 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001308 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001309 if (DBG) {
1310 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1311 " no known tracker for used net type " + usedNetworkType);
1312 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001313 return -1;
1314 }
1315 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001316 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001317 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001318
1319 final long token = Binder.clearCallingIdentity();
1320 try {
1321 reassessPidDns(pid, true);
1322 } finally {
1323 Binder.restoreCallingIdentity(token);
1324 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001325 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001326 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001327 if (VDBG) {
1328 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1329 " others still using it");
1330 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001331 return 1;
1332 }
1333 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001334 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001335 if (DBG) {
1336 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1337 " not a known feature - dropping");
1338 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001339 }
1340 }
Wink Savillec9acde92011-09-21 11:05:43 -07001341
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001342 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001343 if (DBG) {
1344 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1345 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001346 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001347 return 1;
1348 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001349 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
1352
1353 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001354 * @deprecated use requestRouteToHostAddress instead
1355 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 * Ensure that a network route exists to deliver traffic to the specified
1357 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001358 * @param networkType the type of the network over which traffic to the
1359 * specified host is to be routed
1360 * @param hostAddress the IP address of the host to which the route is
1361 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 * @return {@code true} on success, {@code false} on failure
1363 */
1364 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001365 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1366
1367 if (inetAddress == null) {
1368 return false;
1369 }
1370
1371 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1372 }
1373
1374 /**
1375 * Ensure that a network route exists to deliver traffic to the specified
1376 * host via the specified network interface.
1377 * @param networkType the type of the network over which traffic to the
1378 * specified host is to be routed
1379 * @param hostAddress the IP address of the host to which the route is
1380 * desired
1381 * @return {@code true} on success, {@code false} on failure
1382 */
1383 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001385 if (mProtectedNetworks.contains(networkType)) {
1386 enforceConnectivityInternalPermission();
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001390 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 return false;
1392 }
1393 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001394 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001395
Irfan Sheriffda6da092012-08-16 12:49:23 -07001396 if (tracker == null || (netState != DetailedState.CONNECTED &&
1397 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001398 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001399 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001400 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001401 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001402 }
1403 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001405 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001406 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001407 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001408 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001409 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001410 } catch (UnknownHostException e) {
1411 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1412 } finally {
1413 Binder.restoreCallingIdentity(token);
1414 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001415 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001416 }
1417
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001418 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1419 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001420 }
1421
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001422 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1423 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001424 }
1425
Robert Greenwaltad55d352011-07-22 11:55:33 -07001426 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001427 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001428 }
1429
1430 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001431 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001432 }
1433
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001434 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1435 boolean toDefaultTable) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001436 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1437 if (bestRoute == null) {
1438 bestRoute = RouteInfo.makeHostRoute(addr);
1439 } else {
1440 if (bestRoute.getGateway().equals(addr)) {
1441 // if there is no better route, add the implied hostroute for our gateway
1442 bestRoute = RouteInfo.makeHostRoute(addr);
1443 } else {
1444 // if we will connect to this through another route, add a direct route
1445 // to it's gateway
1446 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1447 }
1448 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001449 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 }
1451
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001452 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001453 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001454 if ((ifaceName == null) || (lp == null) || (r == null)) {
1455 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1456 return false;
1457 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001458
1459 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001460 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001461 return false;
1462 }
1463
1464 if (r.isHostRoute() == false) {
1465 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1466 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001467 if (bestRoute.getGateway().equals(r.getGateway())) {
1468 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001469 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001470 } else {
1471 // if we will connect to our gateway through another route, add a direct
1472 // route to it's gateway
1473 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001474 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001475 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001476 }
1477 }
1478 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001479 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001480 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001481 if (toDefaultTable) {
1482 mAddedRoutes.add(r); // only track default table - only one apps can effect
1483 mNetd.addRoute(ifaceName, r);
1484 } else {
1485 mNetd.addSecondaryRoute(ifaceName, r);
1486 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001487 } catch (Exception e) {
1488 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001489 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001490 return false;
1491 }
1492 } else {
1493 // if we remove this one and there are no more like it, then refcount==0 and
1494 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001495 if (toDefaultTable) {
1496 mAddedRoutes.remove(r);
1497 if (mAddedRoutes.contains(r) == false) {
1498 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1499 try {
1500 mNetd.removeRoute(ifaceName, r);
1501 } catch (Exception e) {
1502 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001503 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001504 return false;
1505 }
1506 } else {
1507 if (VDBG) log("not removing " + r + " as it's still in use");
1508 }
1509 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001510 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001511 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001512 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001513 } catch (Exception e) {
1514 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001515 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001516 return false;
1517 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001518 }
1519 }
1520 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
1523 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001524 * @see ConnectivityManager#getMobileDataEnabled()
1525 */
1526 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001527 // TODO: This detail should probably be in DataConnectionTracker's
1528 // which is where we store the value and maybe make this
1529 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001530 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001531 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1532 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001533 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001534 return retVal;
1535 }
1536
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001537 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001538 enforceConnectivityInternalPermission();
1539
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1541 (met ? ENABLED : DISABLED), networkType));
1542 }
1543
1544 private void handleSetDependencyMet(int networkType, boolean met) {
1545 if (mNetTrackers[networkType] != null) {
1546 if (DBG) {
1547 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1548 }
1549 mNetTrackers[networkType].setDependencyMet(met);
1550 }
1551 }
1552
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001553 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1554 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001555 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001556 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001557 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001558 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001559 }
1560
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001561 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001562 // skip update when we've already applied rules
1563 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1564 if (oldRules == uidRules) return;
1565
1566 mUidRules.put(uid, uidRules);
1567 }
1568
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001569 // TODO: notify UID when it has requested targeted updates
1570 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001571
1572 @Override
1573 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001574 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001575 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001576 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001577 }
1578
1579 synchronized (mRulesLock) {
1580 mMeteredIfaces.clear();
1581 for (String iface : meteredIfaces) {
1582 mMeteredIfaces.add(iface);
1583 }
1584 }
1585 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001586
1587 @Override
1588 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1589 // caller is NPMS, since we only register with them
1590 if (LOGD_RULES) {
1591 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1592 }
1593
1594 // kick off connectivity change broadcast for active network, since
1595 // global background policy change is radical.
1596 final int networkType = mActiveDefaultNetwork;
1597 if (isNetworkTypeValid(networkType)) {
1598 final NetworkStateTracker tracker = mNetTrackers[networkType];
1599 if (tracker != null) {
1600 final NetworkInfo info = tracker.getNetworkInfo();
1601 if (info != null && info.isConnected()) {
1602 sendConnectedBroadcast(info);
1603 }
1604 }
1605 }
1606 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001607 };
1608
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001609 /**
1610 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1611 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001612 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001613 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001614 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001615
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001616 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001617 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001618 }
1619
1620 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001621 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001622 if (VDBG) {
1623 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001624 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001625 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1626 }
tk.munb97d34c2012-01-06 10:43:52 +09001627 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1628 if (VDBG) {
1629 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1630 }
1631 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1632 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001633 }
1634
1635 @Override
1636 public void setPolicyDataEnable(int networkType, boolean enabled) {
1637 // only someone like NPMS should only be calling us
1638 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1639
1640 mHandler.sendMessage(mHandler.obtainMessage(
1641 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1642 }
1643
1644 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1645 if (isNetworkTypeValid(networkType)) {
1646 final NetworkStateTracker tracker = mNetTrackers[networkType];
1647 if (tracker != null) {
1648 tracker.setPolicyDataEnable(enabled);
1649 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001650 }
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001654 mContext.enforceCallingOrSelfPermission(
1655 android.Manifest.permission.ACCESS_NETWORK_STATE,
1656 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658
1659 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001660 mContext.enforceCallingOrSelfPermission(
1661 android.Manifest.permission.CHANGE_NETWORK_STATE,
1662 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001665 // TODO Make this a special check when it goes public
1666 private void enforceTetherChangePermission() {
1667 mContext.enforceCallingOrSelfPermission(
1668 android.Manifest.permission.CHANGE_NETWORK_STATE,
1669 "ConnectivityService");
1670 }
1671
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001672 private void enforceTetherAccessPermission() {
1673 mContext.enforceCallingOrSelfPermission(
1674 android.Manifest.permission.ACCESS_NETWORK_STATE,
1675 "ConnectivityService");
1676 }
1677
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001678 private void enforceConnectivityInternalPermission() {
1679 mContext.enforceCallingOrSelfPermission(
1680 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1681 "ConnectivityService");
1682 }
1683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001685 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1686 * network, we ignore it. If it is for the active network, we send out a
1687 * broadcast. But first, we check whether it might be possible to connect
1688 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 * @param info the {@code NetworkInfo} for the network
1690 */
1691 private void handleDisconnect(NetworkInfo info) {
1692
Robert Greenwalt42acef32009-08-12 16:08:25 -07001693 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694
Robert Greenwalt42acef32009-08-12 16:08:25 -07001695 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001696
1697 // Remove idletimer previously setup in {@code handleConnect}
1698 removeDataActivityTracking(prevNetType);
1699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 /*
1701 * If the disconnected network is not the active one, then don't report
1702 * this as a loss of connectivity. What probably happened is that we're
1703 * getting the disconnect for a network that we explicitly disabled
1704 * in accordance with network preference policies.
1705 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001706 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001707 List<Integer> pids = mNetRequestersPids[prevNetType];
1708 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001709 // will remove them because the net's no longer connected
1710 // need to do this now as only now do we know the pids and
1711 // can properly null things that are no longer referenced.
1712 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001717 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001718 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 if (info.isFailover()) {
1720 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1721 info.setFailover(false);
1722 }
1723 if (info.getReason() != null) {
1724 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1725 }
1726 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001727 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1728 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001730
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001731 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001732 tryFailover(prevNetType);
1733 if (mActiveDefaultNetwork != -1) {
1734 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001735 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1736 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001737 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001738 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1739 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001740 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001741 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001742
1743 // Reset interface if no other connections are using the same interface
1744 boolean doReset = true;
1745 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1746 if (linkProperties != null) {
1747 String oldIface = linkProperties.getInterfaceName();
1748 if (TextUtils.isEmpty(oldIface) == false) {
1749 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1750 if (networkStateTracker == null) continue;
1751 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1752 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1753 LinkProperties l = networkStateTracker.getLinkProperties();
1754 if (l == null) continue;
1755 if (oldIface.equals(l.getInterfaceName())) {
1756 doReset = false;
1757 break;
1758 }
1759 }
1760 }
1761 }
1762 }
1763
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001764 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001765 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001766
Jeff Sharkey961e3042011-08-29 16:02:57 -07001767 final Intent immediateIntent = new Intent(intent);
1768 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1769 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001770 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001771 /*
1772 * If the failover network is already connected, then immediately send
1773 * out a followup broadcast indicating successful failover
1774 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001775 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001776 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1777 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001778 }
1779 }
1780
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001781 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001782 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001783 * If this is a default network, check if other defaults are available.
1784 * Try to reconnect on all available and let them hash it out when
1785 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001786 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001787 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001788 if (mActiveDefaultNetwork == prevNetType) {
1789 mActiveDefaultNetwork = -1;
1790 }
1791
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001792 // don't signal a reconnect for anything lower or equal priority than our
1793 // current connected default
1794 // TODO - don't filter by priority now - nice optimization but risky
1795// int currentPriority = -1;
1796// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001797// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001798// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001799 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001800 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001801 if (mNetConfigs[checkType] == null) continue;
1802 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001803 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001804
1805// Enabling the isAvailable() optimization caused mobile to not get
1806// selected if it was in the middle of error handling. Specifically
1807// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1808// would not be available and we wouldn't get connected to anything.
1809// So removing the isAvailable() optimization below for now. TODO: This
1810// optimization should work and we need to investigate why it doesn't work.
1811// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1812// complete before it is really complete.
1813// if (!mNetTrackers[checkType].isAvailable()) continue;
1814
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001815// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001816
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001817 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1818 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1819 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1820 checkInfo.setFailover(true);
1821 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001822 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001823 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001828 public void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001829 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1830 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001831 }
1832
Wink Saville628b0852011-08-04 15:01:58 -07001833 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001834 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1835 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001836 }
1837
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001838 private void sendInetConditionBroadcast(NetworkInfo info) {
1839 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1840 }
1841
Wink Saville628b0852011-08-04 15:01:58 -07001842 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001843 if (mLockdownTracker != null) {
1844 info = mLockdownTracker.augmentNetworkInfo(info);
1845 }
1846
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001847 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001848 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001849 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 if (info.isFailover()) {
1851 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1852 info.setFailover(false);
1853 }
1854 if (info.getReason() != null) {
1855 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1856 }
1857 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001858 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1859 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001861 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001862 return intent;
1863 }
1864
1865 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1866 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1867 }
1868
1869 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1870 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 }
1872
Haoyu Baidb3c8672012-06-20 14:29:57 -07001873 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1874 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1875 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1876 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001877 final long ident = Binder.clearCallingIdentity();
1878 try {
1879 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1880 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1881 } finally {
1882 Binder.restoreCallingIdentity(ident);
1883 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001884 }
1885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 /**
1887 * Called when an attempt to fail over to another network has failed.
1888 * @param info the {@link NetworkInfo} for the failed network
1889 */
1890 private void handleConnectionFailure(NetworkInfo info) {
1891 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892
Robert Greenwalt42acef32009-08-12 16:08:25 -07001893 String reason = info.getReason();
1894 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001895
Robert Greenwalt572172b2010-10-08 16:35:52 -07001896 String reasonText;
1897 if (reason == null) {
1898 reasonText = ".";
1899 } else {
1900 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001902 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001903
1904 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001905 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001906 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001907 if (getActiveNetworkInfo() == null) {
1908 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1909 }
1910 if (reason != null) {
1911 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1912 }
1913 if (extraInfo != null) {
1914 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1915 }
1916 if (info.isFailover()) {
1917 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1918 info.setFailover(false);
1919 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001920
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001921 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001922 tryFailover(info.getType());
1923 if (mActiveDefaultNetwork != -1) {
1924 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001925 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1926 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001927 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001928 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1929 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001930 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001931
Robert Greenwalt029be812010-09-20 18:01:43 -07001932 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001933
1934 final Intent immediateIntent = new Intent(intent);
1935 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1936 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001937 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001938 /*
1939 * If the failover network is already connected, then immediately send
1940 * out a followup broadcast indicating successful failover
1941 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001942 if (mActiveDefaultNetwork != -1) {
1943 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001944 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001945 }
1946
1947 private void sendStickyBroadcast(Intent intent) {
1948 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001949 if (!mSystemReady) {
1950 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001951 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001952 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001953 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001954 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001955 }
1956
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001957 final long ident = Binder.clearCallingIdentity();
1958 try {
1959 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1960 } finally {
1961 Binder.restoreCallingIdentity(ident);
1962 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001963 }
1964 }
1965
Wink Saville628b0852011-08-04 15:01:58 -07001966 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1967 if (delayMs <= 0) {
1968 sendStickyBroadcast(intent);
1969 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001970 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001971 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1972 + intent.getAction());
1973 }
Wink Saville628b0852011-08-04 15:01:58 -07001974 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1975 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1976 }
1977 }
1978
Mike Lockwood0f79b542009-08-14 14:18:49 -04001979 void systemReady() {
1980 synchronized(this) {
1981 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001982 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001983 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001984 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001985 }
1986 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001987 // load the global proxy at startup
1988 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001989
1990 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1991 // for user to unlock device.
1992 if (!updateLockdownVpn()) {
1993 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1994 mContext.registerReceiver(mUserPresentReceiver, filter);
1995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001998 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1999 @Override
2000 public void onReceive(Context context, Intent intent) {
2001 // Try creating lockdown tracker, since user present usually means
2002 // unlocked keystore.
2003 if (updateLockdownVpn()) {
2004 mContext.unregisterReceiver(this);
2005 }
2006 }
2007 };
2008
Irfan Sheriffda6da092012-08-16 12:49:23 -07002009 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2010 if ((type != mNetworkPreference &&
2011 mNetConfigs[mActiveDefaultNetwork].priority >
2012 mNetConfigs[type].priority) ||
2013 mNetworkPreference == mActiveDefaultNetwork) return false;
2014 return true;
2015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016
Irfan Sheriffda6da092012-08-16 12:49:23 -07002017 private void handleConnect(NetworkInfo info) {
2018 final int newNetType = info.getType();
2019
2020 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 // snapshot isFailover, because sendConnectedBroadcast() resets it
2023 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002024 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002025 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026
Robert Greenwalt42acef32009-08-12 16:08:25 -07002027 // if this is a default net and other default is running
2028 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002029 if (mNetConfigs[newNetType].isDefault()) {
2030 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2031 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002032 // tear down the other
2033 NetworkStateTracker otherNet =
2034 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002035 if (DBG) {
2036 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002037 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002038 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002039 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002040 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002041 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002042 return;
2043 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002044 } else {
2045 // don't accept this one
2046 if (VDBG) {
2047 log("Not broadcasting CONNECT_ACTION " +
2048 "to torn down network " + info.getTypeName());
2049 }
2050 teardown(thisNet);
2051 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002052 }
2053 }
2054 synchronized (ConnectivityService.this) {
2055 // have a new default network, release the transition wakelock in a second
2056 // if it's held. The second pause is to allow apps to reconnect over the
2057 // new network
2058 if (mNetTransitionWakeLock.isHeld()) {
2059 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002060 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002061 mNetTransitionWakeLockSerialNumber, 0),
2062 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002063 }
2064 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002065 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002066 // this will cause us to come up initially as unconnected and switching
2067 // to connected after our normal pause unless somebody reports us as reall
2068 // disconnected
2069 mDefaultInetConditionPublished = 0;
2070 mDefaultConnectionSequence++;
2071 mInetConditionChangeInFlight = false;
2072 // Don't do this - if we never sign in stay, grey
2073 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002076 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002077 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002078 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002079
2080 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002081 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002082 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002083 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002084 } catch (RemoteException e) {
2085 // ignored; service lives in system_server
2086 }
2087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
Irfan Sheriffda6da092012-08-16 12:49:23 -07002090 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2091 if (DBG) log("Captive portal check " + info);
2092 int type = info.getType();
2093 final NetworkStateTracker thisNet = mNetTrackers[type];
2094 if (mNetConfigs[type].isDefault()) {
2095 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2096 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2097 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002098 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002099 return;
2100 } else {
2101 if (DBG) log("Tear down low priority net " + info.getTypeName());
2102 teardown(thisNet);
2103 return;
2104 }
2105 }
2106 }
2107
2108 thisNet.captivePortalCheckComplete();
2109 }
2110
2111 /** @hide */
2112 public void captivePortalCheckComplete(NetworkInfo info) {
2113 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002114 }
2115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002117 * Setup data activity tracking for the given network interface.
2118 *
2119 * Every {@code setupDataActivityTracking} should be paired with a
2120 * {@link removeDataActivityTracking} for cleanup.
2121 */
2122 private void setupDataActivityTracking(int type) {
2123 final NetworkStateTracker thisNet = mNetTrackers[type];
2124 final String iface = thisNet.getLinkProperties().getInterfaceName();
2125
2126 final int timeout;
2127
2128 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002129 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2130 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002131 0);
2132 // Canonicalize mobile network type
2133 type = ConnectivityManager.TYPE_MOBILE;
2134 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002135 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2136 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002137 0);
2138 } else {
2139 // do not track any other networks
2140 timeout = 0;
2141 }
2142
2143 if (timeout > 0 && iface != null) {
2144 try {
2145 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2146 } catch (RemoteException e) {
2147 }
2148 }
2149 }
2150
2151 /**
2152 * Remove data activity tracking when network disconnects.
2153 */
2154 private void removeDataActivityTracking(int type) {
2155 final NetworkStateTracker net = mNetTrackers[type];
2156 final String iface = net.getLinkProperties().getInterfaceName();
2157
2158 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2159 ConnectivityManager.TYPE_WIFI == type)) {
2160 try {
2161 // the call fails silently if no idletimer setup for this interface
2162 mNetd.removeIdleTimer(iface);
2163 } catch (RemoteException e) {
2164 }
2165 }
2166 }
2167
2168 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002169 * After a change in the connectivity state of a network. We're mainly
2170 * concerned with making sure that the list of DNS servers is set up
2171 * according to which networks are connected, and ensuring that the
2172 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002174 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002175 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002178 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002179 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002181 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002182
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002183 LinkProperties curLp = mCurrentLinkProperties[netType];
2184 LinkProperties newLp = null;
2185
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002186 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002187 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002188 if (VDBG) {
2189 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2190 " doReset=" + doReset + " resetMask=" + resetMask +
2191 "\n curLp=" + curLp +
2192 "\n newLp=" + newLp);
2193 }
2194
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002195 if (curLp != null) {
2196 if (curLp.isIdenticalInterfaceName(newLp)) {
2197 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2198 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2199 for (LinkAddress linkAddr : car.removed) {
2200 if (linkAddr.getAddress() instanceof Inet4Address) {
2201 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2202 }
2203 if (linkAddr.getAddress() instanceof Inet6Address) {
2204 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2205 }
Wink Savillee8222252011-07-13 13:44:13 -07002206 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002207 if (DBG) {
2208 log("handleConnectivityChange: addresses changed" +
2209 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2210 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002211 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002212 } else {
2213 if (DBG) {
2214 log("handleConnectivityChange: address are the same reset per doReset" +
2215 " linkProperty[" + netType + "]:" +
2216 " resetMask=" + resetMask);
2217 }
Wink Savillee8222252011-07-13 13:44:13 -07002218 }
2219 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002220 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002221 if (DBG) {
2222 log("handleConnectivityChange: interface not not equivalent reset both" +
2223 " linkProperty[" + netType + "]:" +
2224 " resetMask=" + resetMask);
2225 }
Wink Savillee8222252011-07-13 13:44:13 -07002226 }
Wink Savillee8222252011-07-13 13:44:13 -07002227 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002228 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002229 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002230 }
2231 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002232 if (VDBG) {
2233 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2234 " doReset=" + doReset + " resetMask=" + resetMask +
2235 "\n curLp=" + curLp +
2236 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002239 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002240 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002241
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002242 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07002243 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2244 if (linkProperties != null) {
2245 String iface = linkProperties.getInterfaceName();
2246 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002247 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07002248 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2249 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002250
2251 // Tell VPN the interface is down. It is a temporary
2252 // but effective fix to make VPN aware of the change.
2253 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2254 mVpn.interfaceStatusChanged(iface, false);
2255 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002256 }
2257 if (resetDns) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002258 flushVmDnsCache();
Wink Savillec9acde92011-09-21 11:05:43 -07002259 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002260 try {
2261 mNetd.flushInterfaceDnsCache(iface);
2262 } catch (Exception e) {
2263 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07002264 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002265 }
2266 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002267 }
2268 }
2269 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002270
2271 // TODO: Temporary notifying upstread change to Tethering.
2272 // @see bug/4455071
2273 /** Notify TetheringService if interface name has been changed. */
2274 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002275 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002276 if (isTetheringSupported()) {
2277 mTethering.handleTetherIfaceChange();
2278 }
2279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002282 /**
2283 * Add and remove routes using the old properties (null if not previously connected),
2284 * new properties (null if becoming disconnected). May even be double null, which
2285 * is a noop.
2286 * Uses isLinkDefault to determine if default routes should be set or conversely if
2287 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002288 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002289 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002290 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2291 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002292 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002293 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2294 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002295 if (curLp != null) {
2296 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002297 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002298 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002299 } else if (newLp != null) {
2300 routeDiff.added = newLp.getRoutes();
2301 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002302 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002303
Robert Greenwaltf125a092011-08-15 12:31:55 -07002304 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2305
Robert Greenwaltad55d352011-07-22 11:55:33 -07002306 for (RouteInfo r : routeDiff.removed) {
2307 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002308 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2309 }
2310 if (isLinkDefault == false) {
2311 // remove from a secondary route table
2312 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002313 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002314 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002315
Robert Greenwaltad55d352011-07-22 11:55:33 -07002316 for (RouteInfo r : routeDiff.added) {
2317 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002318 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002319 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002320 // add to a secondary route table
2321 addRoute(newLp, r, TO_SECONDARY_TABLE);
2322
Robert Greenwalte6b24292011-08-09 16:52:58 -07002323 // many radios add a default route even when we don't want one.
2324 // remove the default route unless somebody else has asked for it
2325 String ifaceName = newLp.getInterfaceName();
2326 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002327 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002328 try {
2329 mNetd.removeRoute(ifaceName, r);
2330 } catch (Exception e) {
2331 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08002332 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002333 }
2334 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002335 }
2336 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002337
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002338 if (!isLinkDefault) {
2339 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002340 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002341 // routes changed - remove all old dns entries and add new
2342 if (curLp != null) {
2343 for (InetAddress oldDns : curLp.getDnses()) {
2344 removeRouteToAddress(curLp, oldDns);
2345 }
2346 }
2347 if (newLp != null) {
2348 for (InetAddress newDns : newLp.getDnses()) {
2349 addRouteToAddress(newLp, newDns);
2350 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002351 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002352 } else {
2353 // no change in routes, check for change in dns themselves
2354 for (InetAddress oldDns : dnsDiff.removed) {
2355 removeRouteToAddress(curLp, oldDns);
2356 }
2357 for (InetAddress newDns : dnsDiff.added) {
2358 addRouteToAddress(newLp, newDns);
2359 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002360 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002361 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002362 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002363 }
2364
2365
Irfan Sheriffd649c122010-06-09 15:39:36 -07002366 /**
2367 * Reads the network specific TCP buffer sizes from SystemProperties
2368 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2369 * wide use
2370 */
2371 public void updateNetworkSettings(NetworkStateTracker nt) {
2372 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002373 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002374
Jeff Sharkey899223b2012-08-04 15:24:58 -07002375 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002376 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002377
2378 // Setting to default values so we won't be stuck to previous values
2379 key = "net.tcp.buffersize.default";
2380 bufferSizes = SystemProperties.get(key);
2381 }
2382
2383 // Set values in kernel
2384 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002385 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002386 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002387 + "] which comes from [" + key + "]");
2388 }
2389 setBufferSize(bufferSizes);
2390 }
2391 }
2392
2393 /**
2394 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2395 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2396 *
2397 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2398 * writeMin, writeInitial, writeMax"
2399 */
2400 private void setBufferSize(String bufferSizes) {
2401 try {
2402 String[] values = bufferSizes.split(",");
2403
2404 if (values.length == 6) {
2405 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002406 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2407 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2408 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2409 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2410 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2411 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002412 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002413 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002414 }
2415 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002416 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002417 }
2418 }
2419
Robert Greenwalt42acef32009-08-12 16:08:25 -07002420 /**
2421 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2422 * on the highest priority active net which this process requested.
2423 * If there aren't any, clear it out
2424 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002425 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002426 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002427 if (VDBG) log("reassessPidDns for pid " + pid);
2428 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002429 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002430 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002431 continue;
2432 }
2433 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002434 if (nt.getNetworkInfo().isConnected() &&
2435 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002436 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002437 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002438 if (mNetRequestersPids[i].contains(myPid)) {
2439 try {
2440 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2441 } catch (Exception e) {
2442 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002443 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002444 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002445 }
2446 }
2447 }
2448 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002449 try {
2450 mNetd.clearDnsInterfaceForPid(pid);
2451 } catch (Exception e) {
2452 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002453 }
2454 }
2455
Mattias Falk8b47b362011-08-23 14:15:13 +02002456 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002457 /*
2458 * Tell the VMs to toss their DNS caches
2459 */
2460 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2461 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002462 /*
2463 * Connectivity events can happen before boot has completed ...
2464 */
2465 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002466 final long ident = Binder.clearCallingIdentity();
2467 try {
2468 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2469 } finally {
2470 Binder.restoreCallingIdentity(ident);
2471 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002472 }
2473
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002474 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002475 private void updateDnsLocked(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002476 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002477 int last = 0;
2478 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002479 dnses = new ArrayList();
2480 dnses.add(mDefaultDns);
2481 if (DBG) {
2482 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002483 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002484 }
2485
Mattias Falk8b47b362011-08-23 14:15:13 +02002486 try {
2487 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2488 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002489 for (InetAddress dns : dnses) {
2490 ++last;
2491 String key = "net.dns" + last;
2492 String value = dns.getHostAddress();
2493 SystemProperties.set(key, value);
2494 }
2495 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2496 String key = "net.dns" + i;
2497 SystemProperties.set(key, "");
2498 }
2499 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002500 } catch (Exception e) {
2501 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002502 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002503 }
2504
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002505 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002506 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002507 NetworkStateTracker nt = mNetTrackers[netType];
2508 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002509 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002510 if (p == null) return;
2511 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002512 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002513 String network = nt.getNetworkInfo().getTypeName();
2514 synchronized (mDnsLock) {
2515 if (!mDnsOverridden) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002516 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002517 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002518 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002519 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002520 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002521 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002522 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002523 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002524 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002525 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002526 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002527 List<Integer> pids = mNetRequestersPids[netType];
2528 for (Integer pid : pids) {
2529 try {
2530 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2531 } catch (Exception e) {
2532 Slog.e(TAG, "exception setting interface for pid: " + e);
2533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002536 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002538 }
2539
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002540 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002541 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2542 NETWORK_RESTORE_DELAY_PROP_NAME);
2543 if(restoreDefaultNetworkDelayStr != null &&
2544 restoreDefaultNetworkDelayStr.length() != 0) {
2545 try {
2546 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2547 } catch (NumberFormatException e) {
2548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002550 // if the system property isn't set, use the value for the apn type
2551 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2552
2553 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2554 (mNetConfigs[networkType] != null)) {
2555 ret = mNetConfigs[networkType].restoreTime;
2556 }
2557 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 }
2559
2560 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002561 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2562 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002563 if (mContext.checkCallingOrSelfPermission(
2564 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002566 pw.println("Permission Denial: can't dump ConnectivityService " +
2567 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2568 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 return;
2570 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002571
2572 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002574 for (int i = 0; i < mNetTrackers.length; i++) {
2575 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002576 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002577 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2578 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002579 if (nst.getNetworkInfo().isConnected()) {
2580 pw.println("Active network: " + nst.getNetworkInfo().
2581 getTypeName());
2582 }
2583 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002584 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002585 pw.println(nst);
2586 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002587 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002590
2591 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002592 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002593 for (int net : mPriorityList) {
2594 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002595 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002596 pidString = pidString + pid.toString() + ", ";
2597 }
2598 pw.println(pidString);
2599 }
2600 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002601 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002602
2603 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002604 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002605 for (Object requester : mFeatureUsers) {
2606 pw.println(requester.toString());
2607 }
2608 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002609 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002610
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002611 synchronized (this) {
2612 pw.println("NetworkTranstionWakeLock is currently " +
2613 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2614 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2615 }
2616 pw.println();
2617
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002618 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002619
2620 if (mInetLog != null) {
2621 pw.println();
2622 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002623 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002624 for(int i = 0; i < mInetLog.size(); i++) {
2625 pw.println(mInetLog.get(i));
2626 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002627 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630
Robert Greenwalt42acef32009-08-12 16:08:25 -07002631 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002632 private class NetworkStateTrackerHandler extends Handler {
2633 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002634 super(looper);
2635 }
2636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 @Override
2638 public void handleMessage(Message msg) {
2639 NetworkInfo info;
2640 switch (msg.what) {
2641 case NetworkStateTracker.EVENT_STATE_CHANGED:
2642 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002643 int type = info.getType();
2644 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002645
Wink Savillec9acde92011-09-21 11:05:43 -07002646 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2647 (state == NetworkInfo.State.DISCONNECTED)) {
2648 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002649 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002650 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652
Jeff Sharkey2528b502012-11-09 15:57:02 -08002653 EventLogTags.writeConnectivityStateChanged(
2654 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002655
2656 if (info.getDetailedState() ==
2657 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002659 } else if (info.getDetailedState() ==
2660 DetailedState.CAPTIVE_PORTAL_CHECK) {
2661 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002662 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002664 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002666 // the logic here is, handle SUSPENDED the same as
2667 // DISCONNECTED. The only difference being we are
2668 // broadcasting an intent with NetworkInfo that's
2669 // suspended. This allows the applications an
2670 // opportunity to handle DISCONNECTED and SUSPENDED
2671 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002673 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 handleConnect(info);
2675 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002676 if (mLockdownTracker != null) {
2677 mLockdownTracker.onNetworkInfoChanged(info);
2678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002681 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002682 // TODO: Temporary allowing network configuration
2683 // change not resetting sockets.
2684 // @see bug/4455071
2685 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002687 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2688 info = (NetworkInfo) msg.obj;
2689 type = info.getType();
2690 updateNetworkSettings(mNetTrackers[type]);
2691 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002692 }
2693 }
2694 }
2695
2696 private class InternalHandler extends Handler {
2697 public InternalHandler(Looper looper) {
2698 super(looper);
2699 }
2700
2701 @Override
2702 public void handleMessage(Message msg) {
2703 NetworkInfo info;
2704 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002705 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002706 String causedBy = null;
2707 synchronized (ConnectivityService.this) {
2708 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2709 mNetTransitionWakeLock.isHeld()) {
2710 mNetTransitionWakeLock.release();
2711 causedBy = mNetTransitionWakeLockCausedBy;
2712 }
2713 }
2714 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002715 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002716 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002717 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002718 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002719 FeatureUser u = (FeatureUser)msg.obj;
2720 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002721 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002722 case EVENT_INET_CONDITION_CHANGE:
2723 {
2724 int netType = msg.arg1;
2725 int condition = msg.arg2;
2726 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002727 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002728 }
2729 case EVENT_INET_CONDITION_HOLD_END:
2730 {
2731 int netType = msg.arg1;
2732 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002733 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002734 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002735 }
2736 case EVENT_SET_NETWORK_PREFERENCE:
2737 {
2738 int preference = msg.arg1;
2739 handleSetNetworkPreference(preference);
2740 break;
2741 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002742 case EVENT_SET_MOBILE_DATA:
2743 {
2744 boolean enabled = (msg.arg1 == ENABLED);
2745 handleSetMobileData(enabled);
2746 break;
2747 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002748 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2749 {
2750 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002751 break;
2752 }
2753 case EVENT_SET_DEPENDENCY_MET:
2754 {
2755 boolean met = (msg.arg1 == ENABLED);
2756 handleSetDependencyMet(msg.arg2, met);
2757 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002758 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002759 case EVENT_RESTORE_DNS:
2760 {
2761 if (mActiveDefaultNetwork != -1) {
2762 handleDnsConfigurationChange(mActiveDefaultNetwork);
2763 }
2764 break;
2765 }
Wink Saville628b0852011-08-04 15:01:58 -07002766 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2767 {
2768 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002769 sendStickyBroadcast(intent);
2770 break;
2771 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002772 case EVENT_SET_POLICY_DATA_ENABLE: {
2773 final int networkType = msg.arg1;
2774 final boolean enabled = msg.arg2 == ENABLED;
2775 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002776 break;
2777 }
2778 case EVENT_VPN_STATE_CHANGED: {
2779 if (mLockdownTracker != null) {
2780 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2781 }
2782 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 }
2785 }
2786 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002787
2788 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002789 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002790 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002791
2792 if (isTetheringSupported()) {
2793 return mTethering.tether(iface);
2794 } else {
2795 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2796 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002797 }
2798
2799 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002800 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002801 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002802
2803 if (isTetheringSupported()) {
2804 return mTethering.untether(iface);
2805 } else {
2806 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2807 }
2808 }
2809
2810 // javadoc from interface
2811 public int getLastTetherError(String iface) {
2812 enforceTetherAccessPermission();
2813
2814 if (isTetheringSupported()) {
2815 return mTethering.getLastTetherError(iface);
2816 } else {
2817 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2818 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002819 }
2820
2821 // TODO - proper iface API for selection by property, inspection, etc
2822 public String[] getTetherableUsbRegexs() {
2823 enforceTetherAccessPermission();
2824 if (isTetheringSupported()) {
2825 return mTethering.getTetherableUsbRegexs();
2826 } else {
2827 return new String[0];
2828 }
2829 }
2830
2831 public String[] getTetherableWifiRegexs() {
2832 enforceTetherAccessPermission();
2833 if (isTetheringSupported()) {
2834 return mTethering.getTetherableWifiRegexs();
2835 } else {
2836 return new String[0];
2837 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002838 }
2839
Danica Chang6fdd0c62010-08-11 14:54:43 -07002840 public String[] getTetherableBluetoothRegexs() {
2841 enforceTetherAccessPermission();
2842 if (isTetheringSupported()) {
2843 return mTethering.getTetherableBluetoothRegexs();
2844 } else {
2845 return new String[0];
2846 }
2847 }
2848
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002849 public int setUsbTethering(boolean enable) {
2850 enforceTetherAccessPermission();
2851 if (isTetheringSupported()) {
2852 return mTethering.setUsbTethering(enable);
2853 } else {
2854 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2855 }
2856 }
2857
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002858 // TODO - move iface listing, queries, etc to new module
2859 // javadoc from interface
2860 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002861 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002862 return mTethering.getTetherableIfaces();
2863 }
2864
2865 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002866 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002867 return mTethering.getTetheredIfaces();
2868 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002869
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002870 @Override
2871 public String[] getTetheredIfacePairs() {
2872 enforceTetherAccessPermission();
2873 return mTethering.getTetheredIfacePairs();
2874 }
2875
Robert Greenwalt5a735062010-03-02 17:25:02 -08002876 public String[] getTetheringErroredIfaces() {
2877 enforceTetherAccessPermission();
2878 return mTethering.getErroredIfaces();
2879 }
2880
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002881 // if ro.tether.denied = true we default to no tethering
2882 // gservices could set the secure setting to 1 though to enable it on a build where it
2883 // had previously been turned off.
2884 public boolean isTetheringSupported() {
2885 enforceTetherAccessPermission();
2886 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002887 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2888 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002889 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002890 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002891
2892 // An API NetworkStateTrackers can call when they lose their network.
2893 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2894 // whichever happens first. The timer is started by the first caller and not
2895 // restarted by subsequent callers.
2896 public void requestNetworkTransitionWakelock(String forWhom) {
2897 enforceConnectivityInternalPermission();
2898 synchronized (this) {
2899 if (mNetTransitionWakeLock.isHeld()) return;
2900 mNetTransitionWakeLockSerialNumber++;
2901 mNetTransitionWakeLock.acquire();
2902 mNetTransitionWakeLockCausedBy = forWhom;
2903 }
2904 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002905 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002906 mNetTransitionWakeLockSerialNumber, 0),
2907 mNetTransitionWakeLockTimeout);
2908 return;
2909 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002910
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002911 // 100 percent is full good, 0 is full bad.
2912 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002913 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002914 mContext.enforceCallingOrSelfPermission(
2915 android.Manifest.permission.STATUS_BAR,
2916 "ConnectivityService");
2917
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002918 if (DBG) {
2919 int pid = getCallingPid();
2920 int uid = getCallingUid();
2921 String s = pid + "(" + uid + ") reports inet is " +
2922 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2923 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2924 mInetLog.add(s);
2925 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2926 mInetLog.remove(0);
2927 }
2928 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002929 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002930 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2931 }
2932
2933 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002934 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002935 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002936 return;
2937 }
2938 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002939 if (DBG) log("handleInetConditionChange: net=" + netType +
2940 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002941 return;
2942 }
Wink Savillec9acde92011-09-21 11:05:43 -07002943 if (VDBG) {
2944 log("handleInetConditionChange: net=" +
2945 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00002946 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07002947 }
Wink Saville5b7573e2013-01-31 00:30:13 +00002948 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002949 int delay;
2950 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002951 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002952 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00002953 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002954 delay = Settings.Global.getInt(mContext.getContentResolver(),
2955 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002956 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002957 delay = Settings.Global.getInt(mContext.getContentResolver(),
2958 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002959 }
2960 mInetConditionChangeInFlight = true;
2961 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00002962 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002963 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002964 // we've set the new condition, when this hold ends that will get picked up
2965 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002966 }
2967 }
2968
Wink Saville5b7573e2013-01-31 00:30:13 +00002969 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002970 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00002971 log("handleInetConditionHoldEnd: net=" + netType +
2972 ", condition=" + mDefaultInetCondition +
2973 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002974 }
2975 mInetConditionChangeInFlight = false;
2976
2977 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002978 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002979 return;
2980 }
2981 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002982 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002983 return;
2984 }
Wink Saville5b7573e2013-01-31 00:30:13 +00002985 // TODO: Figure out why this optimization sometimes causes a
2986 // change in mDefaultInetCondition to be missed and the
2987 // UI to not be updated.
2988 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2989 // if (DBG) log("no change in condition - aborting");
2990 // return;
2991 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002992 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2993 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002994 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002995 return;
2996 }
Wink Saville5b7573e2013-01-31 00:30:13 +00002997 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002998 sendInetConditionBroadcast(networkInfo);
2999 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003000 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003001
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003002 public ProxyProperties getProxy() {
3003 synchronized (mDefaultProxyLock) {
3004 return mDefaultProxyDisabled ? null : mDefaultProxy;
3005 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003006 }
3007
3008 public void setGlobalProxy(ProxyProperties proxyProperties) {
3009 enforceChangePermission();
3010 synchronized (mGlobalProxyLock) {
3011 if (proxyProperties == mGlobalProxy) return;
3012 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3013 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3014
3015 String host = "";
3016 int port = 0;
3017 String exclList = "";
3018 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3019 mGlobalProxy = new ProxyProperties(proxyProperties);
3020 host = mGlobalProxy.getHost();
3021 port = mGlobalProxy.getPort();
3022 exclList = mGlobalProxy.getExclusionList();
3023 } else {
3024 mGlobalProxy = null;
3025 }
3026 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003027 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3028 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3029 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07003030 exclList);
3031 }
3032
3033 if (mGlobalProxy == null) {
3034 proxyProperties = mDefaultProxy;
3035 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07003036 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003037 }
3038
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003039 private void loadGlobalProxy() {
3040 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003041 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3042 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3043 String exclList = Settings.Global.getString(res,
3044 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003045 if (!TextUtils.isEmpty(host)) {
3046 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3047 synchronized (mGlobalProxyLock) {
3048 mGlobalProxy = proxyProperties;
3049 }
3050 }
3051 }
3052
Robert Greenwalt434203a2010-10-11 16:00:27 -07003053 public ProxyProperties getGlobalProxy() {
3054 synchronized (mGlobalProxyLock) {
3055 return mGlobalProxy;
3056 }
3057 }
3058
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003059 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3060 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3061 proxy = null;
3062 }
3063 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003064 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3065 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003066 mDefaultProxy = proxy;
3067
3068 if (!mDefaultProxyDisabled) {
3069 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003070 }
3071 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003072 }
3073
3074 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003075 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3076 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003077 if (!TextUtils.isEmpty(proxy)) {
3078 String data[] = proxy.split(":");
3079 String proxyHost = data[0];
3080 int proxyPort = 8080;
3081 if (data.length > 1) {
3082 try {
3083 proxyPort = Integer.parseInt(data[1]);
3084 } catch (NumberFormatException e) {
3085 return;
3086 }
3087 }
3088 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3089 setGlobalProxy(p);
3090 }
3091 }
3092
3093 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003094 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003095 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003096 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003097 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3098 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003099 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003100 final long ident = Binder.clearCallingIdentity();
3101 try {
3102 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3103 } finally {
3104 Binder.restoreCallingIdentity(ident);
3105 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003106 }
3107
3108 private static class SettingsObserver extends ContentObserver {
3109 private int mWhat;
3110 private Handler mHandler;
3111 SettingsObserver(Handler handler, int what) {
3112 super(handler);
3113 mHandler = handler;
3114 mWhat = what;
3115 }
3116
3117 void observe(Context context) {
3118 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003119 resolver.registerContentObserver(Settings.Global.getUriFor(
3120 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003121 }
3122
3123 @Override
3124 public void onChange(boolean selfChange) {
3125 mHandler.obtainMessage(mWhat).sendToTarget();
3126 }
3127 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003128
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003129 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003130 Slog.d(TAG, s);
3131 }
3132
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003133 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003134 Slog.e(TAG, s);
3135 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003136
repo syncaea743a2011-07-29 23:55:49 -07003137 int convertFeatureToNetworkType(int networkType, String feature) {
3138 int usedNetworkType = networkType;
3139
3140 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3141 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3142 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3143 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3144 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3145 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3146 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3147 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3148 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3149 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3150 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3151 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3152 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3153 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3154 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3155 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3156 } else {
3157 Slog.e(TAG, "Can't match any mobile netTracker!");
3158 }
3159 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3160 if (TextUtils.equals(feature, "p2p")) {
3161 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3162 } else {
3163 Slog.e(TAG, "Can't match any wifi netTracker!");
3164 }
3165 } else {
3166 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003167 }
repo syncaea743a2011-07-29 23:55:49 -07003168 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003169 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003170
3171 private static <T> T checkNotNull(T value, String message) {
3172 if (value == null) {
3173 throw new NullPointerException(message);
3174 }
3175 return value;
3176 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003177
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003178 /**
3179 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003180 * VpnBuilder and not available in ConnectivityManager. Permissions
3181 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003182 * @hide
3183 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003184 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003185 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003186 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003187 try {
3188 int type = mActiveDefaultNetwork;
3189 if (ConnectivityManager.isNetworkTypeValid(type)) {
3190 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3191 return true;
3192 }
3193 } catch (Exception e) {
3194 // ignore
3195 } finally {
3196 try {
3197 socket.close();
3198 } catch (Exception e) {
3199 // ignore
3200 }
3201 }
3202 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003203 }
3204
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003205 /**
3206 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003207 * and not available in ConnectivityManager. Permissions are checked
3208 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003209 * @hide
3210 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003211 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003212 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003213 throwIfLockdownEnabled();
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003214 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003215 }
3216
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003217 /**
3218 * Configure a TUN interface and return its file descriptor. Parameters
3219 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003220 * and not available in ConnectivityManager. Permissions are checked in
3221 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003222 * @hide
3223 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003224 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003225 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003226 throwIfLockdownEnabled();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003227 return mVpn.establish(config);
3228 }
3229
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003230 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003231 * Start legacy VPN, controlling native daemons as needed. Creates a
3232 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003233 */
3234 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003235 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003236 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003237 final LinkProperties egress = getActiveLinkProperties();
3238 if (egress == null) {
3239 throw new IllegalStateException("Missing active network connection");
3240 }
3241 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003242 }
3243
3244 /**
3245 * Return the information of the ongoing legacy VPN. This method is used
3246 * by VpnSettings and not available in ConnectivityManager. Permissions
3247 * are checked in Vpn class.
3248 * @hide
3249 */
3250 @Override
3251 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003252 throwIfLockdownEnabled();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003253 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003254 }
3255
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003256 /**
3257 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3258 * through NetworkStateTracker since it works differently. For example, it
3259 * needs to override DNS servers but never takes the default routes. It
3260 * relies on another data network, and it could keep existing connections
3261 * alive after reconnecting, switching between networks, or even resuming
3262 * from deep sleep. Calls from applications should be done synchronously
3263 * to avoid race conditions. As these are all hidden APIs, refactoring can
3264 * be done whenever a better abstraction is developed.
3265 */
3266 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003267 private VpnCallback() {
3268 }
3269
Jeff Sharkey899223b2012-08-04 15:24:58 -07003270 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003271 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003272 }
3273
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003274 public void override(List<String> dnsServers, List<String> searchDomains) {
3275 if (dnsServers == null) {
3276 restore();
3277 return;
3278 }
3279
3280 // Convert DNS servers into addresses.
3281 List<InetAddress> addresses = new ArrayList<InetAddress>();
3282 for (String address : dnsServers) {
3283 // Double check the addresses and remove invalid ones.
3284 try {
3285 addresses.add(InetAddress.parseNumericAddress(address));
3286 } catch (Exception e) {
3287 // ignore
3288 }
3289 }
3290 if (addresses.isEmpty()) {
3291 restore();
3292 return;
3293 }
3294
3295 // Concatenate search domains into a string.
3296 StringBuilder buffer = new StringBuilder();
3297 if (searchDomains != null) {
3298 for (String domain : searchDomains) {
3299 buffer.append(domain).append(' ');
3300 }
3301 }
3302 String domains = buffer.toString().trim();
3303
3304 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003305 synchronized (mDnsLock) {
Mattias Falk8b47b362011-08-23 14:15:13 +02003306 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003307 mDnsOverridden = true;
3308 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003309
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003310 // Temporarily disable the default proxy.
3311 synchronized (mDefaultProxyLock) {
3312 mDefaultProxyDisabled = true;
3313 if (mDefaultProxy != null) {
3314 sendProxyBroadcast(null);
3315 }
3316 }
3317
3318 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003319 }
3320
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003321 public void restore() {
3322 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003323 if (mDnsOverridden) {
3324 mDnsOverridden = false;
3325 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003326 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003327 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003328 synchronized (mDefaultProxyLock) {
3329 mDefaultProxyDisabled = false;
3330 if (mDefaultProxy != null) {
3331 sendProxyBroadcast(mDefaultProxy);
3332 }
3333 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003334 }
3335 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003336
3337 @Override
3338 public boolean updateLockdownVpn() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07003339 enforceSystemUid();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003340
3341 // Tear down existing lockdown if profile was removed
3342 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3343 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003344 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003345 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3346 return false;
3347 }
3348
3349 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3350 final VpnProfile profile = VpnProfile.decode(
3351 profileName, mKeyStore.get(Credentials.VPN + profileName));
3352 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3353 } else {
3354 setLockdownTracker(null);
3355 }
3356
3357 return true;
3358 }
3359
3360 /**
3361 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3362 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3363 */
3364 private void setLockdownTracker(LockdownVpnTracker tracker) {
3365 // Shutdown any existing tracker
3366 final LockdownVpnTracker existing = mLockdownTracker;
3367 mLockdownTracker = null;
3368 if (existing != null) {
3369 existing.shutdown();
3370 }
3371
3372 try {
3373 if (tracker != null) {
3374 mNetd.setFirewallEnabled(true);
3375 mLockdownTracker = tracker;
3376 mLockdownTracker.init();
3377 } else {
3378 mNetd.setFirewallEnabled(false);
3379 }
3380 } catch (RemoteException e) {
3381 // ignored; NMS lives inside system_server
3382 }
3383 }
3384
3385 private void throwIfLockdownEnabled() {
3386 if (mLockdownEnabled) {
3387 throw new IllegalStateException("Unavailable in lockdown mode");
3388 }
3389 }
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07003390
3391 private static void enforceSystemUid() {
3392 final int uid = Binder.getCallingUid();
3393 if (uid != Process.SYSTEM_UID) {
3394 throw new SecurityException("Only available to AID_SYSTEM");
3395 }
3396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397}