blob: 54bcdcbb27d2d0ed6d079aa11c21135d1629814d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Wink Savilleab9321d2013-06-29 21:10:57 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080037import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090041import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070048import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080050import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080051import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070057import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080058import android.net.LinkProperties;
Wink Savilleab9321d2013-06-29 21:10:57 -070059import android.net.Uri;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Wink Savilleab9321d2013-06-29 21:10:57 -070065import android.net.NetworkInfo.State;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070069import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070070import android.net.Proxy;
71import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070072import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090074import android.net.wimax.WimaxManagerConstants;
Wink Savilleab9321d2013-06-29 21:10:57 -070075import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040077import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070079import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070080import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070081import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Looper;
83import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070084import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070085import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070086import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070087import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.RemoteException;
Wink Savilleab9321d2013-06-29 21:10:57 -070089import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070091import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070093import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700100import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700101import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Wink Savilleab9321d2013-06-29 21:10:57 -0700103import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700104import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700105import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700106import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700107import com.android.internal.telephony.DctConstants;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700108import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -0700109import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700110import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700111import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700112import com.android.server.am.BatteryStatsService;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900113import com.android.server.connectivity.Nat464Xlat;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800114import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700115import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700116import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700117import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700118import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700119import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700120
tk.mun148c7d02011-10-13 22:51:57 +0900121import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900132import java.lang.reflect.Constructor;
Wink Savilleab9321d2013-06-29 21:10:57 -0700133import java.net.HttpURLConnection;
Wink Savillec9822c52011-07-14 12:23:28 -0700134import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700135import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700136import java.net.InetAddress;
Wink Savilleab9321d2013-06-29 21:10:57 -0700137import java.net.URL;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700138import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700140import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700141import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700142import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700143import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700144import java.util.List;
Wink Savilleab9321d2013-06-29 21:10:57 -0700145import java.util.Random;
146import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
148/**
149 * @hide
150 */
151public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700152 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Robert Greenwaltba175a52010-10-05 19:12:26 -0700154 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700155 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700157 private static final boolean LOGD_RULES = false;
158
Jeff Sharkey899223b2012-08-04 15:24:58 -0700159 // TODO: create better separation between radio types and network types
160
Robert Greenwalt42acef32009-08-12 16:08:25 -0700161 // how long to wait before switching back to a radio's default network
162 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
163 // system property that can override the above value
164 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
165 "android.telephony.apn-restore";
166
Wink Savilleab9321d2013-06-29 21:10:57 -0700167 // Default value if FAIL_FAST_TIME_MS is not set
168 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
169 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
170 private static final String FAIL_FAST_TIME_MS =
171 "persist.radio.fail_fast_time_ms";
172
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700173 // used in recursive route setting to add gateways for the host for which
174 // a host route was requested.
175 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
176
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800177 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800178 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800179
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700180 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700181
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700182 private Vpn mVpn;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700183 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700184
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700185 private boolean mLockdownEnabled;
186 private LockdownVpnTracker mLockdownTracker;
187
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900188 private Nat464Xlat mClat;
189
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
191 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192 /** Currently active network rules by UID. */
193 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Set of ifaces that are costly. */
195 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 /**
198 * Sometimes we want to refer to the individual network state
199 * trackers separately, and sometimes we just want to treat them
200 * abstractly.
201 */
202 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700203
Irfan Sheriffda6da092012-08-16 12:49:23 -0700204 /* Handles captive portal check on a network */
205 private CaptivePortalTracker mCaptivePortalTracker;
206
Robert Greenwalt42acef32009-08-12 16:08:25 -0700207 /**
Wink Savillee8222252011-07-13 13:44:13 -0700208 * The link properties that define the current links
209 */
210 private LinkProperties mCurrentLinkProperties[];
211
212 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213 * A per Net list of the PID's that requested access to the net
214 * used both as a refcount and for per-PID DNS selection
215 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200216 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700217
Robert Greenwalt42acef32009-08-12 16:08:25 -0700218 // priority order of the nettrackers
219 // (excluding dynamically set mNetworkPreference)
220 // TODO - move mNetworkTypePreference into this
221 private int[] mPriorityList;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private Context mContext;
224 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700225 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700226 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000227 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700228 private int mDefaultInetConditionPublished = 0;
229 private boolean mInetConditionChangeInFlight = false;
230 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700232 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800233 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700234 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700237 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700239 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700240 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700241
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 private static final int ENABLED = 1;
243 private static final int DISABLED = 0;
244
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700245 private static final boolean ADD = true;
246 private static final boolean REMOVE = false;
247
248 private static final boolean TO_DEFAULT_TABLE = true;
249 private static final boolean TO_SECONDARY_TABLE = false;
250
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700251 /**
252 * used internally as a delayed event to make us switch back to the
253 * default network
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256
257 /**
258 * used internally to change our mobile data enabled flag
259 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700260 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700261
262 /**
263 * used internally to change our network preference setting
264 * arg1 = networkType to prefer
265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267
268 /**
269 * used internally to synchronize inet condition reports
270 * arg1 = networkType
271 * arg2 = condition (0 bad, 100 good)
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274
275 /**
276 * used internally to mark the end of inet condition hold periods
277 * arg1 = networkType
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700280
281 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700282 * used internally to set enable/disable cellular data
283 * arg1 = ENBALED or DISABLED
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700286
Robert Greenwaltf3331232010-09-24 14:32:21 -0700287 /**
288 * used internally to clear a wakelock when transitioning
289 * from one net to another
290 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700291 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700292
Robert Greenwalt434203a2010-10-11 16:00:27 -0700293 /**
294 * used internally to reload global proxy settings
295 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700296 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700297
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700298 /**
299 * used internally to set external dependency met/unmet
300 * arg1 = ENABLED (met) or DISABLED (unmet)
301 * arg2 = NetworkType
302 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700303 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700304
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700305 /**
306 * used internally to restore DNS properties back to the
307 * default network
308 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700309 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700310
Wink Saville2b30afd2011-08-05 11:40:22 -0700311 /**
Wink Saville628b0852011-08-04 15:01:58 -0700312 * used internally to send a sticky broadcast delayed.
313 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700314 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700315
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700316 /**
317 * Used internally to
318 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
319 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700320 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700322 private static final int EVENT_VPN_STATE_CHANGED = 14;
323
Wink Savilleab9321d2013-06-29 21:10:57 -0700324 /**
325 * Used internally to disable fail fast of mobile data
326 */
327 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
328
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700329 /** Handler used for internal events. */
330 private InternalHandler mHandler;
331 /** Handler used for incoming {@link NetworkStateTracker} events. */
332 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700333
334 // list of DeathRecipients used to make sure features are turned off when
335 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500336 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700337
Mike Lockwood0f79b542009-08-14 14:18:49 -0400338 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800339 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400340
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700341 private PowerManager.WakeLock mNetTransitionWakeLock;
342 private String mNetTransitionWakeLockCausedBy = "";
343 private int mNetTransitionWakeLockSerialNumber;
344 private int mNetTransitionWakeLockTimeout;
345
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700346 private InetAddress mDefaultDns;
347
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700348 // this collection is used to refcount the added routes - if there are none left
349 // it's time to remove the route from the route table
350 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
351
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700352 // used in DBG mode to track inet condition reports
353 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
354 private ArrayList mInetLog;
355
Robert Greenwalt434203a2010-10-11 16:00:27 -0700356 // track the current default http proxy - tell the world if we get a new one (real change)
357 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700358 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700359 private boolean mDefaultProxyDisabled = false;
360
Robert Greenwalt434203a2010-10-11 16:00:27 -0700361 // track the global proxy.
362 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700363
364 private SettingsObserver mSettingsObserver;
365
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700366 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700367 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700368
Robert Greenwalt511288a2009-12-07 11:33:18 -0800369 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700370 public int mSimultaneity;
371 public int mType;
372 public RadioAttributes(String init) {
373 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700374 mType = Integer.parseInt(fragments[0]);
375 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700376 }
377 }
378 RadioAttributes[] mRadioAttributes;
379
Robert Greenwalt50393202011-06-21 17:26:14 -0700380 // the set of network types that can only be enabled by system/sig apps
381 List mProtectedNetworks;
382
Wink Savilleab9321d2013-06-29 21:10:57 -0700383 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
384
385 TelephonyManager mTelephonyManager;
386
Wink Savillefde1ac92013-07-16 17:16:37 -0700387 // We only want one checkMobileProvisioning after booting.
388 volatile boolean mFirstProvisioningCheckStarted = false;
389
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700390 public ConnectivityService(Context context, INetworkManagementService netd,
391 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700392 // Currently, omitting a NetworkFactory will create one internally
393 // TODO: create here when we have cleaner WiMAX support
394 this(context, netd, statsService, policyManager, null);
395 }
396
Jeff Sharkey899223b2012-08-04 15:24:58 -0700397 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700398 INetworkStatsService statsService, INetworkPolicyManager policyManager,
399 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800400 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800401
Wink Savillebb08caf2010-09-02 19:23:52 -0700402 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
403 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 mHandler = new InternalHandler(handlerThread.getLooper());
405 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700406
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700407 if (netFactory == null) {
408 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
409 }
410
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800411 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800412 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
413 String id = Settings.Secure.getString(context.getContentResolver(),
414 Settings.Secure.ANDROID_ID);
415 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700416 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800417 SystemProperties.set("net.hostname", name);
418 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800419 }
420
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700421 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700422 String dns = Settings.Global.getString(context.getContentResolver(),
423 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700424 if (dns == null || dns.length() == 0) {
425 dns = context.getResources().getString(
426 com.android.internal.R.string.config_default_dns_server);
427 }
428 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800429 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
430 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800431 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700432 }
433
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700434 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700435 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700436 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700437 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700438 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700439
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700440 try {
441 mPolicyManager.registerListener(mPolicyListener);
442 } catch (RemoteException e) {
443 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700444 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700445 }
446
447 final PowerManager powerManager = (PowerManager) context.getSystemService(
448 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700449 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
450 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
451 com.android.internal.R.integer.config_networkTransitionTimeout);
452
Robert Greenwalt42acef32009-08-12 16:08:25 -0700453 mNetTrackers = new NetworkStateTracker[
454 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700455 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700456
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700457 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700458 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700459
Robert Greenwalt42acef32009-08-12 16:08:25 -0700460 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700461 String[] raStrings = context.getResources().getStringArray(
462 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700463 for (String raString : raStrings) {
464 RadioAttributes r = new RadioAttributes(raString);
465 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800466 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700467 continue;
468 }
469 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800470 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700471 r.mType);
472 continue;
473 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700474 mRadioAttributes[r.mType] = r;
475 }
476
Wink Saville51f456f2013-04-23 14:26:51 -0700477 // TODO: What is the "correct" way to do determine if this is a wifi only device?
478 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
479 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700480 String[] naStrings = context.getResources().getStringArray(
481 com.android.internal.R.array.networkAttributes);
482 for (String naString : naStrings) {
483 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700484 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700485 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800486 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700487 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700488 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700489 }
Wink Saville51f456f2013-04-23 14:26:51 -0700490 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
491 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
492 n.type);
493 continue;
494 }
Wink Saville975c8482011-04-07 14:23:45 -0700495 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800496 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700497 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700498 continue;
499 }
Wink Saville975c8482011-04-07 14:23:45 -0700500 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800501 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700502 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700503 continue;
504 }
Wink Saville975c8482011-04-07 14:23:45 -0700505 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700506 mNetworksDefined++;
507 } catch(Exception e) {
508 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700509 }
510 }
511
Robert Greenwalt50393202011-06-21 17:26:14 -0700512 mProtectedNetworks = new ArrayList<Integer>();
513 int[] protectedNetworks = context.getResources().getIntArray(
514 com.android.internal.R.array.config_protectedNetworks);
515 for (int p : protectedNetworks) {
516 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
517 mProtectedNetworks.add(p);
518 } else {
519 if (DBG) loge("Ignoring protectedNetwork " + p);
520 }
521 }
522
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700523 // high priority first
524 mPriorityList = new int[mNetworksDefined];
525 {
526 int insertionPoint = mNetworksDefined-1;
527 int currentLowest = 0;
528 int nextLowest = 0;
529 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700530 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700531 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700532 if (na.priority < currentLowest) continue;
533 if (na.priority > currentLowest) {
534 if (na.priority < nextLowest || nextLowest == 0) {
535 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700536 }
537 continue;
538 }
Wink Saville975c8482011-04-07 14:23:45 -0700539 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700540 }
541 currentLowest = nextLowest;
542 nextLowest = 0;
543 }
544 }
545
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800546 // Update mNetworkPreference according to user mannually first then overlay config.xml
547 mNetworkPreference = getPersistedNetworkPreference();
548 if (mNetworkPreference == -1) {
549 for (int n : mPriorityList) {
550 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
551 mNetworkPreference = n;
552 break;
553 }
554 }
555 if (mNetworkPreference == -1) {
556 throw new IllegalStateException(
557 "You should set at least one default Network in config.xml!");
558 }
559 }
560
Mattias Falk8b47b362011-08-23 14:15:13 +0200561 mNetRequestersPids =
562 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700563 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200564 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700565 }
566
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500567 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700568
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700569 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
570 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700571
572 // Create and start trackers for hard-coded networks
573 for (int targetNetworkType : mPriorityList) {
574 final NetworkConfig config = mNetConfigs[targetNetworkType];
575 final NetworkStateTracker tracker;
576 try {
577 tracker = netFactory.createTracker(targetNetworkType, config);
578 mNetTrackers[targetNetworkType] = tracker;
579 } catch (IllegalArgumentException e) {
580 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
581 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700582 continue;
583 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700584
585 tracker.startMonitoring(context, mTrackerHandler);
586 if (config.isDefault()) {
587 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800588 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700589 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800590
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700591 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700592 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700593 mTethering.getTetherableWifiRegexs().length != 0 ||
594 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700595 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800596
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700597 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700598 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700599
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900600 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
601
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700602 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700603 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700604 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900605 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700606 } catch (RemoteException e) {
607 loge("Error registering observer :" + e);
608 }
609
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700610 if (DBG) {
611 mInetLog = new ArrayList();
612 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700613
614 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
615 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800616
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700617 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800618 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700620
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700621 /**
622 * Factory that creates {@link NetworkStateTracker} instances using given
623 * {@link NetworkConfig}.
624 */
625 public interface NetworkFactory {
626 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
627 }
628
629 private static class DefaultNetworkFactory implements NetworkFactory {
630 private final Context mContext;
631 private final Handler mTrackerHandler;
632
633 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
634 mContext = context;
635 mTrackerHandler = trackerHandler;
636 }
637
638 @Override
639 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
640 switch (config.radio) {
641 case TYPE_WIFI:
642 return new WifiStateTracker(targetNetworkType, config.name);
643 case TYPE_MOBILE:
644 return new MobileDataStateTracker(targetNetworkType, config.name);
645 case TYPE_DUMMY:
646 return new DummyDataStateTracker(targetNetworkType, config.name);
647 case TYPE_BLUETOOTH:
648 return BluetoothTetheringDataTracker.getInstance();
649 case TYPE_WIMAX:
650 return makeWimaxStateTracker(mContext, mTrackerHandler);
651 case TYPE_ETHERNET:
652 return EthernetDataTracker.getInstance();
653 default:
654 throw new IllegalArgumentException(
655 "Trying to create a NetworkStateTracker for an unknown radio type: "
656 + config.radio);
657 }
658 }
659 }
660
661 /**
662 * Loads external WiMAX library and registers as system service, returning a
663 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
664 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
665 */
666 private static NetworkStateTracker makeWimaxStateTracker(
667 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700668 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900669 DexClassLoader wimaxClassLoader;
670 Class wimaxStateTrackerClass = null;
671 Class wimaxServiceClass = null;
672 Class wimaxManagerClass;
673 String wimaxJarLocation;
674 String wimaxLibLocation;
675 String wimaxManagerClassName;
676 String wimaxServiceClassName;
677 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678
tk.mun148c7d02011-10-13 22:51:57 +0900679 NetworkStateTracker wimaxStateTracker = null;
680
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700681 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900682 com.android.internal.R.bool.config_wimaxEnabled);
683
684 if (isWimaxEnabled) {
685 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700686 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900687 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700688 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900689 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700690 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900691 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700692 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900693 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700694 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900695 com.android.internal.R.string.config_wimaxStateTrackerClassname);
696
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800697 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900698 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700699 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900700 wimaxLibLocation, ClassLoader.getSystemClassLoader());
701
702 try {
703 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
704 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
705 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
706 } catch (ClassNotFoundException ex) {
707 loge("Exception finding Wimax classes: " + ex.toString());
708 return null;
709 }
710 } catch(Resources.NotFoundException ex) {
711 loge("Wimax Resources does not exist!!! ");
712 return null;
713 }
714
715 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800716 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900717
718 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
719 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700720 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
721 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900722
723 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
724 (new Class[] {Context.class, wimaxStateTrackerClass});
725 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700726 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900727 wmxSrvConst.setAccessible(false);
728
729 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
730
731 } catch(Exception ex) {
732 loge("Exception creating Wimax classes: " + ex.toString());
733 return null;
734 }
735 } else {
736 loge("Wimax is not enabled or not added to the network attributes!!! ");
737 return null;
738 }
739
740 return wimaxStateTracker;
741 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700744 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 * @param preference the new preference
746 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700747 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700749
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700750 mHandler.sendMessage(
751 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
753
754 public int getNetworkPreference() {
755 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700756 int preference;
757 synchronized(this) {
758 preference = mNetworkPreference;
759 }
760 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700763 private void handleSetNetworkPreference(int preference) {
764 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700765 mNetConfigs[preference] != null &&
766 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700767 if (mNetworkPreference != preference) {
768 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700769 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700770 synchronized(this) {
771 mNetworkPreference = preference;
772 }
773 enforcePreference();
774 }
775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700777
Wink Saville628b0852011-08-04 15:01:58 -0700778 private int getConnectivityChangeDelay() {
779 final ContentResolver cr = mContext.getContentResolver();
780
781 /** Check system properties for the default value then use secure settings value, if any. */
782 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700783 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
784 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
785 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700786 defaultDelay);
787 }
788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 private int getPersistedNetworkPreference() {
790 final ContentResolver cr = mContext.getContentResolver();
791
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700792 final int networkPrefSetting = Settings.Global
793 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800795 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700799 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 * In this method, we only tear down a non-preferred network. Establishing
801 * a connection to the preferred network is taken care of when we handle
802 * the disconnect event from the non-preferred network
803 * (see {@link #handleDisconnect(NetworkInfo)}).
804 */
805 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700806 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 return;
808
Robert Greenwalt42acef32009-08-12 16:08:25 -0700809 if (!mNetTrackers[mNetworkPreference].isAvailable())
810 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811
Robert Greenwalt42acef32009-08-12 16:08:25 -0700812 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700813 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700814 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700815 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800816 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700817 " in enforcePreference");
818 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700819 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 }
821 }
822 }
823
824 private boolean teardown(NetworkStateTracker netTracker) {
825 if (netTracker.teardown()) {
826 netTracker.setTeardownRequested(true);
827 return true;
828 } else {
829 return false;
830 }
831 }
832
833 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700834 * Check if UID should be blocked from using the network represented by the
835 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700836 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700837 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
838 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700839
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700840 final boolean networkCostly;
841 final int uidRules;
842 synchronized (mRulesLock) {
843 networkCostly = mMeteredIfaces.contains(iface);
844 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700845 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700846
847 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
848 return true;
849 }
850
851 // no restrictive rules; network is visible
852 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700853 }
854
855 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700856 * Return a filtered {@link NetworkInfo}, potentially marked
857 * {@link DetailedState#BLOCKED} based on
858 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700859 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700860 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
861 NetworkInfo info = tracker.getNetworkInfo();
862 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700863 // network is blocked; clone and override state
864 info = new NetworkInfo(info);
865 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700866 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700867 if (mLockdownTracker != null) {
868 info = mLockdownTracker.augmentNetworkInfo(info);
869 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700870 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700871 }
872
873 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 * Return NetworkInfo for the active (i.e., connected) network interface.
875 * It is assumed that at most one network is active at a time. If more
876 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700877 * @return the info for the active network, or {@code null} if none is
878 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700880 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700882 enforceAccessPermission();
883 final int uid = Binder.getCallingUid();
884 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700887 public NetworkInfo getActiveNetworkInfoUnfiltered() {
888 enforceAccessPermission();
889 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
890 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
891 if (tracker != null) {
892 return tracker.getNetworkInfo();
893 }
894 }
895 return null;
896 }
897
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700898 @Override
899 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
900 enforceConnectivityInternalPermission();
901 return getNetworkInfo(mActiveDefaultNetwork, uid);
902 }
903
904 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 public NetworkInfo getNetworkInfo(int networkType) {
906 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700907 final int uid = Binder.getCallingUid();
908 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 }
910
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700911 private NetworkInfo getNetworkInfo(int networkType, int uid) {
912 NetworkInfo info = null;
913 if (isNetworkTypeValid(networkType)) {
914 final NetworkStateTracker tracker = mNetTrackers[networkType];
915 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700916 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700917 }
918 }
919 return info;
920 }
921
922 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 public NetworkInfo[] getAllNetworkInfo() {
924 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700925 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700926 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700927 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700928 for (NetworkStateTracker tracker : mNetTrackers) {
929 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 }
932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700934 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700937 @Override
938 public boolean isNetworkSupported(int networkType) {
939 enforceAccessPermission();
940 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
941 }
942
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700943 /**
944 * Return LinkProperties for the active (i.e., connected) default
945 * network interface. It is assumed that at most one default network
946 * is active at a time. If more than one is active, it is indeterminate
947 * which will be returned.
948 * @return the ip properties for the active network, or {@code null} if
949 * none is active
950 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700951 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700952 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700953 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700954 }
955
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700957 public LinkProperties getLinkProperties(int networkType) {
958 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700959 if (isNetworkTypeValid(networkType)) {
960 final NetworkStateTracker tracker = mNetTrackers[networkType];
961 if (tracker != null) {
962 return tracker.getLinkProperties();
963 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700964 }
965 return null;
966 }
967
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700968 @Override
969 public NetworkState[] getAllNetworkState() {
970 enforceAccessPermission();
971 final int uid = Binder.getCallingUid();
972 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700973 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700974 for (NetworkStateTracker tracker : mNetTrackers) {
975 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700976 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700977 result.add(new NetworkState(
978 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
979 }
980 }
981 }
982 return result.toArray(new NetworkState[result.size()]);
983 }
984
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700985 private NetworkState getNetworkStateUnchecked(int networkType) {
986 if (isNetworkTypeValid(networkType)) {
987 final NetworkStateTracker tracker = mNetTrackers[networkType];
988 if (tracker != null) {
989 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
990 tracker.getLinkCapabilities());
991 }
992 }
993 return null;
994 }
995
996 @Override
997 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
998 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700999
1000 final long token = Binder.clearCallingIdentity();
1001 try {
1002 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1003 if (state != null) {
1004 try {
1005 return mPolicyManager.getNetworkQuotaInfo(state);
1006 } catch (RemoteException e) {
1007 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001008 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001009 return null;
1010 } finally {
1011 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001012 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001013 }
1014
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001015 @Override
1016 public boolean isActiveNetworkMetered() {
1017 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001018 final long token = Binder.clearCallingIdentity();
1019 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001020 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001021 } finally {
1022 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001023 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001024 }
1025
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001026 private boolean isNetworkMeteredUnchecked(int networkType) {
1027 final NetworkState state = getNetworkStateUnchecked(networkType);
1028 if (state != null) {
1029 try {
1030 return mPolicyManager.isNetworkMetered(state);
1031 } catch (RemoteException e) {
1032 }
1033 }
1034 return false;
1035 }
1036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 public boolean setRadios(boolean turnOn) {
1038 boolean result = true;
1039 enforceChangePermission();
1040 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001041 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 return result;
1044 }
1045
1046 public boolean setRadio(int netType, boolean turnOn) {
1047 enforceChangePermission();
1048 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1049 return false;
1050 }
1051 NetworkStateTracker tracker = mNetTrackers[netType];
1052 return tracker != null && tracker.setRadio(turnOn);
1053 }
1054
Jeff Sharkey216c1812012-08-05 14:29:23 -07001055 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1056 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001057 public void interfaceClassDataActivityChanged(String label, boolean active) {
1058 int deviceType = Integer.parseInt(label);
1059 sendDataActivityBroadcast(deviceType, active);
1060 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001061 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001062
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001063 /**
1064 * Used to notice when the calling process dies so we can self-expire
1065 *
1066 * Also used to know if the process has cleaned up after itself when
1067 * our auto-expire timer goes off. The timer has a link to an object.
1068 *
1069 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001070 private class FeatureUser implements IBinder.DeathRecipient {
1071 int mNetworkType;
1072 String mFeature;
1073 IBinder mBinder;
1074 int mPid;
1075 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001076 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001077
1078 FeatureUser(int type, String feature, IBinder binder) {
1079 super();
1080 mNetworkType = type;
1081 mFeature = feature;
1082 mBinder = binder;
1083 mPid = getCallingPid();
1084 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001085 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001086
Robert Greenwalt42acef32009-08-12 16:08:25 -07001087 try {
1088 mBinder.linkToDeath(this, 0);
1089 } catch (RemoteException e) {
1090 binderDied();
1091 }
1092 }
1093
1094 void unlinkDeathRecipient() {
1095 mBinder.unlinkToDeath(this, 0);
1096 }
1097
1098 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001099 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001100 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1101 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001102 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001103 }
1104
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001105 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001106 if (VDBG) {
1107 log("ConnectivityService FeatureUser expire(" +
1108 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1109 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1110 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001111 stopUsingNetworkFeature(this, false);
1112 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001113
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001114 public boolean isSameUser(FeatureUser u) {
1115 if (u == null) return false;
1116
1117 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1118 }
1119
1120 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1121 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1122 TextUtils.equals(mFeature, feature)) {
1123 return true;
1124 }
1125 return false;
1126 }
1127
Robert Greenwaltb9285352009-12-21 18:24:07 -08001128 public String toString() {
1129 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1130 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1131 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001132 }
1133
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001134 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001135 public int startUsingNetworkFeature(int networkType, String feature,
1136 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001137 long startTime = 0;
1138 if (DBG) {
1139 startTime = SystemClock.elapsedRealtime();
1140 }
Wink Savillec9acde92011-09-21 11:05:43 -07001141 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001142 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1143 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001146 try {
1147 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1148 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001149 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001150 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001151
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001152 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001153
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001154 // TODO - move this into individual networktrackers
1155 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001156
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001157 if (mLockdownEnabled) {
1158 // Since carrier APNs usually aren't available from VPN
1159 // endpoint, mark them as unavailable.
1160 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1161 }
1162
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001163 if (mProtectedNetworks.contains(usedNetworkType)) {
1164 enforceConnectivityInternalPermission();
1165 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001166
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001167 // if UID is restricted, don't allow them to bring up metered APNs
1168 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1169 final int uidRules;
1170 synchronized (mRulesLock) {
1171 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1172 }
1173 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001174 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001175 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001176
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001177 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1178 if (network != null) {
1179 Integer currentPid = new Integer(getCallingPid());
1180 if (usedNetworkType != networkType) {
1181 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001182
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001183 if (ni.isAvailable() == false) {
1184 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1185 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001186 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001187 } else {
1188 // else make the attempt anyway - probably giving REQUEST_STARTED below
1189 if (DBG) {
1190 log("special network not available, but try anyway ni=" +
1191 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001192 }
1193 }
1194 }
1195
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001196 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001197
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001198 synchronized(this) {
1199 boolean addToList = true;
1200 if (restoreTimer < 0) {
1201 // In case there is no timer is specified for the feature,
1202 // make sure we don't add duplicate entry with the same request.
1203 for (FeatureUser u : mFeatureUsers) {
1204 if (u.isSameUser(f)) {
1205 // Duplicate user is found. Do not add.
1206 addToList = false;
1207 break;
1208 }
1209 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001210 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001211
1212 if (addToList) mFeatureUsers.add(f);
1213 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1214 // this gets used for per-pid dns when connected
1215 mNetRequestersPids[usedNetworkType].add(currentPid);
1216 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001217 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001218
1219 if (restoreTimer >= 0) {
1220 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1221 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1222 }
1223
1224 if ((ni.isConnectedOrConnecting() == true) &&
1225 !network.isTeardownRequested()) {
1226 if (ni.isConnected() == true) {
1227 final long token = Binder.clearCallingIdentity();
1228 try {
1229 // add the pid-specific dns
1230 handleDnsConfigurationChange(usedNetworkType);
1231 if (VDBG) log("special network already active");
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
1234 }
Wink Savillea639b312012-07-10 12:37:54 -07001235 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001236 }
1237 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001238 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001239 }
1240
1241 // check if the radio in play can make another contact
1242 // assume if cannot for now
1243
1244 if (DBG) {
1245 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1246 feature);
1247 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001248 if (network.reconnect()) {
1249 return PhoneConstants.APN_REQUEST_STARTED;
1250 } else {
1251 return PhoneConstants.APN_REQUEST_FAILED;
1252 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001253 } else {
1254 // need to remember this unsupported request so we respond appropriately on stop
1255 synchronized(this) {
1256 mFeatureUsers.add(f);
1257 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1258 // this gets used for per-pid dns when connected
1259 mNetRequestersPids[usedNetworkType].add(currentPid);
1260 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001261 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001262 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001263 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001264 }
Wink Savillea639b312012-07-10 12:37:54 -07001265 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001266 } finally {
1267 if (DBG) {
1268 final long execTime = SystemClock.elapsedRealtime() - startTime;
1269 if (execTime > 250) {
1270 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1271 } else {
1272 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1273 }
1274 }
1275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001278 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001280 enforceChangePermission();
1281
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001282 int pid = getCallingPid();
1283 int uid = getCallingUid();
1284
1285 FeatureUser u = null;
1286 boolean found = false;
1287
1288 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001289 for (FeatureUser x : mFeatureUsers) {
1290 if (x.isSameUser(pid, uid, networkType, feature)) {
1291 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001292 found = true;
1293 break;
1294 }
1295 }
1296 }
1297 if (found && u != null) {
1298 // stop regardless of how many other time this proc had called start
1299 return stopUsingNetworkFeature(u, true);
1300 } else {
1301 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001302 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001303 return 1;
1304 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001305 }
1306
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001307 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1308 int networkType = u.mNetworkType;
1309 String feature = u.mFeature;
1310 int pid = u.mPid;
1311 int uid = u.mUid;
1312
1313 NetworkStateTracker tracker = null;
1314 boolean callTeardown = false; // used to carry our decision outside of sync block
1315
Wink Savillec9acde92011-09-21 11:05:43 -07001316 if (VDBG) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001318 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001321 if (DBG) {
1322 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1323 ", net is invalid");
1324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 return -1;
1326 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001327
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001328 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1329 // sync block
1330 synchronized(this) {
1331 // check if this process still has an outstanding start request
1332 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001333 if (VDBG) {
1334 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1335 ", ignoring");
1336 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001337 return 1;
1338 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001339 u.unlinkDeathRecipient();
1340 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1341 // If we care about duplicate requests, check for that here.
1342 //
1343 // This is done to support the extension of a request - the app
1344 // can request we start the network feature again and renew the
1345 // auto-shutoff delay. Normal "stop" calls from the app though
1346 // do not pay attention to duplicate requests - in effect the
1347 // API does not refcount and a single stop will counter multiple starts.
1348 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001349 for (FeatureUser x : mFeatureUsers) {
1350 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001351 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001352 return 1;
1353 }
1354 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001355 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001356
repo syncaea743a2011-07-29 23:55:49 -07001357 // TODO - move to individual network trackers
1358 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1359
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001360 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001361 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001362 if (DBG) {
1363 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1364 " no known tracker for used net type " + usedNetworkType);
1365 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001366 return -1;
1367 }
1368 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001369 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001370 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001371
1372 final long token = Binder.clearCallingIdentity();
1373 try {
1374 reassessPidDns(pid, true);
1375 } finally {
1376 Binder.restoreCallingIdentity(token);
1377 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001378 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001379 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001380 if (VDBG) {
1381 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1382 " others still using it");
1383 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001384 return 1;
1385 }
1386 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001387 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001388 if (DBG) {
1389 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1390 " not a known feature - dropping");
1391 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001392 }
1393 }
Wink Savillec9acde92011-09-21 11:05:43 -07001394
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001395 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001396 if (DBG) {
1397 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1398 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001399 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001400 return 1;
1401 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001402 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405
1406 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001407 * @deprecated use requestRouteToHostAddress instead
1408 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 * Ensure that a network route exists to deliver traffic to the specified
1410 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001411 * @param networkType the type of the network over which traffic to the
1412 * specified host is to be routed
1413 * @param hostAddress the IP address of the host to which the route is
1414 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 * @return {@code true} on success, {@code false} on failure
1416 */
1417 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001418 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1419
1420 if (inetAddress == null) {
1421 return false;
1422 }
1423
1424 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1425 }
1426
1427 /**
1428 * Ensure that a network route exists to deliver traffic to the specified
1429 * host via the specified network interface.
1430 * @param networkType the type of the network over which traffic to the
1431 * specified host is to be routed
1432 * @param hostAddress the IP address of the host to which the route is
1433 * desired
1434 * @return {@code true} on success, {@code false} on failure
1435 */
1436 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001438 if (mProtectedNetworks.contains(networkType)) {
1439 enforceConnectivityInternalPermission();
1440 }
1441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001443 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 return false;
1445 }
1446 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001447 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001448
Irfan Sheriffda6da092012-08-16 12:49:23 -07001449 if (tracker == null || (netState != DetailedState.CONNECTED &&
1450 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001451 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001452 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001453 log("requestRouteToHostAddress on down network "
1454 + "(" + networkType + ") - dropped"
1455 + " tracker=" + tracker
1456 + " netState=" + netState
1457 + " isTeardownRequested="
1458 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001459 }
1460 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001462 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001463 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001464 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001465 LinkProperties lp = tracker.getLinkProperties();
Wink Savilleab9321d2013-06-29 21:10:57 -07001466 boolean ok = addRouteToAddress(lp, addr);
1467 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1468 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001469 } catch (UnknownHostException e) {
1470 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1471 } finally {
1472 Binder.restoreCallingIdentity(token);
1473 }
Wink Savilleab9321d2013-06-29 21:10:57 -07001474 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001475 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001476 }
1477
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001478 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001479 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001480 }
1481
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001482 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001483 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001484 }
1485
Robert Greenwaltad55d352011-07-22 11:55:33 -07001486 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001487 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001488 }
1489
1490 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001491 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001492 }
1493
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001494 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1495 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001496 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001497 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001498 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001499 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001500 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001501 if (bestRoute.getGateway().equals(addr)) {
1502 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001503 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001504 } else {
1505 // if we will connect to this through another route, add a direct route
1506 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001507 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001508 }
1509 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001510 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001511 }
1512
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001513 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1514 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001515 if ((lp == null) || (r == null)) {
1516 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001517 return false;
1518 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001519
1520 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001521 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001522 return false;
1523 }
1524
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001525 String ifaceName = r.getInterface();
1526 if(ifaceName == null) {
1527 loge("Error modifying route - no interface name");
1528 return false;
1529 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001530 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001531 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001532 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001533 if (bestRoute.getGateway().equals(r.getGateway())) {
1534 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001535 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001536 } else {
1537 // if we will connect to our gateway through another route, add a direct
1538 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001539 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1540 bestRoute.getGateway(),
1541 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001542 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001543 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001544 }
1545 }
1546 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001547 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001548 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001549 if (toDefaultTable) {
1550 mAddedRoutes.add(r); // only track default table - only one apps can effect
1551 mNetd.addRoute(ifaceName, r);
1552 } else {
1553 mNetd.addSecondaryRoute(ifaceName, r);
1554 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001555 } catch (Exception e) {
1556 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001557 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001558 return false;
1559 }
1560 } else {
1561 // if we remove this one and there are no more like it, then refcount==0 and
1562 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001563 if (toDefaultTable) {
1564 mAddedRoutes.remove(r);
1565 if (mAddedRoutes.contains(r) == false) {
1566 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1567 try {
1568 mNetd.removeRoute(ifaceName, r);
1569 } catch (Exception e) {
1570 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001571 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001572 return false;
1573 }
1574 } else {
1575 if (VDBG) log("not removing " + r + " as it's still in use");
1576 }
1577 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001578 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001579 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001580 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001581 } catch (Exception e) {
1582 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001583 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001584 return false;
1585 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001586 }
1587 }
1588 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
1591 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001592 * @see ConnectivityManager#getMobileDataEnabled()
1593 */
1594 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001595 // TODO: This detail should probably be in DataConnectionTracker's
1596 // which is where we store the value and maybe make this
1597 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001598 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001599 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1600 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001601 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001602 return retVal;
1603 }
1604
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001605 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001606 enforceConnectivityInternalPermission();
1607
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1609 (met ? ENABLED : DISABLED), networkType));
1610 }
1611
1612 private void handleSetDependencyMet(int networkType, boolean met) {
1613 if (mNetTrackers[networkType] != null) {
1614 if (DBG) {
1615 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1616 }
1617 mNetTrackers[networkType].setDependencyMet(met);
1618 }
1619 }
1620
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001621 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1622 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001623 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001624 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001625 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001626 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001627 }
1628
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001629 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001630 // skip update when we've already applied rules
1631 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1632 if (oldRules == uidRules) return;
1633
1634 mUidRules.put(uid, uidRules);
1635 }
1636
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001637 // TODO: notify UID when it has requested targeted updates
1638 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001639
1640 @Override
1641 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001642 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001643 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001644 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001645 }
1646
1647 synchronized (mRulesLock) {
1648 mMeteredIfaces.clear();
1649 for (String iface : meteredIfaces) {
1650 mMeteredIfaces.add(iface);
1651 }
1652 }
1653 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001654
1655 @Override
1656 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1657 // caller is NPMS, since we only register with them
1658 if (LOGD_RULES) {
1659 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1660 }
1661
1662 // kick off connectivity change broadcast for active network, since
1663 // global background policy change is radical.
1664 final int networkType = mActiveDefaultNetwork;
1665 if (isNetworkTypeValid(networkType)) {
1666 final NetworkStateTracker tracker = mNetTrackers[networkType];
1667 if (tracker != null) {
1668 final NetworkInfo info = tracker.getNetworkInfo();
1669 if (info != null && info.isConnected()) {
1670 sendConnectedBroadcast(info);
1671 }
1672 }
1673 }
1674 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001675 };
1676
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001677 /**
1678 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1679 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001680 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001681 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001682 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001683
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001685 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001686 }
1687
1688 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001689 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001690 if (VDBG) {
1691 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001692 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001693 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1694 }
tk.munb97d34c2012-01-06 10:43:52 +09001695 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1696 if (VDBG) {
1697 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1698 }
1699 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1700 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001701 }
1702
1703 @Override
1704 public void setPolicyDataEnable(int networkType, boolean enabled) {
1705 // only someone like NPMS should only be calling us
1706 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1707
1708 mHandler.sendMessage(mHandler.obtainMessage(
1709 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1710 }
1711
1712 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1713 if (isNetworkTypeValid(networkType)) {
1714 final NetworkStateTracker tracker = mNetTrackers[networkType];
1715 if (tracker != null) {
1716 tracker.setPolicyDataEnable(enabled);
1717 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001718 }
1719 }
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001722 mContext.enforceCallingOrSelfPermission(
1723 android.Manifest.permission.ACCESS_NETWORK_STATE,
1724 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726
1727 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001728 mContext.enforceCallingOrSelfPermission(
1729 android.Manifest.permission.CHANGE_NETWORK_STATE,
1730 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001733 // TODO Make this a special check when it goes public
1734 private void enforceTetherChangePermission() {
1735 mContext.enforceCallingOrSelfPermission(
1736 android.Manifest.permission.CHANGE_NETWORK_STATE,
1737 "ConnectivityService");
1738 }
1739
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001740 private void enforceTetherAccessPermission() {
1741 mContext.enforceCallingOrSelfPermission(
1742 android.Manifest.permission.ACCESS_NETWORK_STATE,
1743 "ConnectivityService");
1744 }
1745
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001746 private void enforceConnectivityInternalPermission() {
1747 mContext.enforceCallingOrSelfPermission(
1748 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1749 "ConnectivityService");
1750 }
1751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001753 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1754 * network, we ignore it. If it is for the active network, we send out a
1755 * broadcast. But first, we check whether it might be possible to connect
1756 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 * @param info the {@code NetworkInfo} for the network
1758 */
1759 private void handleDisconnect(NetworkInfo info) {
1760
Robert Greenwalt42acef32009-08-12 16:08:25 -07001761 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762
Robert Greenwalt42acef32009-08-12 16:08:25 -07001763 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001764
1765 // Remove idletimer previously setup in {@code handleConnect}
1766 removeDataActivityTracking(prevNetType);
1767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 /*
1769 * If the disconnected network is not the active one, then don't report
1770 * this as a loss of connectivity. What probably happened is that we're
1771 * getting the disconnect for a network that we explicitly disabled
1772 * in accordance with network preference policies.
1773 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001774 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001775 List<Integer> pids = mNetRequestersPids[prevNetType];
1776 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001777 // will remove them because the net's no longer connected
1778 // need to do this now as only now do we know the pids and
1779 // can properly null things that are no longer referenced.
1780 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
1783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001785 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001786 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 if (info.isFailover()) {
1788 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1789 info.setFailover(false);
1790 }
1791 if (info.getReason() != null) {
1792 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1793 }
1794 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001795 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1796 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001799 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001800 tryFailover(prevNetType);
1801 if (mActiveDefaultNetwork != -1) {
1802 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001803 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1804 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001805 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001806 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1807 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001808 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001809 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001810
1811 // Reset interface if no other connections are using the same interface
1812 boolean doReset = true;
1813 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1814 if (linkProperties != null) {
1815 String oldIface = linkProperties.getInterfaceName();
1816 if (TextUtils.isEmpty(oldIface) == false) {
1817 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1818 if (networkStateTracker == null) continue;
1819 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1820 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1821 LinkProperties l = networkStateTracker.getLinkProperties();
1822 if (l == null) continue;
1823 if (oldIface.equals(l.getInterfaceName())) {
1824 doReset = false;
1825 break;
1826 }
1827 }
1828 }
1829 }
1830 }
1831
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001832 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001833 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001834
Jeff Sharkey961e3042011-08-29 16:02:57 -07001835 final Intent immediateIntent = new Intent(intent);
1836 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1837 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001838 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001839 /*
1840 * If the failover network is already connected, then immediately send
1841 * out a followup broadcast indicating successful failover
1842 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001843 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001844 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1845 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001846 }
1847 }
1848
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001849 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001850 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001851 * If this is a default network, check if other defaults are available.
1852 * Try to reconnect on all available and let them hash it out when
1853 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001854 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001855 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001856 if (mActiveDefaultNetwork == prevNetType) {
1857 mActiveDefaultNetwork = -1;
1858 }
1859
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001860 // don't signal a reconnect for anything lower or equal priority than our
1861 // current connected default
1862 // TODO - don't filter by priority now - nice optimization but risky
1863// int currentPriority = -1;
1864// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001865// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001866// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001867 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001868 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001869 if (mNetConfigs[checkType] == null) continue;
1870 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001871 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001872
1873// Enabling the isAvailable() optimization caused mobile to not get
1874// selected if it was in the middle of error handling. Specifically
1875// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1876// would not be available and we wouldn't get connected to anything.
1877// So removing the isAvailable() optimization below for now. TODO: This
1878// optimization should work and we need to investigate why it doesn't work.
1879// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1880// complete before it is really complete.
1881// if (!mNetTrackers[checkType].isAvailable()) continue;
1882
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001883// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001884
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001885 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1886 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1887 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1888 checkInfo.setFailover(true);
1889 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001890 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001891 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001896 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001897 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001898 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1899 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001900 }
1901
Wink Saville628b0852011-08-04 15:01:58 -07001902 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001903 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1904 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001905 }
1906
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001907 private void sendInetConditionBroadcast(NetworkInfo info) {
1908 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1909 }
1910
Wink Saville628b0852011-08-04 15:01:58 -07001911 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001912 if (mLockdownTracker != null) {
1913 info = mLockdownTracker.augmentNetworkInfo(info);
1914 }
1915
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001916 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001917 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001918 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 if (info.isFailover()) {
1920 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1921 info.setFailover(false);
1922 }
1923 if (info.getReason() != null) {
1924 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1925 }
1926 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001927 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1928 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001930 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001931 return intent;
1932 }
1933
1934 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1935 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1936 }
1937
1938 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1939 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
1941
Haoyu Baidb3c8672012-06-20 14:29:57 -07001942 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1943 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1944 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1945 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001946 final long ident = Binder.clearCallingIdentity();
1947 try {
1948 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1949 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1950 } finally {
1951 Binder.restoreCallingIdentity(ident);
1952 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001953 }
1954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 /**
1956 * Called when an attempt to fail over to another network has failed.
1957 * @param info the {@link NetworkInfo} for the failed network
1958 */
1959 private void handleConnectionFailure(NetworkInfo info) {
1960 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961
Robert Greenwalt42acef32009-08-12 16:08:25 -07001962 String reason = info.getReason();
1963 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001964
Robert Greenwalt572172b2010-10-08 16:35:52 -07001965 String reasonText;
1966 if (reason == null) {
1967 reasonText = ".";
1968 } else {
1969 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001971 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001972
1973 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001974 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001975 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001976 if (getActiveNetworkInfo() == null) {
1977 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1978 }
1979 if (reason != null) {
1980 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1981 }
1982 if (extraInfo != null) {
1983 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1984 }
1985 if (info.isFailover()) {
1986 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1987 info.setFailover(false);
1988 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001989
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001990 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001991 tryFailover(info.getType());
1992 if (mActiveDefaultNetwork != -1) {
1993 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001994 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1995 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001996 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001997 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1998 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001999 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002000
Robert Greenwalt029be812010-09-20 18:01:43 -07002001 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07002002
2003 final Intent immediateIntent = new Intent(intent);
2004 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2005 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002006 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002007 /*
2008 * If the failover network is already connected, then immediately send
2009 * out a followup broadcast indicating successful failover
2010 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002011 if (mActiveDefaultNetwork != -1) {
2012 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002013 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002014 }
2015
2016 private void sendStickyBroadcast(Intent intent) {
2017 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002018 if (!mSystemReady) {
2019 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002020 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002021 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07002022 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002023 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002024 }
2025
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002026 final long ident = Binder.clearCallingIdentity();
2027 try {
2028 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2029 } finally {
2030 Binder.restoreCallingIdentity(ident);
2031 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002032 }
2033 }
2034
Wink Saville628b0852011-08-04 15:01:58 -07002035 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2036 if (delayMs <= 0) {
2037 sendStickyBroadcast(intent);
2038 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002039 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002040 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2041 + intent.getAction());
2042 }
Wink Saville628b0852011-08-04 15:01:58 -07002043 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2044 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2045 }
2046 }
2047
Mike Lockwood0f79b542009-08-14 14:18:49 -04002048 void systemReady() {
2049 synchronized(this) {
2050 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002051 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002052 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002053 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002054 }
2055 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002056 // load the global proxy at startup
2057 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002058
2059 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2060 // for user to unlock device.
2061 if (!updateLockdownVpn()) {
2062 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2063 mContext.registerReceiver(mUserPresentReceiver, filter);
2064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 }
2066
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002067 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2068 @Override
2069 public void onReceive(Context context, Intent intent) {
2070 // Try creating lockdown tracker, since user present usually means
2071 // unlocked keystore.
2072 if (updateLockdownVpn()) {
2073 mContext.unregisterReceiver(this);
2074 }
2075 }
2076 };
2077
Irfan Sheriffda6da092012-08-16 12:49:23 -07002078 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2079 if ((type != mNetworkPreference &&
2080 mNetConfigs[mActiveDefaultNetwork].priority >
2081 mNetConfigs[type].priority) ||
2082 mNetworkPreference == mActiveDefaultNetwork) return false;
2083 return true;
2084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085
Irfan Sheriffda6da092012-08-16 12:49:23 -07002086 private void handleConnect(NetworkInfo info) {
2087 final int newNetType = info.getType();
2088
2089 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 // snapshot isFailover, because sendConnectedBroadcast() resets it
2092 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002093 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002094 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095
Robert Greenwalt42acef32009-08-12 16:08:25 -07002096 // if this is a default net and other default is running
2097 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002098 if (mNetConfigs[newNetType].isDefault()) {
2099 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2100 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002101 // tear down the other
2102 NetworkStateTracker otherNet =
2103 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002104 if (DBG) {
2105 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002106 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002107 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002108 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002109 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002110 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002111 return;
2112 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002113 } else {
2114 // don't accept this one
2115 if (VDBG) {
2116 log("Not broadcasting CONNECT_ACTION " +
2117 "to torn down network " + info.getTypeName());
2118 }
2119 teardown(thisNet);
2120 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002121 }
2122 }
2123 synchronized (ConnectivityService.this) {
2124 // have a new default network, release the transition wakelock in a second
2125 // if it's held. The second pause is to allow apps to reconnect over the
2126 // new network
2127 if (mNetTransitionWakeLock.isHeld()) {
2128 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002129 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002130 mNetTransitionWakeLockSerialNumber, 0),
2131 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002132 }
2133 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002134 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002135 // this will cause us to come up initially as unconnected and switching
2136 // to connected after our normal pause unless somebody reports us as reall
2137 // disconnected
2138 mDefaultInetConditionPublished = 0;
2139 mDefaultConnectionSequence++;
2140 mInetConditionChangeInFlight = false;
2141 // Don't do this - if we never sign in stay, grey
2142 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002145 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002146 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002147 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002148
2149 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002150 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002151 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002152 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002153 } catch (RemoteException e) {
2154 // ignored; service lives in system_server
2155 }
2156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
2158
Irfan Sheriffda6da092012-08-16 12:49:23 -07002159 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2160 if (DBG) log("Captive portal check " + info);
2161 int type = info.getType();
2162 final NetworkStateTracker thisNet = mNetTrackers[type];
2163 if (mNetConfigs[type].isDefault()) {
2164 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2165 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2166 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002167 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002168 return;
2169 } else {
2170 if (DBG) log("Tear down low priority net " + info.getTypeName());
2171 teardown(thisNet);
2172 return;
2173 }
2174 }
2175 }
2176
2177 thisNet.captivePortalCheckComplete();
2178 }
2179
2180 /** @hide */
2181 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002182 enforceConnectivityInternalPermission();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002183 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002184 }
2185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002187 * Setup data activity tracking for the given network interface.
2188 *
2189 * Every {@code setupDataActivityTracking} should be paired with a
2190 * {@link removeDataActivityTracking} for cleanup.
2191 */
2192 private void setupDataActivityTracking(int type) {
2193 final NetworkStateTracker thisNet = mNetTrackers[type];
2194 final String iface = thisNet.getLinkProperties().getInterfaceName();
2195
2196 final int timeout;
2197
2198 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002199 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2200 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002201 0);
2202 // Canonicalize mobile network type
2203 type = ConnectivityManager.TYPE_MOBILE;
2204 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002205 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2206 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002207 0);
2208 } else {
2209 // do not track any other networks
2210 timeout = 0;
2211 }
2212
2213 if (timeout > 0 && iface != null) {
2214 try {
2215 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2216 } catch (RemoteException e) {
2217 }
2218 }
2219 }
2220
2221 /**
2222 * Remove data activity tracking when network disconnects.
2223 */
2224 private void removeDataActivityTracking(int type) {
2225 final NetworkStateTracker net = mNetTrackers[type];
2226 final String iface = net.getLinkProperties().getInterfaceName();
2227
2228 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2229 ConnectivityManager.TYPE_WIFI == type)) {
2230 try {
2231 // the call fails silently if no idletimer setup for this interface
2232 mNetd.removeIdleTimer(iface);
2233 } catch (RemoteException e) {
2234 }
2235 }
2236 }
2237
2238 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002239 * After a change in the connectivity state of a network. We're mainly
2240 * concerned with making sure that the list of DNS servers is set up
2241 * according to which networks are connected, and ensuring that the
2242 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002244 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002245 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002248 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002249 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002251 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002252
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002253 LinkProperties curLp = mCurrentLinkProperties[netType];
2254 LinkProperties newLp = null;
2255
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002256 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002257 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002258 if (VDBG) {
2259 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2260 " doReset=" + doReset + " resetMask=" + resetMask +
2261 "\n curLp=" + curLp +
2262 "\n newLp=" + newLp);
2263 }
2264
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002265 if (curLp != null) {
2266 if (curLp.isIdenticalInterfaceName(newLp)) {
2267 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2268 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2269 for (LinkAddress linkAddr : car.removed) {
2270 if (linkAddr.getAddress() instanceof Inet4Address) {
2271 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2272 }
2273 if (linkAddr.getAddress() instanceof Inet6Address) {
2274 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2275 }
Wink Savillee8222252011-07-13 13:44:13 -07002276 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002277 if (DBG) {
2278 log("handleConnectivityChange: addresses changed" +
2279 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2280 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002281 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002282 } else {
2283 if (DBG) {
2284 log("handleConnectivityChange: address are the same reset per doReset" +
2285 " linkProperty[" + netType + "]:" +
2286 " resetMask=" + resetMask);
2287 }
Wink Savillee8222252011-07-13 13:44:13 -07002288 }
2289 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002290 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002291 if (DBG) {
2292 log("handleConnectivityChange: interface not not equivalent reset both" +
2293 " linkProperty[" + netType + "]:" +
2294 " resetMask=" + resetMask);
2295 }
Wink Savillee8222252011-07-13 13:44:13 -07002296 }
Wink Savillee8222252011-07-13 13:44:13 -07002297 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002298 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002299 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002300 }
2301 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002302 if (VDBG) {
2303 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2304 " doReset=" + doReset + " resetMask=" + resetMask +
2305 "\n curLp=" + curLp +
2306 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002309 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002310 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002311
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002312 if (resetMask != 0 || resetDns) {
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002313 if (curLp != null) {
2314 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002315 if (TextUtils.isEmpty(iface) == false) {
2316 if (resetMask != 0) {
2317 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2318 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002319
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002320 // Tell VPN the interface is down. It is a temporary
2321 // but effective fix to make VPN aware of the change.
2322 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2323 mVpn.interfaceStatusChanged(iface, false);
2324 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002325 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002326 if (resetDns) {
2327 flushVmDnsCache();
2328 if (VDBG) log("resetting DNS cache for " + iface);
2329 try {
2330 mNetd.flushInterfaceDnsCache(iface);
2331 } catch (Exception e) {
2332 // never crash - catch them all
2333 if (DBG) loge("Exception resetting dns cache: " + e);
2334 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002335 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002336 } else {
2337 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002338 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002339 }
2340 }
2341 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002342
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002343 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002344 NetworkStateTracker tracker = mNetTrackers[netType];
2345 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002346 // If the connection was previously using clat, but is not using it now, stop the clat
2347 // daemon. Normally, this happens automatically when the connection disconnects, but if
2348 // the disconnect is not reported, or if the connection's LinkProperties changed for
2349 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2350 // still be running. If it's not running, then stopping it is a no-op.
2351 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2352 mClat.stopClat();
2353 }
2354 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002355 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2356 mClat.startClat(tracker);
2357 } else {
2358 mClat.stopClat();
2359 }
2360 }
2361
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002362 // TODO: Temporary notifying upstread change to Tethering.
2363 // @see bug/4455071
2364 /** Notify TetheringService if interface name has been changed. */
2365 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002366 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002367 if (isTetheringSupported()) {
2368 mTethering.handleTetherIfaceChange();
2369 }
2370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 }
2372
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002373 /**
2374 * Add and remove routes using the old properties (null if not previously connected),
2375 * new properties (null if becoming disconnected). May even be double null, which
2376 * is a noop.
2377 * Uses isLinkDefault to determine if default routes should be set or conversely if
2378 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002379 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002380 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002381 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2382 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002383 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002384 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2385 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002386 if (curLp != null) {
2387 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002388 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002389 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002390 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002391 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002392 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002393 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002394
Robert Greenwaltf125a092011-08-15 12:31:55 -07002395 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2396
Robert Greenwaltad55d352011-07-22 11:55:33 -07002397 for (RouteInfo r : routeDiff.removed) {
2398 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002399 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2400 }
2401 if (isLinkDefault == false) {
2402 // remove from a secondary route table
2403 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002404 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002405 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002406
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002407 if (!isLinkDefault) {
2408 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002409 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002410 // routes changed - remove all old dns entries and add new
2411 if (curLp != null) {
2412 for (InetAddress oldDns : curLp.getDnses()) {
2413 removeRouteToAddress(curLp, oldDns);
2414 }
2415 }
2416 if (newLp != null) {
2417 for (InetAddress newDns : newLp.getDnses()) {
2418 addRouteToAddress(newLp, newDns);
2419 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002420 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002421 } else {
2422 // no change in routes, check for change in dns themselves
2423 for (InetAddress oldDns : dnsDiff.removed) {
2424 removeRouteToAddress(curLp, oldDns);
2425 }
2426 for (InetAddress newDns : dnsDiff.added) {
2427 addRouteToAddress(newLp, newDns);
2428 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002429 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002430 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002431
2432 for (RouteInfo r : routeDiff.added) {
2433 if (isLinkDefault || ! r.isDefaultRoute()) {
2434 addRoute(newLp, r, TO_DEFAULT_TABLE);
2435 } else {
2436 // add to a secondary route table
2437 addRoute(newLp, r, TO_SECONDARY_TABLE);
2438
2439 // many radios add a default route even when we don't want one.
2440 // remove the default route unless somebody else has asked for it
2441 String ifaceName = newLp.getInterfaceName();
2442 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2443 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2444 try {
2445 mNetd.removeRoute(ifaceName, r);
2446 } catch (Exception e) {
2447 // never crash - catch them all
2448 if (DBG) loge("Exception trying to remove a route: " + e);
2449 }
2450 }
2451 }
2452 }
2453
Robert Greenwaltf125a092011-08-15 12:31:55 -07002454 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002455 }
2456
2457
Irfan Sheriffd649c122010-06-09 15:39:36 -07002458 /**
2459 * Reads the network specific TCP buffer sizes from SystemProperties
2460 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2461 * wide use
2462 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002463 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002464 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002465 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002466
Jeff Sharkey899223b2012-08-04 15:24:58 -07002467 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002468 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002469
2470 // Setting to default values so we won't be stuck to previous values
2471 key = "net.tcp.buffersize.default";
2472 bufferSizes = SystemProperties.get(key);
2473 }
2474
2475 // Set values in kernel
2476 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002477 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002478 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002479 + "] which comes from [" + key + "]");
2480 }
2481 setBufferSize(bufferSizes);
2482 }
2483 }
2484
2485 /**
2486 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2487 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2488 *
2489 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2490 * writeMin, writeInitial, writeMax"
2491 */
2492 private void setBufferSize(String bufferSizes) {
2493 try {
2494 String[] values = bufferSizes.split(",");
2495
2496 if (values.length == 6) {
2497 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002498 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2499 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2500 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2501 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2502 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2503 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002504 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002505 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002506 }
2507 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002508 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002509 }
2510 }
2511
Robert Greenwalt42acef32009-08-12 16:08:25 -07002512 /**
2513 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2514 * on the highest priority active net which this process requested.
2515 * If there aren't any, clear it out
2516 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002517 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002518 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002519 if (VDBG) log("reassessPidDns for pid " + pid);
2520 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002521 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002522 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002523 continue;
2524 }
2525 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002526 if (nt.getNetworkInfo().isConnected() &&
2527 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002528 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002529 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002530 if (mNetRequestersPids[i].contains(myPid)) {
2531 try {
2532 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2533 } catch (Exception e) {
2534 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002535 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002536 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002537 }
2538 }
2539 }
2540 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002541 try {
2542 mNetd.clearDnsInterfaceForPid(pid);
2543 } catch (Exception e) {
2544 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002545 }
2546 }
2547
Mattias Falk8b47b362011-08-23 14:15:13 +02002548 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002549 /*
2550 * Tell the VMs to toss their DNS caches
2551 */
2552 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2553 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002554 /*
2555 * Connectivity events can happen before boot has completed ...
2556 */
2557 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002558 final long ident = Binder.clearCallingIdentity();
2559 try {
2560 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2561 } finally {
2562 Binder.restoreCallingIdentity(ident);
2563 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002564 }
2565
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002566 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002567 private void updateDnsLocked(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002568 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002569 int last = 0;
2570 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002571 dnses = new ArrayList();
2572 dnses.add(mDefaultDns);
2573 if (DBG) {
2574 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002575 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002576 }
2577
Mattias Falk8b47b362011-08-23 14:15:13 +02002578 try {
2579 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2580 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002581 for (InetAddress dns : dnses) {
2582 ++last;
2583 String key = "net.dns" + last;
2584 String value = dns.getHostAddress();
2585 SystemProperties.set(key, value);
2586 }
2587 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2588 String key = "net.dns" + i;
2589 SystemProperties.set(key, "");
2590 }
2591 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002592 } catch (Exception e) {
2593 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002594 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002595 }
2596
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002597 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002598 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002599 NetworkStateTracker nt = mNetTrackers[netType];
2600 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002601 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002602 if (p == null) return;
2603 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002604 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002605 String network = nt.getNetworkInfo().getTypeName();
2606 synchronized (mDnsLock) {
2607 if (!mDnsOverridden) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002608 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002609 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002610 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002611 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002612 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002613 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002614 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002615 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002616 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002617 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002618 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002619 List<Integer> pids = mNetRequestersPids[netType];
2620 for (Integer pid : pids) {
2621 try {
2622 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2623 } catch (Exception e) {
2624 Slog.e(TAG, "exception setting interface for pid: " + e);
2625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002628 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002630 }
2631
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002632 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002633 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2634 NETWORK_RESTORE_DELAY_PROP_NAME);
2635 if(restoreDefaultNetworkDelayStr != null &&
2636 restoreDefaultNetworkDelayStr.length() != 0) {
2637 try {
2638 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2639 } catch (NumberFormatException e) {
2640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002642 // if the system property isn't set, use the value for the apn type
2643 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2644
2645 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2646 (mNetConfigs[networkType] != null)) {
2647 ret = mNetConfigs[networkType].restoreTime;
2648 }
2649 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651
2652 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002653 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2654 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002655 if (mContext.checkCallingOrSelfPermission(
2656 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002658 pw.println("Permission Denial: can't dump ConnectivityService " +
2659 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2660 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 return;
2662 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002663
2664 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002666 for (int i = 0; i < mNetTrackers.length; i++) {
2667 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002668 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002669 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2670 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002671 if (nst.getNetworkInfo().isConnected()) {
2672 pw.println("Active network: " + nst.getNetworkInfo().
2673 getTypeName());
2674 }
2675 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002676 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002677 pw.println(nst);
2678 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002679 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002682
2683 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002684 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002685 for (int net : mPriorityList) {
2686 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002687 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002688 pidString = pidString + pid.toString() + ", ";
2689 }
2690 pw.println(pidString);
2691 }
2692 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002693 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002694
2695 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002696 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002697 for (Object requester : mFeatureUsers) {
2698 pw.println(requester.toString());
2699 }
2700 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002701 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002702
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002703 synchronized (this) {
2704 pw.println("NetworkTranstionWakeLock is currently " +
2705 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2706 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2707 }
2708 pw.println();
2709
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002710 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002711
2712 if (mInetLog != null) {
2713 pw.println();
2714 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002715 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002716 for(int i = 0; i < mInetLog.size(); i++) {
2717 pw.println(mInetLog.get(i));
2718 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002719 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722
Robert Greenwalt42acef32009-08-12 16:08:25 -07002723 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002724 private class NetworkStateTrackerHandler extends Handler {
2725 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002726 super(looper);
2727 }
2728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 @Override
2730 public void handleMessage(Message msg) {
2731 NetworkInfo info;
2732 switch (msg.what) {
2733 case NetworkStateTracker.EVENT_STATE_CHANGED:
2734 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002735 int type = info.getType();
2736 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002737
Wink Savillec9acde92011-09-21 11:05:43 -07002738 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2739 (state == NetworkInfo.State.DISCONNECTED)) {
2740 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002741 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002742 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744
Wink Savillefde1ac92013-07-16 17:16:37 -07002745 // After booting we'll check once for mobile provisioning
2746 // if we've provisioned by and connected.
2747 if (!mFirstProvisioningCheckStarted
2748 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2749 Settings.Global.DEVICE_PROVISIONED, 0))
2750 && (state == NetworkInfo.State.CONNECTED)) {
2751 log("check provisioning after booting");
2752 mFirstProvisioningCheckStarted = true;
2753 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2754 }
2755
Jeff Sharkey2528b502012-11-09 15:57:02 -08002756 EventLogTags.writeConnectivityStateChanged(
2757 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002758
2759 if (info.getDetailedState() ==
2760 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002762 } else if (info.getDetailedState() ==
2763 DetailedState.CAPTIVE_PORTAL_CHECK) {
2764 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002765 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002767 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002769 // the logic here is, handle SUSPENDED the same as
2770 // DISCONNECTED. The only difference being we are
2771 // broadcasting an intent with NetworkInfo that's
2772 // suspended. This allows the applications an
2773 // opportunity to handle DISCONNECTED and SUSPENDED
2774 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002776 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 handleConnect(info);
2778 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002779 if (mLockdownTracker != null) {
2780 mLockdownTracker.onNetworkInfoChanged(info);
2781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002784 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002785 // TODO: Temporary allowing network configuration
2786 // change not resetting sockets.
2787 // @see bug/4455071
2788 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002790 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2791 info = (NetworkInfo) msg.obj;
2792 type = info.getType();
2793 updateNetworkSettings(mNetTrackers[type]);
2794 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002795 }
2796 }
2797 }
2798
2799 private class InternalHandler extends Handler {
2800 public InternalHandler(Looper looper) {
2801 super(looper);
2802 }
2803
2804 @Override
2805 public void handleMessage(Message msg) {
2806 NetworkInfo info;
2807 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002808 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002809 String causedBy = null;
2810 synchronized (ConnectivityService.this) {
2811 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2812 mNetTransitionWakeLock.isHeld()) {
2813 mNetTransitionWakeLock.release();
2814 causedBy = mNetTransitionWakeLockCausedBy;
2815 }
2816 }
2817 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002818 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002819 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002820 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002821 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002822 FeatureUser u = (FeatureUser)msg.obj;
2823 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002824 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002825 case EVENT_INET_CONDITION_CHANGE:
2826 {
2827 int netType = msg.arg1;
2828 int condition = msg.arg2;
2829 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002830 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002831 }
2832 case EVENT_INET_CONDITION_HOLD_END:
2833 {
2834 int netType = msg.arg1;
2835 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002836 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002837 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002838 }
2839 case EVENT_SET_NETWORK_PREFERENCE:
2840 {
2841 int preference = msg.arg1;
2842 handleSetNetworkPreference(preference);
2843 break;
2844 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002845 case EVENT_SET_MOBILE_DATA:
2846 {
2847 boolean enabled = (msg.arg1 == ENABLED);
2848 handleSetMobileData(enabled);
2849 break;
2850 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2852 {
2853 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002854 break;
2855 }
2856 case EVENT_SET_DEPENDENCY_MET:
2857 {
2858 boolean met = (msg.arg1 == ENABLED);
2859 handleSetDependencyMet(msg.arg2, met);
2860 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002861 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002862 case EVENT_RESTORE_DNS:
2863 {
2864 if (mActiveDefaultNetwork != -1) {
2865 handleDnsConfigurationChange(mActiveDefaultNetwork);
2866 }
2867 break;
2868 }
Wink Saville628b0852011-08-04 15:01:58 -07002869 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2870 {
2871 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002872 sendStickyBroadcast(intent);
2873 break;
2874 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002875 case EVENT_SET_POLICY_DATA_ENABLE: {
2876 final int networkType = msg.arg1;
2877 final boolean enabled = msg.arg2 == ENABLED;
2878 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002879 break;
2880 }
2881 case EVENT_VPN_STATE_CHANGED: {
2882 if (mLockdownTracker != null) {
2883 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2884 }
2885 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002886 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002887 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2888 int tag = mEnableFailFastMobileDataTag.get();
2889 if (msg.arg1 == tag) {
2890 MobileDataStateTracker mobileDst =
2891 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2892 if (mobileDst != null) {
2893 mobileDst.setEnableFailFastMobileData(msg.arg2);
2894 }
2895 } else {
2896 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2897 + " != tag:" + tag);
2898 }
2899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 }
2901 }
2902 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002903
2904 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002905 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002906 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002907
2908 if (isTetheringSupported()) {
2909 return mTethering.tether(iface);
2910 } else {
2911 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2912 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002913 }
2914
2915 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002916 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002917 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002918
2919 if (isTetheringSupported()) {
2920 return mTethering.untether(iface);
2921 } else {
2922 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2923 }
2924 }
2925
2926 // javadoc from interface
2927 public int getLastTetherError(String iface) {
2928 enforceTetherAccessPermission();
2929
2930 if (isTetheringSupported()) {
2931 return mTethering.getLastTetherError(iface);
2932 } else {
2933 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2934 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002935 }
2936
2937 // TODO - proper iface API for selection by property, inspection, etc
2938 public String[] getTetherableUsbRegexs() {
2939 enforceTetherAccessPermission();
2940 if (isTetheringSupported()) {
2941 return mTethering.getTetherableUsbRegexs();
2942 } else {
2943 return new String[0];
2944 }
2945 }
2946
2947 public String[] getTetherableWifiRegexs() {
2948 enforceTetherAccessPermission();
2949 if (isTetheringSupported()) {
2950 return mTethering.getTetherableWifiRegexs();
2951 } else {
2952 return new String[0];
2953 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002954 }
2955
Danica Chang6fdd0c62010-08-11 14:54:43 -07002956 public String[] getTetherableBluetoothRegexs() {
2957 enforceTetherAccessPermission();
2958 if (isTetheringSupported()) {
2959 return mTethering.getTetherableBluetoothRegexs();
2960 } else {
2961 return new String[0];
2962 }
2963 }
2964
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002965 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002966 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002967 if (isTetheringSupported()) {
2968 return mTethering.setUsbTethering(enable);
2969 } else {
2970 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2971 }
2972 }
2973
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002974 // TODO - move iface listing, queries, etc to new module
2975 // javadoc from interface
2976 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002977 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002978 return mTethering.getTetherableIfaces();
2979 }
2980
2981 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002982 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002983 return mTethering.getTetheredIfaces();
2984 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002985
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002986 @Override
2987 public String[] getTetheredIfacePairs() {
2988 enforceTetherAccessPermission();
2989 return mTethering.getTetheredIfacePairs();
2990 }
2991
Robert Greenwalt5a735062010-03-02 17:25:02 -08002992 public String[] getTetheringErroredIfaces() {
2993 enforceTetherAccessPermission();
2994 return mTethering.getErroredIfaces();
2995 }
2996
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002997 // if ro.tether.denied = true we default to no tethering
2998 // gservices could set the secure setting to 1 though to enable it on a build where it
2999 // had previously been turned off.
3000 public boolean isTetheringSupported() {
3001 enforceTetherAccessPermission();
3002 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003003 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3004 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08003005 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003006 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003007
3008 // An API NetworkStateTrackers can call when they lose their network.
3009 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3010 // whichever happens first. The timer is started by the first caller and not
3011 // restarted by subsequent callers.
3012 public void requestNetworkTransitionWakelock(String forWhom) {
3013 enforceConnectivityInternalPermission();
3014 synchronized (this) {
3015 if (mNetTransitionWakeLock.isHeld()) return;
3016 mNetTransitionWakeLockSerialNumber++;
3017 mNetTransitionWakeLock.acquire();
3018 mNetTransitionWakeLockCausedBy = forWhom;
3019 }
3020 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003021 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003022 mNetTransitionWakeLockSerialNumber, 0),
3023 mNetTransitionWakeLockTimeout);
3024 return;
3025 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003026
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003027 // 100 percent is full good, 0 is full bad.
3028 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003029 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003030 mContext.enforceCallingOrSelfPermission(
3031 android.Manifest.permission.STATUS_BAR,
3032 "ConnectivityService");
3033
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003034 if (DBG) {
3035 int pid = getCallingPid();
3036 int uid = getCallingUid();
3037 String s = pid + "(" + uid + ") reports inet is " +
3038 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3039 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3040 mInetLog.add(s);
3041 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3042 mInetLog.remove(0);
3043 }
3044 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003045 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003046 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3047 }
3048
3049 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003050 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003051 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003052 return;
3053 }
3054 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003055 if (DBG) log("handleInetConditionChange: net=" + netType +
3056 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003057 return;
3058 }
Wink Savillec9acde92011-09-21 11:05:43 -07003059 if (VDBG) {
3060 log("handleInetConditionChange: net=" +
3061 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003062 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003063 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003064 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003065 int delay;
3066 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003067 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003068 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003069 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003070 delay = Settings.Global.getInt(mContext.getContentResolver(),
3071 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003072 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003073 delay = Settings.Global.getInt(mContext.getContentResolver(),
3074 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003075 }
3076 mInetConditionChangeInFlight = true;
3077 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003078 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003079 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003080 // we've set the new condition, when this hold ends that will get picked up
3081 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003082 }
3083 }
3084
Wink Saville5b7573e2013-01-31 00:30:13 +00003085 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003086 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003087 log("handleInetConditionHoldEnd: net=" + netType +
3088 ", condition=" + mDefaultInetCondition +
3089 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003090 }
3091 mInetConditionChangeInFlight = false;
3092
3093 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003094 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003095 return;
3096 }
3097 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003098 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003099 return;
3100 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003101 // TODO: Figure out why this optimization sometimes causes a
3102 // change in mDefaultInetCondition to be missed and the
3103 // UI to not be updated.
3104 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3105 // if (DBG) log("no change in condition - aborting");
3106 // return;
3107 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003108 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3109 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003110 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003111 return;
3112 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003113 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003114 sendInetConditionBroadcast(networkInfo);
3115 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003116 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003117
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003118 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003119 // this information is already available as a world read/writable jvm property
3120 // so this API change wouldn't have a benifit. It also breaks the passing
3121 // of proxy info to all the JVMs.
3122 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003123 synchronized (mProxyLock) {
3124 if (mGlobalProxy != null) return mGlobalProxy;
3125 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003126 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003127 }
3128
3129 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003130 enforceConnectivityInternalPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003131 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003132 if (proxyProperties == mGlobalProxy) return;
3133 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3134 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3135
3136 String host = "";
3137 int port = 0;
3138 String exclList = "";
3139 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3140 mGlobalProxy = new ProxyProperties(proxyProperties);
3141 host = mGlobalProxy.getHost();
3142 port = mGlobalProxy.getPort();
3143 exclList = mGlobalProxy.getExclusionList();
3144 } else {
3145 mGlobalProxy = null;
3146 }
3147 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003148 final long token = Binder.clearCallingIdentity();
3149 try {
3150 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3151 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3152 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3153 exclList);
3154 } finally {
3155 Binder.restoreCallingIdentity(token);
3156 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003157 }
3158
3159 if (mGlobalProxy == null) {
3160 proxyProperties = mDefaultProxy;
3161 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003162 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003163 }
3164
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003165 private void loadGlobalProxy() {
3166 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003167 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3168 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3169 String exclList = Settings.Global.getString(res,
3170 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003171 if (!TextUtils.isEmpty(host)) {
3172 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003173 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003174 mGlobalProxy = proxyProperties;
3175 }
3176 }
3177 }
3178
Robert Greenwalt434203a2010-10-11 16:00:27 -07003179 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003180 // this information is already available as a world read/writable jvm property
3181 // so this API change wouldn't have a benifit. It also breaks the passing
3182 // of proxy info to all the JVMs.
3183 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003184 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003185 return mGlobalProxy;
3186 }
3187 }
3188
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003189 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3190 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3191 proxy = null;
3192 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003193 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003194 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003195 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003196 mDefaultProxy = proxy;
3197
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003198 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003199 if (!mDefaultProxyDisabled) {
3200 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003201 }
3202 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003203 }
3204
3205 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003206 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3207 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003208 if (!TextUtils.isEmpty(proxy)) {
3209 String data[] = proxy.split(":");
3210 String proxyHost = data[0];
3211 int proxyPort = 8080;
3212 if (data.length > 1) {
3213 try {
3214 proxyPort = Integer.parseInt(data[1]);
3215 } catch (NumberFormatException e) {
3216 return;
3217 }
3218 }
3219 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3220 setGlobalProxy(p);
3221 }
3222 }
3223
3224 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003225 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003226 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003227 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003228 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3229 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003230 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003231 final long ident = Binder.clearCallingIdentity();
3232 try {
3233 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3234 } finally {
3235 Binder.restoreCallingIdentity(ident);
3236 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003237 }
3238
3239 private static class SettingsObserver extends ContentObserver {
3240 private int mWhat;
3241 private Handler mHandler;
3242 SettingsObserver(Handler handler, int what) {
3243 super(handler);
3244 mHandler = handler;
3245 mWhat = what;
3246 }
3247
3248 void observe(Context context) {
3249 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003250 resolver.registerContentObserver(Settings.Global.getUriFor(
3251 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 }
3253
3254 @Override
3255 public void onChange(boolean selfChange) {
3256 mHandler.obtainMessage(mWhat).sendToTarget();
3257 }
3258 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003259
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003260 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003261 Slog.d(TAG, s);
3262 }
3263
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003264 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003265 Slog.e(TAG, s);
3266 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003267
repo syncaea743a2011-07-29 23:55:49 -07003268 int convertFeatureToNetworkType(int networkType, String feature) {
3269 int usedNetworkType = networkType;
3270
3271 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3272 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3273 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3274 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3275 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3276 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3277 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3278 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3279 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3280 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3281 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3282 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3283 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3284 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3285 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3286 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3287 } else {
3288 Slog.e(TAG, "Can't match any mobile netTracker!");
3289 }
3290 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3291 if (TextUtils.equals(feature, "p2p")) {
3292 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3293 } else {
3294 Slog.e(TAG, "Can't match any wifi netTracker!");
3295 }
3296 } else {
3297 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003298 }
repo syncaea743a2011-07-29 23:55:49 -07003299 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003300 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003301
3302 private static <T> T checkNotNull(T value, String message) {
3303 if (value == null) {
3304 throw new NullPointerException(message);
3305 }
3306 return value;
3307 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003308
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003309 /**
3310 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003311 * VpnBuilder and not available in ConnectivityManager. Permissions
3312 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003313 * @hide
3314 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003315 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003316 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003317 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003318 try {
3319 int type = mActiveDefaultNetwork;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003320 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003321 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3322 return true;
3323 }
3324 } catch (Exception e) {
3325 // ignore
3326 } finally {
3327 try {
3328 socket.close();
3329 } catch (Exception e) {
3330 // ignore
3331 }
3332 }
3333 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003334 }
3335
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003336 /**
3337 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003338 * and not available in ConnectivityManager. Permissions are checked
3339 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003340 * @hide
3341 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003342 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003343 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003344 throwIfLockdownEnabled();
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003345 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003346 }
3347
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003348 /**
3349 * Configure a TUN interface and return its file descriptor. Parameters
3350 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003351 * and not available in ConnectivityManager. Permissions are checked in
3352 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003353 * @hide
3354 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003355 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003356 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003357 throwIfLockdownEnabled();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003358 return mVpn.establish(config);
3359 }
3360
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003361 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003362 * Start legacy VPN, controlling native daemons as needed. Creates a
3363 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003364 */
3365 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003366 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003367 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003368 final LinkProperties egress = getActiveLinkProperties();
3369 if (egress == null) {
3370 throw new IllegalStateException("Missing active network connection");
3371 }
3372 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003373 }
3374
3375 /**
3376 * Return the information of the ongoing legacy VPN. This method is used
3377 * by VpnSettings and not available in ConnectivityManager. Permissions
3378 * are checked in Vpn class.
3379 * @hide
3380 */
3381 @Override
3382 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003383 throwIfLockdownEnabled();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003384 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003385 }
3386
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003387 /**
3388 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3389 * through NetworkStateTracker since it works differently. For example, it
3390 * needs to override DNS servers but never takes the default routes. It
3391 * relies on another data network, and it could keep existing connections
3392 * alive after reconnecting, switching between networks, or even resuming
3393 * from deep sleep. Calls from applications should be done synchronously
3394 * to avoid race conditions. As these are all hidden APIs, refactoring can
3395 * be done whenever a better abstraction is developed.
3396 */
3397 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003398 private VpnCallback() {
3399 }
3400
Jeff Sharkey899223b2012-08-04 15:24:58 -07003401 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003402 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003403 }
3404
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003405 public void override(List<String> dnsServers, List<String> searchDomains) {
3406 if (dnsServers == null) {
3407 restore();
3408 return;
3409 }
3410
3411 // Convert DNS servers into addresses.
3412 List<InetAddress> addresses = new ArrayList<InetAddress>();
3413 for (String address : dnsServers) {
3414 // Double check the addresses and remove invalid ones.
3415 try {
3416 addresses.add(InetAddress.parseNumericAddress(address));
3417 } catch (Exception e) {
3418 // ignore
3419 }
3420 }
3421 if (addresses.isEmpty()) {
3422 restore();
3423 return;
3424 }
3425
3426 // Concatenate search domains into a string.
3427 StringBuilder buffer = new StringBuilder();
3428 if (searchDomains != null) {
3429 for (String domain : searchDomains) {
3430 buffer.append(domain).append(' ');
3431 }
3432 }
3433 String domains = buffer.toString().trim();
3434
3435 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003436 synchronized (mDnsLock) {
Mattias Falk8b47b362011-08-23 14:15:13 +02003437 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003438 mDnsOverridden = true;
3439 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003440
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003441 // Temporarily disable the default proxy (not global).
3442 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003443 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003444 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003445 sendProxyBroadcast(null);
3446 }
3447 }
3448
3449 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003450 }
3451
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003452 public void restore() {
3453 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003454 if (mDnsOverridden) {
3455 mDnsOverridden = false;
3456 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003457 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003458 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003459 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003460 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003461 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003462 sendProxyBroadcast(mDefaultProxy);
3463 }
3464 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003465 }
3466 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003467
3468 @Override
3469 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003470 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3471 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3472 return false;
3473 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003474
3475 // Tear down existing lockdown if profile was removed
3476 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3477 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003478 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003479 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3480 return false;
3481 }
3482
3483 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3484 final VpnProfile profile = VpnProfile.decode(
3485 profileName, mKeyStore.get(Credentials.VPN + profileName));
3486 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3487 } else {
3488 setLockdownTracker(null);
3489 }
3490
3491 return true;
3492 }
3493
3494 /**
3495 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3496 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3497 */
3498 private void setLockdownTracker(LockdownVpnTracker tracker) {
3499 // Shutdown any existing tracker
3500 final LockdownVpnTracker existing = mLockdownTracker;
3501 mLockdownTracker = null;
3502 if (existing != null) {
3503 existing.shutdown();
3504 }
3505
3506 try {
3507 if (tracker != null) {
3508 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003509 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003510 mLockdownTracker = tracker;
3511 mLockdownTracker.init();
3512 } else {
3513 mNetd.setFirewallEnabled(false);
3514 }
3515 } catch (RemoteException e) {
3516 // ignored; NMS lives inside system_server
3517 }
3518 }
3519
3520 private void throwIfLockdownEnabled() {
3521 if (mLockdownEnabled) {
3522 throw new IllegalStateException("Unavailable in lockdown mode");
3523 }
3524 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003525
3526 public void supplyMessenger(int networkType, Messenger messenger) {
3527 enforceConnectivityInternalPermission();
3528
3529 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3530 mNetTrackers[networkType].supplyMessenger(messenger);
3531 }
3532 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003533
3534 public int findConnectionTypeForIface(String iface) {
3535 enforceConnectivityInternalPermission();
3536
3537 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3538 for (NetworkStateTracker tracker : mNetTrackers) {
3539 if (tracker != null) {
3540 LinkProperties lp = tracker.getLinkProperties();
3541 if (lp != null && iface.equals(lp.getInterfaceName())) {
3542 return tracker.getNetworkInfo().getType();
3543 }
3544 }
3545 }
3546 return ConnectivityManager.TYPE_NONE;
3547 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003548
3549 /**
3550 * Have mobile data fail fast if enabled.
3551 *
3552 * @param enabled DctConstants.ENABLED/DISABLED
3553 */
3554 private void setEnableFailFastMobileData(int enabled) {
3555 int tag;
3556
3557 if (enabled == DctConstants.ENABLED) {
3558 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3559 } else {
3560 tag = mEnableFailFastMobileDataTag.get();
3561 }
3562 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3563 enabled));
3564 }
3565
3566 @Override
3567 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3568 final ResultReceiver resultReceiver) {
3569 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3570 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3571 + " resultReceiver=" + resultReceiver);
3572 enforceChangePermission();
3573
Wink Savillefde1ac92013-07-16 17:16:37 -07003574 mFirstProvisioningCheckStarted = true;
3575
Wink Savilleab9321d2013-06-29 21:10:57 -07003576 int timeOutMs = suggestedTimeOutMs;
3577 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3578 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3579 }
3580
Wink Saville68e6c642013-07-02 10:55:14 -07003581 // Check that mobile networks are supported
3582 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3583 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3584 log("checkMobileProvisioning: X no mobile network");
3585 if (resultReceiver != null) {
3586 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3587 }
3588 return timeOutMs;
3589 }
3590
Wink Savilleab9321d2013-06-29 21:10:57 -07003591 final long token = Binder.clearCallingIdentity();
3592 try {
3593 CheckMp checkMp = new CheckMp(mContext, this);
3594 CheckMp.CallBack cb = new CheckMp.CallBack() {
3595 @Override
3596 void onComplete(Integer result) {
3597 log("CheckMp.onComplete: result=" + result);
3598 if (resultReceiver != null) {
3599 log("CheckMp.onComplete: send result");
3600 resultReceiver.send(result, null);
3601 }
3602 NetworkInfo ni =
3603 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3604 switch(result) {
3605 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3606 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3607 log("CheckMp.onComplete: ignore, connected or no connection");
3608 break;
3609 }
3610 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3611 log("CheckMp.onComplete: warm sim");
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003612 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003613 if (TextUtils.isEmpty(url)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003614 url = getMobileRedirectedProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003615 }
3616 if (TextUtils.isEmpty(url) == false) {
3617 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3618 setNotificationVisible(true, ni, url);
3619 } else {
3620 log("CheckMp.onComplete: warm sim (redirected), no url");
3621 }
3622 break;
3623 }
3624 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3625 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003626 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003627 if (TextUtils.isEmpty(url) == false) {
3628 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3629 setNotificationVisible(true, ni, url);
3630 } else {
3631 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3632 }
3633 break;
3634 }
3635 default: {
3636 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3637 break;
3638 }
3639 }
3640 }
3641 };
3642 CheckMp.Params params =
3643 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3644 log("checkMobileProvisioning: params=" + params);
3645 setNotificationVisible(false, null, null);
3646 checkMp.execute(params);
3647 } finally {
3648 Binder.restoreCallingIdentity(token);
3649 log("checkMobileProvisioning: X");
3650 }
3651 return timeOutMs;
3652 }
3653
3654 static class CheckMp extends
3655 AsyncTask<CheckMp.Params, Void, Integer> {
3656 private static final String CHECKMP_TAG = "CheckMp";
3657 public static final int MAX_TIMEOUT_MS = 60000;
3658 private static final int SOCKET_TIMEOUT_MS = 5000;
3659 private Context mContext;
3660 private ConnectivityService mCs;
3661 private TelephonyManager mTm;
3662 private Params mParams;
3663
3664 /**
3665 * Parameters for AsyncTask.execute
3666 */
3667 static class Params {
3668 private String mUrl;
3669 private long mTimeOutMs;
3670 private CallBack mCb;
3671
3672 Params(String url, long timeOutMs, CallBack cb) {
3673 mUrl = url;
3674 mTimeOutMs = timeOutMs;
3675 mCb = cb;
3676 }
3677
3678 @Override
3679 public String toString() {
3680 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3681 }
3682 }
3683
3684 /**
3685 * The call back object passed in Params. onComplete will be called
3686 * on the main thread.
3687 */
3688 abstract static class CallBack {
3689 // Called on the main thread.
3690 abstract void onComplete(Integer result);
3691 }
3692
3693 public CheckMp(Context context, ConnectivityService cs) {
3694 mContext = context;
3695 mCs = cs;
3696
3697 // Setup access to TelephonyService we'll be using.
3698 mTm = (TelephonyManager) mContext.getSystemService(
3699 Context.TELEPHONY_SERVICE);
3700 }
3701
3702 /**
3703 * Get the default url to use for the test.
3704 */
3705 public String getDefaultUrl() {
3706 // See http://go/clientsdns for usage approval
3707 String server = Settings.Global.getString(mContext.getContentResolver(),
3708 Settings.Global.CAPTIVE_PORTAL_SERVER);
3709 if (server == null) {
3710 server = "clients3.google.com";
3711 }
3712 return "http://" + server + "/generate_204";
3713 }
3714
3715 /**
3716 * Detect if its possible to connect to the http url. DNS based detection techniques
3717 * do not work at all hotspots. The best way to check is to perform a request to
3718 * a known address that fetches the data we expect.
3719 */
3720 private synchronized Integer isMobileOk(Params params) {
3721 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3722 Uri orgUri = Uri.parse(params.mUrl);
3723 Random rand = new Random();
3724 mParams = params;
3725
3726 try {
3727 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3728 log("isMobileOk: not mobile capable");
3729 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3730 return result;
3731 }
3732
3733 // Enable fail fast as we'll do retries here and use a
3734 // hipri connection so the default connection stays active.
3735 log("isMobileOk: start hipri url=" + params.mUrl);
3736 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3737 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3738 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3739
3740 // Continue trying to connect until time has run out
3741 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3742 while(SystemClock.elapsedRealtime() < endTime) {
3743 try {
3744 // Wait for hipri to connect.
3745 // TODO: Don't poll and handle situation where hipri fails
3746 // because default is retrying. See b/9569540
3747 NetworkInfo.State state = mCs
3748 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3749 if (state != NetworkInfo.State.CONNECTED) {
3750 log("isMobileOk: not connected ni=" +
3751 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3752 sleep(1);
3753 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3754 continue;
3755 }
3756
3757 // Get of the addresses associated with the url host. We need to use the
3758 // address otherwise HttpURLConnection object will use the name to get
3759 // the addresses and is will try every address but that will bypass the
3760 // route to host we setup and the connection could succeed as the default
3761 // interface might be connected to the internet via wifi or other interface.
3762 InetAddress[] addresses;
3763 try {
3764 addresses = InetAddress.getAllByName(orgUri.getHost());
3765 } catch (UnknownHostException e) {
3766 log("isMobileOk: UnknownHostException");
3767 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3768 return result;
3769 }
3770 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3771
3772 // Get the type of addresses supported by this link
3773 LinkProperties lp = mCs.getLinkProperties(
3774 ConnectivityManager.TYPE_MOBILE_HIPRI);
3775 boolean linkHasIpv4 = hasIPv4Address(lp);
3776 boolean linkHasIpv6 = hasIPv6Address(lp);
3777 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3778 + " linkHasIpv6=" + linkHasIpv6);
3779
3780 // Loop through at most 3 valid addresses or all of the address or until
3781 // we run out of time
3782 int loops = Math.min(3, addresses.length);
3783 for(int validAddr=0, addrTried=0;
3784 (validAddr < loops) && (addrTried < addresses.length)
3785 && (SystemClock.elapsedRealtime() < endTime);
3786 addrTried ++) {
3787
3788 // Choose the address at random but make sure its type is supported
3789 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3790 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3791 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3792 // Valid address, so use it
3793 validAddr += 1;
3794 } else {
3795 // Invalid address so try next address
3796 continue;
3797 }
3798
3799 // Make a route to host so we check the specific interface.
3800 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3801 hostAddr.getAddress())) {
3802 // Wait a short time to be sure the route is established ??
3803 log("isMobileOk:"
3804 + " wait to establish route to hostAddr=" + hostAddr);
3805 sleep(3);
3806 } else {
3807 log("isMobileOk:"
3808 + " could not establish route to hostAddr=" + hostAddr);
3809 continue;
3810 }
3811
3812 // Rewrite the url to have numeric address to use the specific route.
3813 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3814 // is used which is useless in this case.
3815 URL newUrl = new URL(orgUri.getScheme() + "://"
3816 + hostAddr.getHostAddress() + orgUri.getPath());
3817 log("isMobileOk: newUrl=" + newUrl);
3818
3819 HttpURLConnection urlConn = null;
3820 try {
3821 // Open the connection set the request header and get the response
3822 urlConn = (HttpURLConnection) newUrl.openConnection(
3823 java.net.Proxy.NO_PROXY);
3824 urlConn.setInstanceFollowRedirects(false);
3825 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3826 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3827 urlConn.setUseCaches(false);
3828 urlConn.setAllowUserInteraction(false);
3829 urlConn.setRequestProperty("Connection", "close");
3830 int responseCode = urlConn.getResponseCode();
3831 if (responseCode == 204) {
3832 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3833 } else {
3834 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3835 }
3836 log("isMobileOk: connected responseCode=" + responseCode);
3837 urlConn.disconnect();
3838 urlConn = null;
3839 return result;
3840 } catch (Exception e) {
3841 log("isMobileOk: HttpURLConnection Exception e=" + e);
3842 if (urlConn != null) {
3843 urlConn.disconnect();
3844 urlConn = null;
3845 }
3846 }
3847 }
3848 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3849 log("isMobileOk: loops|timed out");
3850 return result;
3851 } catch (Exception e) {
3852 log("isMobileOk: Exception e=" + e);
3853 continue;
3854 }
3855 }
3856 log("isMobileOk: timed out");
3857 } finally {
3858 log("isMobileOk: F stop hipri");
3859 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3860 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3861 Phone.FEATURE_ENABLE_HIPRI);
3862 log("isMobileOk: X result=" + result);
3863 }
3864 return result;
3865 }
3866
3867 @Override
3868 protected Integer doInBackground(Params... params) {
3869 return isMobileOk(params[0]);
3870 }
3871
3872 @Override
3873 protected void onPostExecute(Integer result) {
3874 log("onPostExecute: result=" + result);
3875 if ((mParams != null) && (mParams.mCb != null)) {
3876 mParams.mCb.onComplete(result);
3877 }
3878 }
3879
3880 private String inetAddressesToString(InetAddress[] addresses) {
3881 StringBuffer sb = new StringBuffer();
3882 boolean firstTime = true;
3883 for(InetAddress addr : addresses) {
3884 if (firstTime) {
3885 firstTime = false;
3886 } else {
3887 sb.append(",");
3888 }
3889 sb.append(addr);
3890 }
3891 return sb.toString();
3892 }
3893
3894 private void printNetworkInfo() {
3895 boolean hasIccCard = mTm.hasIccCard();
3896 int simState = mTm.getSimState();
3897 log("hasIccCard=" + hasIccCard
3898 + " simState=" + simState);
3899 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3900 if (ni != null) {
3901 log("ni.length=" + ni.length);
3902 for (NetworkInfo netInfo: ni) {
3903 log("netInfo=" + netInfo.toString());
3904 }
3905 } else {
3906 log("no network info ni=null");
3907 }
3908 }
3909
3910 /**
3911 * Sleep for a few seconds then return.
3912 * @param seconds
3913 */
3914 private static void sleep(int seconds) {
3915 try {
3916 Thread.sleep(seconds * 1000);
3917 } catch (InterruptedException e) {
3918 e.printStackTrace();
3919 }
3920 }
3921
3922 public boolean hasIPv4Address(LinkProperties lp) {
3923 return lp.hasIPv4Address();
3924 }
3925
3926 // Not implemented in LinkProperties, do it here.
3927 public boolean hasIPv6Address(LinkProperties lp) {
3928 for (LinkAddress address : lp.getLinkAddresses()) {
3929 if (address.getAddress() instanceof Inet6Address) {
3930 return true;
3931 }
3932 }
3933 return false;
3934 }
3935
3936 private void log(String s) {
3937 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3938 }
3939 }
3940
3941 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3942
3943 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3944 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3945
3946 Resources r = Resources.getSystem();
3947 NotificationManager notificationManager = (NotificationManager) mContext
3948 .getSystemService(Context.NOTIFICATION_SERVICE);
3949
3950 if (visible) {
3951 CharSequence title;
3952 CharSequence details;
3953 int icon;
3954 switch (networkInfo.getType()) {
3955 case ConnectivityManager.TYPE_WIFI:
3956 log("setNotificationVisible: TYPE_WIFI");
3957 title = r.getString(R.string.wifi_available_sign_in, 0);
3958 details = r.getString(R.string.network_available_sign_in_detailed,
3959 networkInfo.getExtraInfo());
3960 icon = R.drawable.stat_notify_wifi_in_range;
3961 break;
3962 case ConnectivityManager.TYPE_MOBILE:
3963 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3964 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
3965 title = r.getString(R.string.network_available_sign_in, 0);
3966 // TODO: Change this to pull from NetworkInfo once a printable
3967 // name has been added to it
3968 details = mTelephonyManager.getNetworkOperatorName();
3969 icon = R.drawable.stat_notify_rssi_in_range;
3970 break;
3971 default:
3972 log("setNotificationVisible: other type=" + networkInfo.getType());
3973 title = r.getString(R.string.network_available_sign_in, 0);
3974 details = r.getString(R.string.network_available_sign_in_detailed,
3975 networkInfo.getExtraInfo());
3976 icon = R.drawable.stat_notify_rssi_in_range;
3977 break;
3978 }
3979
3980 Notification notification = new Notification();
3981 notification.when = 0;
3982 notification.icon = icon;
3983 notification.flags = Notification.FLAG_AUTO_CANCEL;
3984 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3985 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3986 Intent.FLAG_ACTIVITY_NEW_TASK);
3987 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3988 notification.tickerText = title;
3989 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3990
3991 log("setNotificaitionVisible: notify notificaiton=" + notification);
3992 notificationManager.notify(NOTIFICATION_ID, 1, notification);
3993 } else {
3994 log("setNotificaitionVisible: cancel");
3995 notificationManager.cancel(NOTIFICATION_ID, 1);
3996 }
3997 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
3998 }
3999
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004000 /** Location to an updatable file listing carrier provisioning urls.
4001 * An example:
4002 *
4003 * <?xml version="1.0" encoding="utf-8"?>
4004 * <provisioningUrls>
4005 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4006 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4007 * </provisioningUrls>
4008 */
4009 private static final String PROVISIONING_URL_PATH =
4010 "/data/misc/radio/provisioning_urls.xml";
4011 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004012
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004013 /** XML tag for root element. */
4014 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4015 /** XML tag for individual url */
4016 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4017 /** XML tag for redirected url */
4018 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4019 /** XML attribute for mcc */
4020 private static final String ATTR_MCC = "mcc";
4021 /** XML attribute for mnc */
4022 private static final String ATTR_MNC = "mnc";
4023
4024 private static final int REDIRECTED_PROVISIONING = 1;
4025 private static final int PROVISIONING = 2;
4026
4027 private String getProvisioningUrlBaseFromFile(int type) {
4028 FileReader fileReader = null;
4029 XmlPullParser parser = null;
4030 Configuration config = mContext.getResources().getConfiguration();
4031 String tagType;
4032
4033 switch (type) {
4034 case PROVISIONING:
4035 tagType = TAG_PROVISIONING_URL;
4036 break;
4037 case REDIRECTED_PROVISIONING:
4038 tagType = TAG_REDIRECTED_URL;
4039 break;
4040 default:
4041 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4042 type);
4043 }
4044
4045 try {
4046 fileReader = new FileReader(mProvisioningUrlFile);
4047 parser = Xml.newPullParser();
4048 parser.setInput(fileReader);
4049 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4050
4051 while (true) {
4052 XmlUtils.nextElement(parser);
4053
4054 String element = parser.getName();
4055 if (element == null) break;
4056
4057 if (element.equals(tagType)) {
4058 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4059 try {
4060 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4061 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4062 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4063 parser.next();
4064 if (parser.getEventType() == XmlPullParser.TEXT) {
4065 return parser.getText();
4066 }
4067 }
4068 }
4069 } catch (NumberFormatException e) {
4070 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4071 }
4072 }
4073 }
4074 return null;
4075 } catch (FileNotFoundException e) {
4076 loge("Carrier Provisioning Urls file not found");
4077 } catch (XmlPullParserException e) {
4078 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4079 } catch (IOException e) {
4080 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4081 } finally {
4082 if (fileReader != null) {
4083 try {
4084 fileReader.close();
4085 } catch (IOException e) {}
4086 }
4087 }
4088 return null;
4089 }
4090
4091 private String getMobileRedirectedProvisioningUrl() {
4092 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4093 if (TextUtils.isEmpty(url)) {
4094 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4095 }
4096 return url;
4097 }
4098
4099 public String getMobileProvisioningUrl() {
4100 enforceConnectivityInternalPermission();
4101 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4102 if (TextUtils.isEmpty(url)) {
4103 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4104 log("getProvisioningUrl: mobile_provisioining_url from resource =" + url);
4105 } else {
4106 log("getProvisioningUrl: mobile_provisioning_url from File =" + url);
4107 }
Wink Saville8cf35602013-07-10 23:00:07 -07004108 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004109 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004110 String phoneNumber = mTelephonyManager.getLine1Number();
4111 if (TextUtils.isEmpty(phoneNumber)) {
4112 phoneNumber = "0000000000";
4113 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004114 url = String.format(url,
4115 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4116 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004117 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004118 }
4119
Wink Savilleab9321d2013-06-29 21:10:57 -07004120 return url;
4121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122}