blob: 0862f8a969e62ec8f70dd991f4e37ba08f76ff09 [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;
Hui Lu1c5624a2014-01-15 11:05:36 -050029import static android.net.ConnectivityManager.TYPE_PROXY;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070030import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.ConnectivityManager.isNetworkTypeValid;
32import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070035import android.app.AlarmManager;
Chad Brubaker74f99a42014-03-13 18:18:40 +000036import android.app.AppOpsManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080040import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville948282b2013-08-29 08:55:16 -070041import android.content.ActivityNotFoundException;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ContentResolver;
44import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090045import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070047import android.content.IntentFilter;
Chad Brubaker74f99a42014-03-13 18:18:40 +000048import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Chad Brubaker74f99a42014-03-13 18:18:40 +000050import android.content.pm.PackageManager.NameNotFoundException;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070051import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090052import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070053import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070054import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080056import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080057import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070059import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070060import android.net.INetworkPolicyListener;
61import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070062import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070063import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080064import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070065import android.net.LinkProperties.CompareResult;
Jeff Sharkeye4984be2013-09-10 21:03:27 -070066import android.net.LinkQualityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070068import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070070import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070071import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070072import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070074import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070075import android.net.Proxy;
Hui Lu1c5624a2014-01-15 11:05:36 -050076import android.net.ProxyDataTracker;
Robert Greenwalt434203a2010-10-11 16:00:27 -070077import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070078import android.net.RouteInfo;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070079import android.net.SamplingDataTracker;
Jason Monk602b2322013-07-03 17:04:33 -040080import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090082import android.net.wimax.WimaxManagerConstants;
Wink Savilleab9321d2013-06-29 21:10:57 -070083import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Binder;
Wink Saville1d3a89e2013-10-31 06:35:22 -070085import android.os.Build;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040086import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070088import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070090import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Looper;
92import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070093import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070094import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070095import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070096import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070099import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700101import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800107import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700108import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700109import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700110import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Wink Savilleab9321d2013-06-29 21:10:57 -0700112import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400113import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700114import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700115import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700116import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.telephony.DctConstants;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700118import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -0700119import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700120import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700121import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700122import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400123import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900124import com.android.server.connectivity.Nat464Xlat;
Jason Monk602b2322013-07-03 17:04:33 -0400125import com.android.server.connectivity.PacManager;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800126import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700128import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700129import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700130import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700131import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700132
tk.mun148c7d02011-10-13 22:51:57 +0900133import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700134
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import org.xmlpull.v1.XmlPullParser;
136import org.xmlpull.v1.XmlPullParserException;
137
138import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import java.io.FileNotFoundException;
141import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700142import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900144import java.lang.reflect.Constructor;
Wink Savilleab9321d2013-06-29 21:10:57 -0700145import java.net.HttpURLConnection;
Wink Savillec9822c52011-07-14 12:23:28 -0700146import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700147import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700148import java.net.InetAddress;
Wink Savilleab9321d2013-06-29 21:10:57 -0700149import java.net.URL;
Wink Saville1d3a89e2013-10-31 06:35:22 -0700150import java.net.URLConnection;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700151import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700153import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700154import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700155import java.util.GregorianCalendar;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700156import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700157import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700158import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700159import java.util.Map;
Wink Savilleab9321d2013-06-29 21:10:57 -0700160import java.util.Random;
Wink Saville948282b2013-08-29 08:55:16 -0700161import java.util.concurrent.atomic.AtomicBoolean;
Wink Savilleab9321d2013-06-29 21:10:57 -0700162import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Wink Saville1d3a89e2013-10-31 06:35:22 -0700164import javax.net.ssl.HostnameVerifier;
165import javax.net.ssl.HttpsURLConnection;
166import javax.net.ssl.SSLSession;
167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168/**
169 * @hide
170 */
171public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700172 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
Robert Greenwaltba175a52010-10-05 19:12:26 -0700174 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700175 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700177 private static final boolean LOGD_RULES = false;
178
Jeff Sharkey899223b2012-08-04 15:24:58 -0700179 // TODO: create better separation between radio types and network types
180
Robert Greenwalt42acef32009-08-12 16:08:25 -0700181 // how long to wait before switching back to a radio's default network
182 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
183 // system property that can override the above value
184 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
185 "android.telephony.apn-restore";
186
Wink Savilleab9321d2013-06-29 21:10:57 -0700187 // Default value if FAIL_FAST_TIME_MS is not set
188 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
189 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
190 private static final String FAIL_FAST_TIME_MS =
191 "persist.radio.fail_fast_time_ms";
192
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700193 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
194 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
195
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -0700196 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700197
198 private PendingIntent mSampleIntervalElapsedIntent;
199
200 // Set network sampling interval at 12 minutes, this way, even if the timers get
201 // aggregated, it will fire at around 15 minutes, which should allow us to
202 // aggregate this timer with other timers (specially the socket keep alive timers)
203 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
204
205 // start network sampling a minute after booting ...
206 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
207
208 AlarmManager mAlarmManager;
209
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700210 // used in recursive route setting to add gateways for the host for which
211 // a host route was requested.
212 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
213
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800214 private Tethering mTethering;
215
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700216 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700217
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700218 @GuardedBy("mVpns")
219 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700220 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700221
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700222 private boolean mLockdownEnabled;
223 private LockdownVpnTracker mLockdownTracker;
224
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900225 private Nat464Xlat mClat;
226
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700227 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
228 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700229 /** Currently active network rules by UID. */
230 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700231 /** Set of ifaces that are costly. */
232 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 /**
235 * Sometimes we want to refer to the individual network state
236 * trackers separately, and sometimes we just want to treat them
237 * abstractly.
238 */
239 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700240
Irfan Sheriffda6da092012-08-16 12:49:23 -0700241 /* Handles captive portal check on a network */
242 private CaptivePortalTracker mCaptivePortalTracker;
243
Robert Greenwalt42acef32009-08-12 16:08:25 -0700244 /**
Wink Savillee8222252011-07-13 13:44:13 -0700245 * The link properties that define the current links
246 */
247 private LinkProperties mCurrentLinkProperties[];
248
249 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700250 * A per Net list of the PID's that requested access to the net
251 * used both as a refcount and for per-PID DNS selection
252 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200253 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700254
Robert Greenwalt42acef32009-08-12 16:08:25 -0700255 // priority order of the nettrackers
256 // (excluding dynamically set mNetworkPreference)
257 // TODO - move mNetworkTypePreference into this
258 private int[] mPriorityList;
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 private Context mContext;
261 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700262 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700263 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000264 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700265 private int mDefaultInetConditionPublished = 0;
266 private boolean mInetConditionChangeInFlight = false;
267 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700269 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800270 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
272 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700273 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700275 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700276 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700277
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278 private static final int ENABLED = 1;
279 private static final int DISABLED = 0;
280
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700281 private static final boolean ADD = true;
282 private static final boolean REMOVE = false;
283
284 private static final boolean TO_DEFAULT_TABLE = true;
285 private static final boolean TO_SECONDARY_TABLE = false;
286
Chad Brubakerf336d722013-07-15 16:34:04 -0700287 private static final boolean EXEMPT = true;
288 private static final boolean UNEXEMPT = false;
289
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700290 /**
291 * used internally as a delayed event to make us switch back to the
292 * default network
293 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700295
296 /**
297 * used internally to change our mobile data enabled flag
298 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700299 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700300
301 /**
302 * used internally to change our network preference setting
303 * arg1 = networkType to prefer
304 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700305 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700306
307 /**
308 * used internally to synchronize inet condition reports
309 * arg1 = networkType
310 * arg2 = condition (0 bad, 100 good)
311 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700312 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700313
314 /**
315 * used internally to mark the end of inet condition hold periods
316 * arg1 = networkType
317 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700318 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700319
320 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700321 * used internally to set enable/disable cellular data
322 * arg1 = ENBALED or DISABLED
323 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700324 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700325
Robert Greenwaltf3331232010-09-24 14:32:21 -0700326 /**
327 * used internally to clear a wakelock when transitioning
328 * from one net to another
329 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700330 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700331
Robert Greenwalt434203a2010-10-11 16:00:27 -0700332 /**
333 * used internally to reload global proxy settings
334 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700335 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700336
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700337 /**
338 * used internally to set external dependency met/unmet
339 * arg1 = ENABLED (met) or DISABLED (unmet)
340 * arg2 = NetworkType
341 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700342 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700343
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700344 /**
Wink Saville628b0852011-08-04 15:01:58 -0700345 * used internally to send a sticky broadcast delayed.
346 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700347 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700348
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700349 /**
350 * Used internally to
351 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
352 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700353 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700354
Chad Brubakerb98703e2013-07-23 17:44:41 -0700355 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700356
Wink Savilleab9321d2013-06-29 21:10:57 -0700357 /**
358 * Used internally to disable fail fast of mobile data
359 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700360 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Savilleab9321d2013-06-29 21:10:57 -0700361
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700362 /**
363 * user internally to indicate that data sampling interval is up
364 */
365 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
366
Jason Monkdecd2952013-10-10 14:02:51 -0400367 /**
368 * PAC manager has received new port.
369 */
370 private static final int EVENT_PROXY_HAS_CHANGED = 16;
371
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700372 /** Handler used for internal events. */
373 private InternalHandler mHandler;
374 /** Handler used for incoming {@link NetworkStateTracker} events. */
375 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700376
377 // list of DeathRecipients used to make sure features are turned off when
378 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500379 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700380
Mike Lockwood0f79b542009-08-14 14:18:49 -0400381 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800382 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400383
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700384 private PowerManager.WakeLock mNetTransitionWakeLock;
385 private String mNetTransitionWakeLockCausedBy = "";
386 private int mNetTransitionWakeLockSerialNumber;
387 private int mNetTransitionWakeLockTimeout;
388
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700389 private InetAddress mDefaultDns;
390
Chad Brubakerf336d722013-07-15 16:34:04 -0700391 // Lock for protecting access to mAddedRoutes and mExemptAddresses
392 private final Object mRoutesLock = new Object();
393
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700394 // this collection is used to refcount the added routes - if there are none left
395 // it's time to remove the route from the route table
Chad Brubakerf336d722013-07-15 16:34:04 -0700396 @GuardedBy("mRoutesLock")
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700397 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
398
Chad Brubakerf336d722013-07-15 16:34:04 -0700399 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
400 // used to handle cleanup of exempt rules
401 @GuardedBy("mRoutesLock")
402 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
403
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700404 // used in DBG mode to track inet condition reports
405 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
406 private ArrayList mInetLog;
407
Robert Greenwalt434203a2010-10-11 16:00:27 -0700408 // track the current default http proxy - tell the world if we get a new one (real change)
409 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700410 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700411 private boolean mDefaultProxyDisabled = false;
412
Robert Greenwalt434203a2010-10-11 16:00:27 -0700413 // track the global proxy.
414 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700415
Jason Monk602b2322013-07-03 17:04:33 -0400416 private PacManager mPacManager = null;
417
Robert Greenwalt434203a2010-10-11 16:00:27 -0700418 private SettingsObserver mSettingsObserver;
419
Chad Brubaker74f99a42014-03-13 18:18:40 +0000420 private AppOpsManager mAppOpsManager;
421
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700422 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700423 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700424
Robert Greenwalt511288a2009-12-07 11:33:18 -0800425 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700426 public int mSimultaneity;
427 public int mType;
428 public RadioAttributes(String init) {
429 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700430 mType = Integer.parseInt(fragments[0]);
431 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700432 }
433 }
434 RadioAttributes[] mRadioAttributes;
435
Robert Greenwalt50393202011-06-21 17:26:14 -0700436 // the set of network types that can only be enabled by system/sig apps
437 List mProtectedNetworks;
438
John Spurlockbf991a82013-06-24 14:20:23 -0400439 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700440
Wink Savilleab9321d2013-06-29 21:10:57 -0700441 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
442
443 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400444
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700445 public ConnectivityService(Context context, INetworkManagementService netd,
446 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700447 // Currently, omitting a NetworkFactory will create one internally
448 // TODO: create here when we have cleaner WiMAX support
449 this(context, netd, statsService, policyManager, null);
450 }
451
Jeff Sharkey899223b2012-08-04 15:24:58 -0700452 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700453 INetworkStatsService statsService, INetworkPolicyManager policyManager,
454 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800455 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800456
Wink Savillebb08caf2010-09-02 19:23:52 -0700457 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
458 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700459 mHandler = new InternalHandler(handlerThread.getLooper());
460 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700461
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700462 if (netFactory == null) {
463 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
464 }
465
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800466 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800467 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
468 String id = Settings.Secure.getString(context.getContentResolver(),
469 Settings.Secure.ANDROID_ID);
470 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700471 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800472 SystemProperties.set("net.hostname", name);
473 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800474 }
475
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700476 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700477 String dns = Settings.Global.getString(context.getContentResolver(),
478 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700479 if (dns == null || dns.length() == 0) {
480 dns = context.getResources().getString(
481 com.android.internal.R.string.config_default_dns_server);
482 }
483 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800484 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
485 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800486 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700487 }
488
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700489 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700490 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700491 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700492 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700493 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700494
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700495 try {
496 mPolicyManager.registerListener(mPolicyListener);
497 } catch (RemoteException e) {
498 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700499 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700500 }
501
502 final PowerManager powerManager = (PowerManager) context.getSystemService(
503 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700504 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
505 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
506 com.android.internal.R.integer.config_networkTransitionTimeout);
507
Robert Greenwalt42acef32009-08-12 16:08:25 -0700508 mNetTrackers = new NetworkStateTracker[
509 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700510 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700511
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700512 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700513 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700514
Robert Greenwalt42acef32009-08-12 16:08:25 -0700515 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700516 String[] raStrings = context.getResources().getStringArray(
517 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700518 for (String raString : raStrings) {
519 RadioAttributes r = new RadioAttributes(raString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700520 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700521 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800522 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700523 continue;
524 }
525 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800526 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700527 r.mType);
528 continue;
529 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700530 mRadioAttributes[r.mType] = r;
531 }
532
Wink Saville51f456f2013-04-23 14:26:51 -0700533 // TODO: What is the "correct" way to do determine if this is a wifi only device?
534 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
535 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700536 String[] naStrings = context.getResources().getStringArray(
537 com.android.internal.R.array.networkAttributes);
538 for (String naString : naStrings) {
539 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700540 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700541 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700542 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800543 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700544 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700545 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700546 }
Wink Saville51f456f2013-04-23 14:26:51 -0700547 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
548 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
549 n.type);
550 continue;
551 }
Wink Saville975c8482011-04-07 14:23:45 -0700552 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800553 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700554 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700555 continue;
556 }
Wink Saville975c8482011-04-07 14:23:45 -0700557 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800558 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700559 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700560 continue;
561 }
Wink Saville975c8482011-04-07 14:23:45 -0700562 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700563 mNetworksDefined++;
564 } catch(Exception e) {
565 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700566 }
567 }
Wink Saville5e56bc52013-07-29 15:00:57 -0700568 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700569
Robert Greenwalt50393202011-06-21 17:26:14 -0700570 mProtectedNetworks = new ArrayList<Integer>();
571 int[] protectedNetworks = context.getResources().getIntArray(
572 com.android.internal.R.array.config_protectedNetworks);
573 for (int p : protectedNetworks) {
574 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
575 mProtectedNetworks.add(p);
576 } else {
577 if (DBG) loge("Ignoring protectedNetwork " + p);
578 }
579 }
580
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700581 // high priority first
582 mPriorityList = new int[mNetworksDefined];
583 {
584 int insertionPoint = mNetworksDefined-1;
585 int currentLowest = 0;
586 int nextLowest = 0;
587 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700588 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700589 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700590 if (na.priority < currentLowest) continue;
591 if (na.priority > currentLowest) {
592 if (na.priority < nextLowest || nextLowest == 0) {
593 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700594 }
595 continue;
596 }
Wink Saville975c8482011-04-07 14:23:45 -0700597 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700598 }
599 currentLowest = nextLowest;
600 nextLowest = 0;
601 }
602 }
603
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800604 // Update mNetworkPreference according to user mannually first then overlay config.xml
605 mNetworkPreference = getPersistedNetworkPreference();
606 if (mNetworkPreference == -1) {
607 for (int n : mPriorityList) {
608 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
609 mNetworkPreference = n;
610 break;
611 }
612 }
613 if (mNetworkPreference == -1) {
614 throw new IllegalStateException(
615 "You should set at least one default Network in config.xml!");
616 }
617 }
618
Mattias Falk8b47b362011-08-23 14:15:13 +0200619 mNetRequestersPids =
620 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700621 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200622 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700623 }
624
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500625 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700626
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700627 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
628 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700629
630 // Create and start trackers for hard-coded networks
631 for (int targetNetworkType : mPriorityList) {
632 final NetworkConfig config = mNetConfigs[targetNetworkType];
633 final NetworkStateTracker tracker;
634 try {
635 tracker = netFactory.createTracker(targetNetworkType, config);
636 mNetTrackers[targetNetworkType] = tracker;
637 } catch (IllegalArgumentException e) {
638 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
639 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700640 continue;
641 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700642
643 tracker.startMonitoring(context, mTrackerHandler);
644 if (config.isDefault()) {
645 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800646 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700647 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800648
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700649 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800650
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700651 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700652 IntentFilter intentFilter = new IntentFilter();
653 intentFilter.addAction(Intent.ACTION_USER_STARTING);
654 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
655 mContext.registerReceiverAsUser(
656 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900657 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
658
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700659 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700660 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700661 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900662 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700663 } catch (RemoteException e) {
664 loge("Error registering observer :" + e);
665 }
666
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700667 if (DBG) {
668 mInetLog = new ArrayList();
669 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700670
671 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
672 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800673
John Spurlockbf991a82013-06-24 14:20:23 -0400674 mDataConnectionStats = new DataConnectionStats(mContext);
675 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400676
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700677 // start network sampling ..
678 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
679 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -0700680 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700681
682 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
683 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
684
685 IntentFilter filter = new IntentFilter();
686 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
687 mContext.registerReceiver(
688 new BroadcastReceiver() {
689 @Override
690 public void onReceive(Context context, Intent intent) {
691 String action = intent.getAction();
692 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
693 mHandler.sendMessage(mHandler.obtainMessage
694 (EVENT_SAMPLE_INTERVAL_ELAPSED));
695 }
696 }
697 },
698 new IntentFilter(filter));
699
Jason Monkdecd2952013-10-10 14:02:51 -0400700 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700701
702 filter = new IntentFilter();
Wink Saville948282b2013-08-29 08:55:16 -0700703 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
704 mContext.registerReceiver(mProvisioningReceiver, filter);
Chad Brubaker74f99a42014-03-13 18:18:40 +0000705
706 mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700708
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700709 /**
710 * Factory that creates {@link NetworkStateTracker} instances using given
711 * {@link NetworkConfig}.
712 */
713 public interface NetworkFactory {
714 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
715 }
716
717 private static class DefaultNetworkFactory implements NetworkFactory {
718 private final Context mContext;
719 private final Handler mTrackerHandler;
720
721 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
722 mContext = context;
723 mTrackerHandler = trackerHandler;
724 }
725
726 @Override
727 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
728 switch (config.radio) {
729 case TYPE_WIFI:
730 return new WifiStateTracker(targetNetworkType, config.name);
731 case TYPE_MOBILE:
732 return new MobileDataStateTracker(targetNetworkType, config.name);
733 case TYPE_DUMMY:
734 return new DummyDataStateTracker(targetNetworkType, config.name);
735 case TYPE_BLUETOOTH:
736 return BluetoothTetheringDataTracker.getInstance();
737 case TYPE_WIMAX:
738 return makeWimaxStateTracker(mContext, mTrackerHandler);
739 case TYPE_ETHERNET:
740 return EthernetDataTracker.getInstance();
Hui Lu1c5624a2014-01-15 11:05:36 -0500741 case TYPE_PROXY:
742 return new ProxyDataTracker();
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700743 default:
744 throw new IllegalArgumentException(
745 "Trying to create a NetworkStateTracker for an unknown radio type: "
746 + config.radio);
747 }
748 }
749 }
750
751 /**
752 * Loads external WiMAX library and registers as system service, returning a
753 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
754 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
755 */
756 private static NetworkStateTracker makeWimaxStateTracker(
757 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700758 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900759 DexClassLoader wimaxClassLoader;
760 Class wimaxStateTrackerClass = null;
761 Class wimaxServiceClass = null;
762 Class wimaxManagerClass;
763 String wimaxJarLocation;
764 String wimaxLibLocation;
765 String wimaxManagerClassName;
766 String wimaxServiceClassName;
767 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768
tk.mun148c7d02011-10-13 22:51:57 +0900769 NetworkStateTracker wimaxStateTracker = null;
770
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700771 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900772 com.android.internal.R.bool.config_wimaxEnabled);
773
774 if (isWimaxEnabled) {
775 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700776 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900777 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700778 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900779 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700780 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900781 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700782 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900783 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700784 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900785 com.android.internal.R.string.config_wimaxStateTrackerClassname);
786
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800787 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900788 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700789 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900790 wimaxLibLocation, ClassLoader.getSystemClassLoader());
791
792 try {
793 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
794 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
795 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
796 } catch (ClassNotFoundException ex) {
797 loge("Exception finding Wimax classes: " + ex.toString());
798 return null;
799 }
800 } catch(Resources.NotFoundException ex) {
801 loge("Wimax Resources does not exist!!! ");
802 return null;
803 }
804
805 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800806 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900807
808 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
809 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700810 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
811 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900812
813 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
814 (new Class[] {Context.class, wimaxStateTrackerClass});
815 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700816 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900817 wmxSrvConst.setAccessible(false);
818
819 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
820
821 } catch(Exception ex) {
822 loge("Exception creating Wimax classes: " + ex.toString());
823 return null;
824 }
825 } else {
826 loge("Wimax is not enabled or not added to the network attributes!!! ");
827 return null;
828 }
829
830 return wimaxStateTracker;
831 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700834 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 * @param preference the new preference
836 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700837 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700839
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700840 mHandler.sendMessage(
841 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
844 public int getNetworkPreference() {
845 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700846 int preference;
847 synchronized(this) {
848 preference = mNetworkPreference;
849 }
850 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700853 private void handleSetNetworkPreference(int preference) {
854 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700855 mNetConfigs[preference] != null &&
856 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700857 if (mNetworkPreference != preference) {
858 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700859 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700860 synchronized(this) {
861 mNetworkPreference = preference;
862 }
863 enforcePreference();
864 }
865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700867
Wink Saville628b0852011-08-04 15:01:58 -0700868 private int getConnectivityChangeDelay() {
869 final ContentResolver cr = mContext.getContentResolver();
870
871 /** Check system properties for the default value then use secure settings value, if any. */
872 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700873 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
874 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
875 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700876 defaultDelay);
877 }
878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 private int getPersistedNetworkPreference() {
880 final ContentResolver cr = mContext.getContentResolver();
881
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700882 final int networkPrefSetting = Settings.Global
883 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800885 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700889 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 * In this method, we only tear down a non-preferred network. Establishing
891 * a connection to the preferred network is taken care of when we handle
892 * the disconnect event from the non-preferred network
893 * (see {@link #handleDisconnect(NetworkInfo)}).
894 */
895 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700896 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 return;
898
Robert Greenwalt42acef32009-08-12 16:08:25 -0700899 if (!mNetTrackers[mNetworkPreference].isAvailable())
900 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901
Robert Greenwalt42acef32009-08-12 16:08:25 -0700902 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700903 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700904 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700905 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800906 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700907 " in enforcePreference");
908 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700909 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911 }
912 }
913
914 private boolean teardown(NetworkStateTracker netTracker) {
915 if (netTracker.teardown()) {
916 netTracker.setTeardownRequested(true);
917 return true;
918 } else {
919 return false;
920 }
921 }
922
923 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700924 * Check if UID should be blocked from using the network represented by the
925 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700926 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700927 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
928 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700929
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930 final boolean networkCostly;
931 final int uidRules;
932 synchronized (mRulesLock) {
933 networkCostly = mMeteredIfaces.contains(iface);
934 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700935 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700936
937 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
938 return true;
939 }
940
941 // no restrictive rules; network is visible
942 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700943 }
944
945 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700946 * Return a filtered {@link NetworkInfo}, potentially marked
947 * {@link DetailedState#BLOCKED} based on
948 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700949 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700950 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
951 NetworkInfo info = tracker.getNetworkInfo();
952 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700953 // network is blocked; clone and override state
954 info = new NetworkInfo(info);
955 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700957 if (mLockdownTracker != null) {
958 info = mLockdownTracker.augmentNetworkInfo(info);
959 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700960 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 }
962
963 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 * Return NetworkInfo for the active (i.e., connected) network interface.
965 * It is assumed that at most one network is active at a time. If more
966 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700967 * @return the info for the active network, or {@code null} if none is
968 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700970 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 enforceAccessPermission();
973 final int uid = Binder.getCallingUid();
974 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976
Wink Saville948282b2013-08-29 08:55:16 -0700977 /**
978 * Find the first Provisioning network.
979 *
980 * @return NetworkInfo or null if none.
981 */
982 private NetworkInfo getProvisioningNetworkInfo() {
983 enforceAccessPermission();
984
985 // Find the first Provisioning Network
986 NetworkInfo provNi = null;
987 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700988 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700989 provNi = ni;
990 break;
991 }
992 }
993 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
994 return provNi;
995 }
996
997 /**
998 * Find the first Provisioning network or the ActiveDefaultNetwork
999 * if there is no Provisioning network
1000 *
1001 * @return NetworkInfo or null if none.
1002 */
1003 @Override
1004 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
1005 enforceAccessPermission();
1006
1007 NetworkInfo provNi = getProvisioningNetworkInfo();
1008 if (provNi == null) {
1009 final int uid = Binder.getCallingUid();
1010 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1011 }
1012 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1013 return provNi;
1014 }
1015
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001016 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1017 enforceAccessPermission();
1018 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1019 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1020 if (tracker != null) {
1021 return tracker.getNetworkInfo();
1022 }
1023 }
1024 return null;
1025 }
1026
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001027 @Override
1028 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1029 enforceConnectivityInternalPermission();
1030 return getNetworkInfo(mActiveDefaultNetwork, uid);
1031 }
1032
1033 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 public NetworkInfo getNetworkInfo(int networkType) {
1035 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001036 final int uid = Binder.getCallingUid();
1037 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1041 NetworkInfo info = null;
1042 if (isNetworkTypeValid(networkType)) {
1043 final NetworkStateTracker tracker = mNetTrackers[networkType];
1044 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001045 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
1047 }
1048 return info;
1049 }
1050
1051 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 public NetworkInfo[] getAllNetworkInfo() {
1053 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001055 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001056 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 for (NetworkStateTracker tracker : mNetTrackers) {
1058 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001059 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
1061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001063 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001066 @Override
1067 public boolean isNetworkSupported(int networkType) {
1068 enforceAccessPermission();
1069 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1070 }
1071
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001072 /**
1073 * Return LinkProperties for the active (i.e., connected) default
1074 * network interface. It is assumed that at most one default network
1075 * is active at a time. If more than one is active, it is indeterminate
1076 * which will be returned.
1077 * @return the ip properties for the active network, or {@code null} if
1078 * none is active
1079 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001080 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001081 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -07001082 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001083 }
1084
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001085 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001086 public LinkProperties getLinkProperties(int networkType) {
1087 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001088 if (isNetworkTypeValid(networkType)) {
1089 final NetworkStateTracker tracker = mNetTrackers[networkType];
1090 if (tracker != null) {
1091 return tracker.getLinkProperties();
1092 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001093 }
1094 return null;
1095 }
1096
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001097 @Override
1098 public NetworkState[] getAllNetworkState() {
1099 enforceAccessPermission();
1100 final int uid = Binder.getCallingUid();
1101 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001102 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001103 for (NetworkStateTracker tracker : mNetTrackers) {
1104 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001105 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001106 result.add(new NetworkState(
1107 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1108 }
1109 }
1110 }
1111 return result.toArray(new NetworkState[result.size()]);
1112 }
1113
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001114 private NetworkState getNetworkStateUnchecked(int networkType) {
1115 if (isNetworkTypeValid(networkType)) {
1116 final NetworkStateTracker tracker = mNetTrackers[networkType];
1117 if (tracker != null) {
1118 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1119 tracker.getLinkCapabilities());
1120 }
1121 }
1122 return null;
1123 }
1124
1125 @Override
1126 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1127 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001128
1129 final long token = Binder.clearCallingIdentity();
1130 try {
1131 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1132 if (state != null) {
1133 try {
1134 return mPolicyManager.getNetworkQuotaInfo(state);
1135 } catch (RemoteException e) {
1136 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001137 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001138 return null;
1139 } finally {
1140 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001141 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001142 }
1143
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001144 @Override
1145 public boolean isActiveNetworkMetered() {
1146 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001147 final long token = Binder.clearCallingIdentity();
1148 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001149 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001150 } finally {
1151 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001152 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001153 }
1154
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001155 private boolean isNetworkMeteredUnchecked(int networkType) {
1156 final NetworkState state = getNetworkStateUnchecked(networkType);
1157 if (state != null) {
1158 try {
1159 return mPolicyManager.isNetworkMetered(state);
1160 } catch (RemoteException e) {
1161 }
1162 }
1163 return false;
1164 }
1165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 public boolean setRadios(boolean turnOn) {
1167 boolean result = true;
1168 enforceChangePermission();
1169 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001170 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172 return result;
1173 }
1174
1175 public boolean setRadio(int netType, boolean turnOn) {
1176 enforceChangePermission();
1177 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1178 return false;
1179 }
1180 NetworkStateTracker tracker = mNetTrackers[netType];
1181 return tracker != null && tracker.setRadio(turnOn);
1182 }
1183
Jeff Sharkey216c1812012-08-05 14:29:23 -07001184 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1185 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001186 public void interfaceClassDataActivityChanged(String label, boolean active) {
1187 int deviceType = Integer.parseInt(label);
1188 sendDataActivityBroadcast(deviceType, active);
1189 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001190 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001191
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001192 /**
1193 * Used to notice when the calling process dies so we can self-expire
1194 *
1195 * Also used to know if the process has cleaned up after itself when
1196 * our auto-expire timer goes off. The timer has a link to an object.
1197 *
1198 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001199 private class FeatureUser implements IBinder.DeathRecipient {
1200 int mNetworkType;
1201 String mFeature;
1202 IBinder mBinder;
1203 int mPid;
1204 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001205 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001206
1207 FeatureUser(int type, String feature, IBinder binder) {
1208 super();
1209 mNetworkType = type;
1210 mFeature = feature;
1211 mBinder = binder;
1212 mPid = getCallingPid();
1213 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001214 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001215
Robert Greenwalt42acef32009-08-12 16:08:25 -07001216 try {
1217 mBinder.linkToDeath(this, 0);
1218 } catch (RemoteException e) {
1219 binderDied();
1220 }
1221 }
1222
1223 void unlinkDeathRecipient() {
1224 mBinder.unlinkToDeath(this, 0);
1225 }
1226
1227 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001228 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001229 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1230 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001231 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001232 }
1233
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001234 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001235 if (VDBG) {
1236 log("ConnectivityService FeatureUser expire(" +
1237 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1238 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1239 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001240 stopUsingNetworkFeature(this, false);
1241 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001242
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001243 public boolean isSameUser(FeatureUser u) {
1244 if (u == null) return false;
1245
1246 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1247 }
1248
1249 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1250 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1251 TextUtils.equals(mFeature, feature)) {
1252 return true;
1253 }
1254 return false;
1255 }
1256
Robert Greenwaltb9285352009-12-21 18:24:07 -08001257 public String toString() {
1258 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1259 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1260 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001261 }
1262
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001263 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001264 public int startUsingNetworkFeature(int networkType, String feature,
1265 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001266 long startTime = 0;
1267 if (DBG) {
1268 startTime = SystemClock.elapsedRealtime();
1269 }
Wink Savillec9acde92011-09-21 11:05:43 -07001270 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001271 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1272 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001275 try {
1276 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1277 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001278 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001279 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001280
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001281 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001282
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001283 // TODO - move this into individual networktrackers
1284 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001285
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001286 if (mLockdownEnabled) {
1287 // Since carrier APNs usually aren't available from VPN
1288 // endpoint, mark them as unavailable.
1289 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1290 }
1291
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001292 if (mProtectedNetworks.contains(usedNetworkType)) {
1293 enforceConnectivityInternalPermission();
1294 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001295
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001296 // if UID is restricted, don't allow them to bring up metered APNs
1297 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1298 final int uidRules;
1299 synchronized (mRulesLock) {
1300 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1301 }
1302 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001303 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001304 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001305
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001306 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1307 if (network != null) {
1308 Integer currentPid = new Integer(getCallingPid());
1309 if (usedNetworkType != networkType) {
1310 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001311
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001312 if (ni.isAvailable() == false) {
1313 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1314 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001315 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001316 } else {
1317 // else make the attempt anyway - probably giving REQUEST_STARTED below
1318 if (DBG) {
1319 log("special network not available, but try anyway ni=" +
1320 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001321 }
1322 }
1323 }
1324
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001325 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001326
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001327 synchronized(this) {
1328 boolean addToList = true;
1329 if (restoreTimer < 0) {
1330 // In case there is no timer is specified for the feature,
1331 // make sure we don't add duplicate entry with the same request.
1332 for (FeatureUser u : mFeatureUsers) {
1333 if (u.isSameUser(f)) {
1334 // Duplicate user is found. Do not add.
1335 addToList = false;
1336 break;
1337 }
1338 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001339 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001340
1341 if (addToList) mFeatureUsers.add(f);
1342 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1343 // this gets used for per-pid dns when connected
1344 mNetRequestersPids[usedNetworkType].add(currentPid);
1345 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001346 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001347
1348 if (restoreTimer >= 0) {
1349 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1350 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1351 }
1352
1353 if ((ni.isConnectedOrConnecting() == true) &&
1354 !network.isTeardownRequested()) {
1355 if (ni.isConnected() == true) {
1356 final long token = Binder.clearCallingIdentity();
1357 try {
1358 // add the pid-specific dns
1359 handleDnsConfigurationChange(usedNetworkType);
1360 if (VDBG) log("special network already active");
1361 } finally {
1362 Binder.restoreCallingIdentity(token);
1363 }
Wink Savillea639b312012-07-10 12:37:54 -07001364 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001365 }
1366 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001367 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001368 }
1369
1370 // check if the radio in play can make another contact
1371 // assume if cannot for now
1372
1373 if (DBG) {
1374 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1375 feature);
1376 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001377 if (network.reconnect()) {
Wink Saville948282b2013-08-29 08:55:16 -07001378 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001379 return PhoneConstants.APN_REQUEST_STARTED;
1380 } else {
Wink Saville948282b2013-08-29 08:55:16 -07001381 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001382 return PhoneConstants.APN_REQUEST_FAILED;
1383 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001384 } else {
1385 // need to remember this unsupported request so we respond appropriately on stop
1386 synchronized(this) {
1387 mFeatureUsers.add(f);
1388 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1389 // this gets used for per-pid dns when connected
1390 mNetRequestersPids[usedNetworkType].add(currentPid);
1391 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001392 }
Wink Saville948282b2013-08-29 08:55:16 -07001393 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001394 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001395 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001396 }
Wink Saville948282b2013-08-29 08:55:16 -07001397 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Savillea639b312012-07-10 12:37:54 -07001398 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001399 } finally {
1400 if (DBG) {
1401 final long execTime = SystemClock.elapsedRealtime() - startTime;
1402 if (execTime > 250) {
1403 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1404 } else {
1405 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1406 }
1407 }
1408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
1410
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001411 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001413 enforceChangePermission();
1414
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001415 int pid = getCallingPid();
1416 int uid = getCallingUid();
1417
1418 FeatureUser u = null;
1419 boolean found = false;
1420
1421 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001422 for (FeatureUser x : mFeatureUsers) {
1423 if (x.isSameUser(pid, uid, networkType, feature)) {
1424 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001425 found = true;
1426 break;
1427 }
1428 }
1429 }
1430 if (found && u != null) {
Wink Saville948282b2013-08-29 08:55:16 -07001431 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001432 // stop regardless of how many other time this proc had called start
1433 return stopUsingNetworkFeature(u, true);
1434 } else {
1435 // none found!
Wink Saville948282b2013-08-29 08:55:16 -07001436 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001437 return 1;
1438 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001439 }
1440
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001441 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1442 int networkType = u.mNetworkType;
1443 String feature = u.mFeature;
1444 int pid = u.mPid;
1445 int uid = u.mUid;
1446
1447 NetworkStateTracker tracker = null;
1448 boolean callTeardown = false; // used to carry our decision outside of sync block
1449
Wink Savillec9acde92011-09-21 11:05:43 -07001450 if (VDBG) {
1451 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001452 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001455 if (DBG) {
1456 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1457 ", net is invalid");
1458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 return -1;
1460 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001461
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001462 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1463 // sync block
1464 synchronized(this) {
1465 // check if this process still has an outstanding start request
1466 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001467 if (VDBG) {
1468 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1469 ", ignoring");
1470 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001471 return 1;
1472 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001473 u.unlinkDeathRecipient();
1474 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1475 // If we care about duplicate requests, check for that here.
1476 //
1477 // This is done to support the extension of a request - the app
1478 // can request we start the network feature again and renew the
1479 // auto-shutoff delay. Normal "stop" calls from the app though
1480 // do not pay attention to duplicate requests - in effect the
1481 // API does not refcount and a single stop will counter multiple starts.
1482 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001483 for (FeatureUser x : mFeatureUsers) {
1484 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001485 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001486 return 1;
1487 }
1488 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001489 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001490
repo syncaea743a2011-07-29 23:55:49 -07001491 // TODO - move to individual network trackers
1492 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1493
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001494 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001495 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001496 if (DBG) {
1497 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1498 " no known tracker for used net type " + usedNetworkType);
1499 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001500 return -1;
1501 }
1502 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001503 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001504 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001505
1506 final long token = Binder.clearCallingIdentity();
1507 try {
1508 reassessPidDns(pid, true);
1509 } finally {
1510 Binder.restoreCallingIdentity(token);
1511 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001512 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001513 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001514 if (VDBG) {
1515 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1516 " others still using it");
1517 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001518 return 1;
1519 }
1520 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001521 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001522 if (DBG) {
1523 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1524 " not a known feature - dropping");
1525 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001526 }
1527 }
Wink Savillec9acde92011-09-21 11:05:43 -07001528
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001529 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001530 if (DBG) {
1531 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1532 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001533 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001534 return 1;
1535 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001536 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539
1540 /**
Chad Brubaker74f99a42014-03-13 18:18:40 +00001541 * Check if the address falls into any of currently running VPN's route's.
1542 */
1543 private boolean isAddressUnderVpn(InetAddress address) {
1544 synchronized (mVpns) {
1545 synchronized (mRoutesLock) {
1546 int uid = UserHandle.getCallingUserId();
1547 Vpn vpn = mVpns.get(uid);
1548 if (vpn == null) {
1549 return false;
1550 }
1551
1552 // Check if an exemption exists for this address.
1553 for (LinkAddress destination : mExemptAddresses) {
1554 if (!NetworkUtils.addressTypeMatches(address, destination.getAddress())) {
1555 continue;
1556 }
1557
1558 int prefix = destination.getNetworkPrefixLength();
1559 InetAddress addrMasked = NetworkUtils.getNetworkPart(address, prefix);
1560 InetAddress destMasked = NetworkUtils.getNetworkPart(destination.getAddress(),
1561 prefix);
1562
1563 if (addrMasked.equals(destMasked)) {
1564 return false;
1565 }
1566 }
1567
1568 // Finally check if the address is covered by the VPN.
1569 return vpn.isAddressCovered(address);
1570 }
1571 }
1572 }
1573
1574 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001575 * @deprecated use requestRouteToHostAddress instead
1576 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 * Ensure that a network route exists to deliver traffic to the specified
1578 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001579 * @param networkType the type of the network over which traffic to the
1580 * specified host is to be routed
1581 * @param hostAddress the IP address of the host to which the route is
1582 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 * @return {@code true} on success, {@code false} on failure
1584 */
Chad Brubakerf5729a62014-03-13 18:18:36 +00001585 public boolean requestRouteToHost(int networkType, int hostAddress, String packageName) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001586 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1587
1588 if (inetAddress == null) {
1589 return false;
1590 }
1591
Chad Brubakerf5729a62014-03-13 18:18:36 +00001592 return requestRouteToHostAddress(networkType, inetAddress.getAddress(), packageName);
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001593 }
1594
1595 /**
1596 * Ensure that a network route exists to deliver traffic to the specified
1597 * host via the specified network interface.
1598 * @param networkType the type of the network over which traffic to the
1599 * specified host is to be routed
1600 * @param hostAddress the IP address of the host to which the route is
1601 * desired
1602 * @return {@code true} on success, {@code false} on failure
1603 */
Chad Brubakerf5729a62014-03-13 18:18:36 +00001604 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
1605 String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001607 if (mProtectedNetworks.contains(networkType)) {
1608 enforceConnectivityInternalPermission();
1609 }
Chad Brubaker74f99a42014-03-13 18:18:40 +00001610 boolean exempt;
1611 InetAddress addr;
1612 try {
1613 addr = InetAddress.getByAddress(hostAddress);
1614 } catch (UnknownHostException e) {
1615 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1616 return false;
1617 }
1618 // System apps may request routes bypassing the VPN to keep other networks working.
1619 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1620 exempt = true;
1621 } else {
1622 mAppOpsManager.checkPackage(Binder.getCallingUid(), packageName);
1623 try {
1624 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName,
1625 0);
1626 exempt = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
1627 } catch (NameNotFoundException e) {
1628 throw new IllegalArgumentException("Failed to find calling package details", e);
1629 }
1630 }
1631
1632 // Non-exempt routeToHost's can only be added if the host is not covered by the VPN.
1633 // This can be either because the VPN's routes do not cover the destination or a
1634 // system application added an exemption that covers this destination.
1635 if (!exempt && isAddressUnderVpn(addr)) {
1636 return false;
1637 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001640 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 return false;
1642 }
1643 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter151d3032013-11-07 22:08:24 -08001644 DetailedState netState = DetailedState.DISCONNECTED;
1645 if (tracker != null) {
1646 netState = tracker.getNetworkInfo().getDetailedState();
1647 }
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001648
Ken Mixter151d3032013-11-07 22:08:24 -08001649 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriffda6da092012-08-16 12:49:23 -07001650 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001651 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001652 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001653 log("requestRouteToHostAddress on down network "
1654 + "(" + networkType + ") - dropped"
1655 + " tracker=" + tracker
1656 + " netState=" + netState
1657 + " isTeardownRequested="
1658 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001659 }
1660 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001662 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001663 try {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001664 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker74f99a42014-03-13 18:18:40 +00001665 boolean ok = addRouteToAddress(lp, addr, exempt);
Wink Savilleab9321d2013-06-29 21:10:57 -07001666 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1667 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001668 } finally {
1669 Binder.restoreCallingIdentity(token);
1670 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671 }
1672
Chad Brubakerf336d722013-07-15 16:34:04 -07001673 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1674 boolean exempt) {
1675 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001676 }
1677
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001678 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001679 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001680 }
1681
Chad Brubakerf336d722013-07-15 16:34:04 -07001682 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1683 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001684 }
1685
1686 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001687 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001688 }
1689
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001690 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubakerf336d722013-07-15 16:34:04 -07001691 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001692 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001693 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001694 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001695 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001696 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001697 if (bestRoute.getGateway().equals(addr)) {
1698 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001699 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001700 } else {
1701 // if we will connect to this through another route, add a direct route
1702 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001703 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001704 }
1705 }
Chad Brubakerf336d722013-07-15 16:34:04 -07001706 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001707 }
1708
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001709 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubakerf336d722013-07-15 16:34:04 -07001710 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001711 if ((lp == null) || (r == null)) {
1712 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001713 return false;
1714 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001715
1716 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001717 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001718 return false;
1719 }
1720
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001721 String ifaceName = r.getInterface();
1722 if(ifaceName == null) {
1723 loge("Error modifying route - no interface name");
1724 return false;
1725 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001726 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001727 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001728 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001729 if (bestRoute.getGateway().equals(r.getGateway())) {
1730 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001731 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001732 } else {
1733 // if we will connect to our gateway through another route, add a direct
1734 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001735 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1736 bestRoute.getGateway(),
1737 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001738 }
Chad Brubakerf336d722013-07-15 16:34:04 -07001739 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001740 }
1741 }
1742 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001743 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001744 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001745 if (toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001746 synchronized (mRoutesLock) {
1747 // only track default table - only one apps can effect
1748 mAddedRoutes.add(r);
1749 mNetd.addRoute(ifaceName, r);
1750 if (exempt) {
1751 LinkAddress dest = r.getDestination();
1752 if (!mExemptAddresses.contains(dest)) {
1753 mNetd.setHostExemption(dest);
1754 mExemptAddresses.add(dest);
1755 }
1756 }
1757 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001758 } else {
1759 mNetd.addSecondaryRoute(ifaceName, r);
1760 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001761 } catch (Exception e) {
1762 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001763 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001764 return false;
1765 }
1766 } else {
1767 // if we remove this one and there are no more like it, then refcount==0 and
1768 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001769 if (toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001770 synchronized (mRoutesLock) {
1771 mAddedRoutes.remove(r);
1772 if (mAddedRoutes.contains(r) == false) {
1773 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1774 try {
1775 mNetd.removeRoute(ifaceName, r);
1776 LinkAddress dest = r.getDestination();
1777 if (mExemptAddresses.contains(dest)) {
1778 mNetd.clearHostExemption(dest);
1779 mExemptAddresses.remove(dest);
1780 }
1781 } catch (Exception e) {
1782 // never crash - catch them all
1783 if (VDBG) loge("Exception trying to remove a route: " + e);
1784 return false;
1785 }
1786 } else {
1787 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001788 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001789 }
1790 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001791 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001792 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001793 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001794 } catch (Exception e) {
1795 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001796 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001797 return false;
1798 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001799 }
1800 }
1801 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803
1804 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001805 * @see ConnectivityManager#getMobileDataEnabled()
1806 */
1807 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001808 // TODO: This detail should probably be in DataConnectionTracker's
1809 // which is where we store the value and maybe make this
1810 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001811 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001812 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1813 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001814 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001815 return retVal;
1816 }
1817
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001818 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001819 enforceConnectivityInternalPermission();
1820
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001821 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1822 (met ? ENABLED : DISABLED), networkType));
1823 }
1824
1825 private void handleSetDependencyMet(int networkType, boolean met) {
1826 if (mNetTrackers[networkType] != null) {
1827 if (DBG) {
1828 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1829 }
1830 mNetTrackers[networkType].setDependencyMet(met);
1831 }
1832 }
1833
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001834 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1835 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001836 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001837 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001838 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001839 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001840 }
1841
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001842 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001843 // skip update when we've already applied rules
1844 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1845 if (oldRules == uidRules) return;
1846
1847 mUidRules.put(uid, uidRules);
1848 }
1849
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001850 // TODO: notify UID when it has requested targeted updates
1851 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001852
1853 @Override
1854 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001855 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001856 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001857 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001858 }
1859
1860 synchronized (mRulesLock) {
1861 mMeteredIfaces.clear();
1862 for (String iface : meteredIfaces) {
1863 mMeteredIfaces.add(iface);
1864 }
1865 }
1866 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001867
1868 @Override
1869 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1870 // caller is NPMS, since we only register with them
1871 if (LOGD_RULES) {
1872 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1873 }
1874
1875 // kick off connectivity change broadcast for active network, since
1876 // global background policy change is radical.
1877 final int networkType = mActiveDefaultNetwork;
1878 if (isNetworkTypeValid(networkType)) {
1879 final NetworkStateTracker tracker = mNetTrackers[networkType];
1880 if (tracker != null) {
1881 final NetworkInfo info = tracker.getNetworkInfo();
1882 if (info != null && info.isConnected()) {
1883 sendConnectedBroadcast(info);
1884 }
1885 }
1886 }
1887 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001888 };
1889
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001890 /**
1891 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1892 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001893 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001894 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001895 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001896
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001897 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001898 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001899 }
1900
1901 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001902 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001903 if (VDBG) {
1904 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001905 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001906 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1907 }
tk.munb97d34c2012-01-06 10:43:52 +09001908 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1909 if (VDBG) {
1910 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1911 }
1912 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1913 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001914 }
1915
1916 @Override
1917 public void setPolicyDataEnable(int networkType, boolean enabled) {
1918 // only someone like NPMS should only be calling us
1919 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1920
1921 mHandler.sendMessage(mHandler.obtainMessage(
1922 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1923 }
1924
1925 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1926 if (isNetworkTypeValid(networkType)) {
1927 final NetworkStateTracker tracker = mNetTrackers[networkType];
1928 if (tracker != null) {
1929 tracker.setPolicyDataEnable(enabled);
1930 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001931 }
1932 }
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001935 mContext.enforceCallingOrSelfPermission(
1936 android.Manifest.permission.ACCESS_NETWORK_STATE,
1937 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
1939
1940 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001941 mContext.enforceCallingOrSelfPermission(
1942 android.Manifest.permission.CHANGE_NETWORK_STATE,
1943 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001946 // TODO Make this a special check when it goes public
1947 private void enforceTetherChangePermission() {
1948 mContext.enforceCallingOrSelfPermission(
1949 android.Manifest.permission.CHANGE_NETWORK_STATE,
1950 "ConnectivityService");
1951 }
1952
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001953 private void enforceTetherAccessPermission() {
1954 mContext.enforceCallingOrSelfPermission(
1955 android.Manifest.permission.ACCESS_NETWORK_STATE,
1956 "ConnectivityService");
1957 }
1958
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001959 private void enforceConnectivityInternalPermission() {
1960 mContext.enforceCallingOrSelfPermission(
1961 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1962 "ConnectivityService");
1963 }
1964
Chad Brubakerd475c702013-07-11 13:29:30 -07001965 private void enforceMarkNetworkSocketPermission() {
1966 //Media server special case
1967 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1968 return;
1969 }
1970 mContext.enforceCallingOrSelfPermission(
1971 android.Manifest.permission.MARK_NETWORK_SOCKET,
1972 "ConnectivityService");
1973 }
1974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001976 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1977 * network, we ignore it. If it is for the active network, we send out a
1978 * broadcast. But first, we check whether it might be possible to connect
1979 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 * @param info the {@code NetworkInfo} for the network
1981 */
1982 private void handleDisconnect(NetworkInfo info) {
1983
Robert Greenwalt42acef32009-08-12 16:08:25 -07001984 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985
Robert Greenwalt42acef32009-08-12 16:08:25 -07001986 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001987
1988 // Remove idletimer previously setup in {@code handleConnect}
1989 removeDataActivityTracking(prevNetType);
1990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 /*
1992 * If the disconnected network is not the active one, then don't report
1993 * this as a loss of connectivity. What probably happened is that we're
1994 * getting the disconnect for a network that we explicitly disabled
1995 * in accordance with network preference policies.
1996 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001997 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001998 List<Integer> pids = mNetRequestersPids[prevNetType];
1999 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002000 // will remove them because the net's no longer connected
2001 // need to do this now as only now do we know the pids and
2002 // can properly null things that are no longer referenced.
2003 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002008 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002009 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 if (info.isFailover()) {
2011 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2012 info.setFailover(false);
2013 }
2014 if (info.getReason() != null) {
2015 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2016 }
2017 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002018 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2019 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002021
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002022 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002023 tryFailover(prevNetType);
2024 if (mActiveDefaultNetwork != -1) {
2025 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002026 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2027 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07002028 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002029 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2030 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002031 }
Robert Greenwalt029be812010-09-20 18:01:43 -07002032 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07002033
2034 // Reset interface if no other connections are using the same interface
2035 boolean doReset = true;
2036 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
2037 if (linkProperties != null) {
2038 String oldIface = linkProperties.getInterfaceName();
2039 if (TextUtils.isEmpty(oldIface) == false) {
2040 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
2041 if (networkStateTracker == null) continue;
2042 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
2043 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
2044 LinkProperties l = networkStateTracker.getLinkProperties();
2045 if (l == null) continue;
2046 if (oldIface.equals(l.getInterfaceName())) {
2047 doReset = false;
2048 break;
2049 }
2050 }
2051 }
2052 }
2053 }
2054
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002055 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07002056 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002057
Jeff Sharkey961e3042011-08-29 16:02:57 -07002058 final Intent immediateIntent = new Intent(intent);
2059 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2060 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07002061 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002062 /*
2063 * If the failover network is already connected, then immediately send
2064 * out a followup broadcast indicating successful failover
2065 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002066 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07002067 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
2068 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002069 }
2070 }
2071
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002072 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002073 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08002074 * If this is a default network, check if other defaults are available.
2075 * Try to reconnect on all available and let them hash it out when
2076 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07002077 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002078 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002079 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville948282b2013-08-29 08:55:16 -07002080 if (DBG) {
2081 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2082 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002083 mActiveDefaultNetwork = -1;
2084 }
2085
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002086 // don't signal a reconnect for anything lower or equal priority than our
2087 // current connected default
2088 // TODO - don't filter by priority now - nice optimization but risky
2089// int currentPriority = -1;
2090// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002091// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002092// }
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002093
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002094 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07002095 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002096 if (mNetConfigs[checkType] == null) continue;
2097 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08002098 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08002099
2100// Enabling the isAvailable() optimization caused mobile to not get
2101// selected if it was in the middle of error handling. Specifically
2102// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2103// would not be available and we wouldn't get connected to anything.
2104// So removing the isAvailable() optimization below for now. TODO: This
2105// optimization should work and we need to investigate why it doesn't work.
2106// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2107// complete before it is really complete.
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002108
Wink Saville9f7a0b22011-01-26 15:43:49 -08002109// if (!mNetTrackers[checkType].isAvailable()) continue;
2110
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002111// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002112
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002113 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2114 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2115 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2116 checkInfo.setFailover(true);
2117 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002118 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002119 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07002120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 }
2123
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002124 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002125 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07002126 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2127 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002128 }
2129
Wink Saville628b0852011-08-04 15:01:58 -07002130 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002131 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2132 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07002133 }
2134
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002135 private void sendInetConditionBroadcast(NetworkInfo info) {
2136 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2137 }
2138
Wink Saville628b0852011-08-04 15:01:58 -07002139 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002140 if (mLockdownTracker != null) {
2141 info = mLockdownTracker.augmentNetworkInfo(info);
2142 }
2143
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002144 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002145 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002146 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 if (info.isFailover()) {
2148 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2149 info.setFailover(false);
2150 }
2151 if (info.getReason() != null) {
2152 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2153 }
2154 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002155 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2156 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002158 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002159 return intent;
2160 }
2161
2162 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2163 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2164 }
2165
2166 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2167 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
2169
Haoyu Baidb3c8672012-06-20 14:29:57 -07002170 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2171 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2172 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2173 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002174 final long ident = Binder.clearCallingIdentity();
2175 try {
2176 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2177 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2178 } finally {
2179 Binder.restoreCallingIdentity(ident);
2180 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002181 }
2182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 /**
2184 * Called when an attempt to fail over to another network has failed.
2185 * @param info the {@link NetworkInfo} for the failed network
2186 */
2187 private void handleConnectionFailure(NetworkInfo info) {
2188 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189
Robert Greenwalt42acef32009-08-12 16:08:25 -07002190 String reason = info.getReason();
2191 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002192
Robert Greenwalt572172b2010-10-08 16:35:52 -07002193 String reasonText;
2194 if (reason == null) {
2195 reasonText = ".";
2196 } else {
2197 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002199 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002200
2201 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002202 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002203 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07002204 if (getActiveNetworkInfo() == null) {
2205 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2206 }
2207 if (reason != null) {
2208 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2209 }
2210 if (extraInfo != null) {
2211 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2212 }
2213 if (info.isFailover()) {
2214 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2215 info.setFailover(false);
2216 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002217
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002218 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002219 tryFailover(info.getType());
2220 if (mActiveDefaultNetwork != -1) {
2221 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002222 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2223 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07002224 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002225 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2226 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002227 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002228
Robert Greenwalt029be812010-09-20 18:01:43 -07002229 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07002230
2231 final Intent immediateIntent = new Intent(intent);
2232 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2233 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002234 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002235 /*
2236 * If the failover network is already connected, then immediately send
2237 * out a followup broadcast indicating successful failover
2238 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002239 if (mActiveDefaultNetwork != -1) {
2240 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002241 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002242 }
2243
2244 private void sendStickyBroadcast(Intent intent) {
2245 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002246 if (!mSystemReady) {
2247 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002248 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002249 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07002250 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002251 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002252 }
2253
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002254 final long ident = Binder.clearCallingIdentity();
2255 try {
2256 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2257 } finally {
2258 Binder.restoreCallingIdentity(ident);
2259 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002260 }
2261 }
2262
Wink Saville628b0852011-08-04 15:01:58 -07002263 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2264 if (delayMs <= 0) {
2265 sendStickyBroadcast(intent);
2266 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002267 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002268 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2269 + intent.getAction());
2270 }
Wink Saville628b0852011-08-04 15:01:58 -07002271 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2272 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2273 }
2274 }
2275
Mike Lockwood0f79b542009-08-14 14:18:49 -04002276 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07002277 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2278 loadGlobalProxy();
2279
Mike Lockwood0f79b542009-08-14 14:18:49 -04002280 synchronized(this) {
2281 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002282 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002283 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002284 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002285 }
2286 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002287 // load the global proxy at startup
2288 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002289
2290 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2291 // for user to unlock device.
2292 if (!updateLockdownVpn()) {
2293 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2294 mContext.registerReceiver(mUserPresentReceiver, filter);
2295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002298 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2299 @Override
2300 public void onReceive(Context context, Intent intent) {
2301 // Try creating lockdown tracker, since user present usually means
2302 // unlocked keystore.
2303 if (updateLockdownVpn()) {
2304 mContext.unregisterReceiver(this);
2305 }
2306 }
2307 };
2308
Irfan Sheriffda6da092012-08-16 12:49:23 -07002309 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville948282b2013-08-29 08:55:16 -07002310 if (((type != mNetworkPreference)
2311 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2312 || (mNetworkPreference == mActiveDefaultNetwork)) {
2313 return false;
2314 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002315 return true;
2316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317
Irfan Sheriffda6da092012-08-16 12:49:23 -07002318 private void handleConnect(NetworkInfo info) {
2319 final int newNetType = info.getType();
2320
2321 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 // snapshot isFailover, because sendConnectedBroadcast() resets it
2324 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002325 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002326 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327
Wink Saville948282b2013-08-29 08:55:16 -07002328 if (VDBG) {
2329 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2330 + " isFailover" + isFailover);
2331 }
2332
Robert Greenwalt42acef32009-08-12 16:08:25 -07002333 // if this is a default net and other default is running
2334 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002335 if (mNetConfigs[newNetType].isDefault()) {
2336 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2337 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002338 // tear down the other
2339 NetworkStateTracker otherNet =
2340 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002341 if (DBG) {
2342 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002343 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002344 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002345 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002346 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002347 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002348 return;
2349 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002350 } else {
2351 // don't accept this one
2352 if (VDBG) {
2353 log("Not broadcasting CONNECT_ACTION " +
2354 "to torn down network " + info.getTypeName());
2355 }
2356 teardown(thisNet);
2357 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002358 }
2359 }
2360 synchronized (ConnectivityService.this) {
2361 // have a new default network, release the transition wakelock in a second
2362 // if it's held. The second pause is to allow apps to reconnect over the
2363 // new network
2364 if (mNetTransitionWakeLock.isHeld()) {
2365 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002366 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002367 mNetTransitionWakeLockSerialNumber, 0),
2368 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002369 }
2370 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002371 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002372 // this will cause us to come up initially as unconnected and switching
2373 // to connected after our normal pause unless somebody reports us as reall
2374 // disconnected
2375 mDefaultInetConditionPublished = 0;
2376 mDefaultConnectionSequence++;
2377 mInetConditionChangeInFlight = false;
2378 // Don't do this - if we never sign in stay, grey
2379 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt30a2bc82014-02-28 16:44:00 -08002380 updateNetworkSettings(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 thisNet.setTeardownRequested(false);
sy.yun9d9b74a2013-09-02 05:24:09 +09002383 updateMtuSizeSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002384 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002385 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002386
2387 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002388 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002389 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002390 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002391 } catch (RemoteException e) {
2392 // ignored; service lives in system_server
2393 }
2394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396
Irfan Sheriffda6da092012-08-16 12:49:23 -07002397 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2398 if (DBG) log("Captive portal check " + info);
2399 int type = info.getType();
2400 final NetworkStateTracker thisNet = mNetTrackers[type];
2401 if (mNetConfigs[type].isDefault()) {
2402 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2403 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2404 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002405 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002406 return;
2407 } else {
2408 if (DBG) log("Tear down low priority net " + info.getTypeName());
2409 teardown(thisNet);
2410 return;
2411 }
2412 }
2413 }
2414
Wink Savilled747cbc2013-08-07 16:22:47 -07002415 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002416 thisNet.captivePortalCheckComplete();
2417 }
2418
2419 /** @hide */
Wink Savilled747cbc2013-08-07 16:22:47 -07002420 @Override
Irfan Sheriffda6da092012-08-16 12:49:23 -07002421 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002422 enforceConnectivityInternalPermission();
Wink Savilled747cbc2013-08-07 16:22:47 -07002423 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002424 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002425 }
2426
Wink Savilled747cbc2013-08-07 16:22:47 -07002427 /** @hide */
2428 @Override
2429 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2430 enforceConnectivityInternalPermission();
2431 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2432 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2433 }
2434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002436 * Setup data activity tracking for the given network interface.
2437 *
2438 * Every {@code setupDataActivityTracking} should be paired with a
2439 * {@link removeDataActivityTracking} for cleanup.
2440 */
2441 private void setupDataActivityTracking(int type) {
2442 final NetworkStateTracker thisNet = mNetTrackers[type];
2443 final String iface = thisNet.getLinkProperties().getInterfaceName();
2444
2445 final int timeout;
2446
2447 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002448 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2449 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002450 0);
2451 // Canonicalize mobile network type
2452 type = ConnectivityManager.TYPE_MOBILE;
2453 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002454 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2455 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002456 0);
2457 } else {
2458 // do not track any other networks
2459 timeout = 0;
2460 }
2461
2462 if (timeout > 0 && iface != null) {
2463 try {
2464 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2465 } catch (RemoteException e) {
2466 }
2467 }
2468 }
2469
2470 /**
2471 * Remove data activity tracking when network disconnects.
2472 */
2473 private void removeDataActivityTracking(int type) {
2474 final NetworkStateTracker net = mNetTrackers[type];
2475 final String iface = net.getLinkProperties().getInterfaceName();
2476
2477 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2478 ConnectivityManager.TYPE_WIFI == type)) {
2479 try {
2480 // the call fails silently if no idletimer setup for this interface
2481 mNetd.removeIdleTimer(iface);
2482 } catch (RemoteException e) {
2483 }
2484 }
2485 }
2486
2487 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002488 * After a change in the connectivity state of a network. We're mainly
2489 * concerned with making sure that the list of DNS servers is set up
2490 * according to which networks are connected, and ensuring that the
2491 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002493 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002494 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubakerf336d722013-07-15 16:34:04 -07002495 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville948282b2013-08-29 08:55:16 -07002496 if (VDBG) {
2497 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2498 + " resetMask=" + resetMask);
2499 }
Wink Savillee8222252011-07-13 13:44:13 -07002500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002502 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002503 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002505 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002506
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002507 LinkProperties curLp = mCurrentLinkProperties[netType];
2508 LinkProperties newLp = null;
2509
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002510 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002511 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002512 if (VDBG) {
2513 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2514 " doReset=" + doReset + " resetMask=" + resetMask +
2515 "\n curLp=" + curLp +
2516 "\n newLp=" + newLp);
2517 }
2518
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002519 if (curLp != null) {
2520 if (curLp.isIdenticalInterfaceName(newLp)) {
2521 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2522 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2523 for (LinkAddress linkAddr : car.removed) {
2524 if (linkAddr.getAddress() instanceof Inet4Address) {
2525 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2526 }
2527 if (linkAddr.getAddress() instanceof Inet6Address) {
2528 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2529 }
Wink Savillee8222252011-07-13 13:44:13 -07002530 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002531 if (DBG) {
2532 log("handleConnectivityChange: addresses changed" +
2533 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2534 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002535 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002536 } else {
2537 if (DBG) {
2538 log("handleConnectivityChange: address are the same reset per doReset" +
2539 " linkProperty[" + netType + "]:" +
2540 " resetMask=" + resetMask);
2541 }
Wink Savillee8222252011-07-13 13:44:13 -07002542 }
2543 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002544 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002545 if (DBG) {
2546 log("handleConnectivityChange: interface not not equivalent reset both" +
2547 " linkProperty[" + netType + "]:" +
2548 " resetMask=" + resetMask);
2549 }
Wink Savillee8222252011-07-13 13:44:13 -07002550 }
Wink Savillee8222252011-07-13 13:44:13 -07002551 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002552 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002553 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002554 }
2555 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002556 if (VDBG) {
2557 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2558 " doReset=" + doReset + " resetMask=" + resetMask +
2559 "\n curLp=" + curLp +
2560 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002563 mCurrentLinkProperties[netType] = newLp;
Chad Brubakerf336d722013-07-15 16:34:04 -07002564 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwaltec896c62011-06-15 12:22:07 -07002565
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002566 if (resetMask != 0 || resetDns) {
Wink Saville948282b2013-08-29 08:55:16 -07002567 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002568 if (curLp != null) {
Wink Saville948282b2013-08-29 08:55:16 -07002569 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002570 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002571 if (TextUtils.isEmpty(iface) == false) {
2572 if (resetMask != 0) {
2573 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2574 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002575
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002576 // Tell VPN the interface is down. It is a temporary
2577 // but effective fix to make VPN aware of the change.
2578 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002579 synchronized(mVpns) {
2580 for (int i = 0; i < mVpns.size(); i++) {
2581 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2582 }
2583 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002584 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002585 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002586 if (resetDns) {
2587 flushVmDnsCache();
2588 if (VDBG) log("resetting DNS cache for " + iface);
2589 try {
2590 mNetd.flushInterfaceDnsCache(iface);
2591 } catch (Exception e) {
2592 // never crash - catch them all
2593 if (DBG) loge("Exception resetting dns cache: " + e);
2594 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002595 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002596 } else {
2597 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002598 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002599 }
2600 }
2601 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002602
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002603 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002604 NetworkStateTracker tracker = mNetTrackers[netType];
2605 if (mClat.requiresClat(netType, tracker)) {
Wink Saville948282b2013-08-29 08:55:16 -07002606
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002607 // If the connection was previously using clat, but is not using it now, stop the clat
2608 // daemon. Normally, this happens automatically when the connection disconnects, but if
2609 // the disconnect is not reported, or if the connection's LinkProperties changed for
2610 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2611 // still be running. If it's not running, then stopping it is a no-op.
2612 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2613 mClat.stopClat();
2614 }
2615 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002616 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2617 mClat.startClat(tracker);
2618 } else {
2619 mClat.stopClat();
2620 }
2621 }
2622
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002623 // TODO: Temporary notifying upstread change to Tethering.
2624 // @see bug/4455071
2625 /** Notify TetheringService if interface name has been changed. */
2626 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002627 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002628 if (isTetheringSupported()) {
2629 mTethering.handleTetherIfaceChange();
2630 }
2631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 }
2633
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002634 /**
2635 * Add and remove routes using the old properties (null if not previously connected),
2636 * new properties (null if becoming disconnected). May even be double null, which
2637 * is a noop.
2638 * Uses isLinkDefault to determine if default routes should be set or conversely if
2639 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002640 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002641 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002642 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubakerf336d722013-07-15 16:34:04 -07002643 boolean isLinkDefault, boolean exempt) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002644 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002645 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2646 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002647 if (curLp != null) {
2648 // check for the delta between the current set and the new
Lorenzo Colittid1e0fae2013-07-31 23:23:21 +09002649 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002650 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002651 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002652 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002653 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002654 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002655
Robert Greenwaltf125a092011-08-15 12:31:55 -07002656 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2657
Robert Greenwaltad55d352011-07-22 11:55:33 -07002658 for (RouteInfo r : routeDiff.removed) {
2659 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville948282b2013-08-29 08:55:16 -07002660 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002661 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2662 }
2663 if (isLinkDefault == false) {
2664 // remove from a secondary route table
2665 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002666 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002667 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002668
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002669 if (!isLinkDefault) {
2670 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002671 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002672 // routes changed - remove all old dns entries and add new
2673 if (curLp != null) {
2674 for (InetAddress oldDns : curLp.getDnses()) {
2675 removeRouteToAddress(curLp, oldDns);
2676 }
2677 }
2678 if (newLp != null) {
2679 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002680 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002681 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002682 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002683 } else {
2684 // no change in routes, check for change in dns themselves
2685 for (InetAddress oldDns : dnsDiff.removed) {
2686 removeRouteToAddress(curLp, oldDns);
2687 }
2688 for (InetAddress newDns : dnsDiff.added) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002689 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002690 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002691 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002692 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002693
2694 for (RouteInfo r : routeDiff.added) {
2695 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002696 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002697 } else {
2698 // add to a secondary route table
Chad Brubakerf336d722013-07-15 16:34:04 -07002699 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002700
2701 // many radios add a default route even when we don't want one.
2702 // remove the default route unless somebody else has asked for it
2703 String ifaceName = newLp.getInterfaceName();
Chad Brubakerf336d722013-07-15 16:34:04 -07002704 synchronized (mRoutesLock) {
2705 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2706 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2707 try {
2708 mNetd.removeRoute(ifaceName, r);
2709 } catch (Exception e) {
2710 // never crash - catch them all
2711 if (DBG) loge("Exception trying to remove a route: " + e);
2712 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002713 }
2714 }
2715 }
2716 }
2717
Robert Greenwaltf125a092011-08-15 12:31:55 -07002718 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002719 }
2720
sy.yun9d9b74a2013-09-02 05:24:09 +09002721 /**
2722 * Reads the network specific MTU size from reources.
2723 * and set it on it's iface.
2724 */
2725 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2726 final String iface = nt.getLinkProperties().getInterfaceName();
2727 final int mtu = nt.getLinkProperties().getMtu();
2728
2729 if (mtu < 68 || mtu > 10000) {
2730 loge("Unexpected mtu value: " + nt);
2731 return;
2732 }
2733
2734 try {
2735 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2736 mNetd.setMtu(iface, mtu);
2737 } catch (Exception e) {
2738 Slog.e(TAG, "exception in setMtu()" + e);
2739 }
2740 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002741
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002742 /**
Irfan Sheriffd649c122010-06-09 15:39:36 -07002743 * Reads the network specific TCP buffer sizes from SystemProperties
2744 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2745 * wide use
2746 */
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002747 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002748 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002749 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002750
Jeff Sharkey899223b2012-08-04 15:24:58 -07002751 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002752 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002753
2754 // Setting to default values so we won't be stuck to previous values
2755 key = "net.tcp.buffersize.default";
2756 bufferSizes = SystemProperties.get(key);
2757 }
2758
2759 // Set values in kernel
2760 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002761 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002762 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002763 + "] which comes from [" + key + "]");
2764 }
2765 setBufferSize(bufferSizes);
2766 }
JP Abgrall4f261392014-03-14 16:28:09 +00002767
2768 final String defaultRwndKey = "net.tcp.default_init_rwnd";
2769 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
2770 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
2771 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
2772 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2773 if (rwndValue != 0) {
2774 SystemProperties.set(sysctlKey, rwndValue.toString());
2775 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002776 }
2777
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002778 /**
Irfan Sheriffd649c122010-06-09 15:39:36 -07002779 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2780 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2781 *
2782 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2783 * writeMin, writeInitial, writeMax"
2784 */
2785 private void setBufferSize(String bufferSizes) {
2786 try {
2787 String[] values = bufferSizes.split(",");
2788
2789 if (values.length == 6) {
2790 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002791 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2792 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2793 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2794 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2795 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2796 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002797 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002798 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002799 }
2800 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002801 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002802 }
2803 }
2804
Robert Greenwalt42acef32009-08-12 16:08:25 -07002805 /**
2806 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2807 * on the highest priority active net which this process requested.
2808 * If there aren't any, clear it out
2809 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002810 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002811 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002812 if (VDBG) log("reassessPidDns for pid " + pid);
2813 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002814 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002815 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002816 continue;
2817 }
2818 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002819 if (nt.getNetworkInfo().isConnected() &&
2820 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002821 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002822 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002823 if (mNetRequestersPids[i].contains(myPid)) {
2824 try {
2825 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2826 } catch (Exception e) {
2827 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002828 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002829 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002830 }
2831 }
2832 }
2833 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002834 try {
2835 mNetd.clearDnsInterfaceForPid(pid);
2836 } catch (Exception e) {
2837 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002838 }
2839 }
2840
Mattias Falk8b47b362011-08-23 14:15:13 +02002841 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002842 /*
2843 * Tell the VMs to toss their DNS caches
2844 */
2845 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2846 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002847 /*
2848 * Connectivity events can happen before boot has completed ...
2849 */
2850 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002851 final long ident = Binder.clearCallingIdentity();
2852 try {
2853 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2854 } finally {
2855 Binder.restoreCallingIdentity(ident);
2856 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002857 }
2858
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002859 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002860 private void updateDnsLocked(String network, String iface,
Chad Brubaker20a7e882013-07-23 17:13:36 -07002861 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002862 int last = 0;
2863 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002864 dnses = new ArrayList();
2865 dnses.add(mDefaultDns);
2866 if (DBG) {
2867 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002868 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002869 }
2870
Mattias Falk8b47b362011-08-23 14:15:13 +02002871 try {
2872 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker20a7e882013-07-23 17:13:36 -07002873 if (defaultDns) {
2874 mNetd.setDefaultInterfaceForDns(iface);
2875 }
2876
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002877 for (InetAddress dns : dnses) {
2878 ++last;
2879 String key = "net.dns" + last;
2880 String value = dns.getHostAddress();
2881 SystemProperties.set(key, value);
2882 }
2883 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2884 String key = "net.dns" + i;
2885 SystemProperties.set(key, "");
2886 }
2887 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002888 } catch (Exception e) {
Robert Greenwalt69887e82013-09-24 11:05:57 -07002889 loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002890 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002891 }
2892
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002893 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002894 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002895 NetworkStateTracker nt = mNetTrackers[netType];
2896 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002897 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002898 if (p == null) return;
2899 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002900 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002901 String network = nt.getNetworkInfo().getTypeName();
2902 synchronized (mDnsLock) {
Chad Brubakerb98703e2013-07-23 17:44:41 -07002903 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002904 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002905 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002906 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002907 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002908 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002909 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002910 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002911 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002912 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002913 List<Integer> pids = mNetRequestersPids[netType];
2914 for (Integer pid : pids) {
2915 try {
2916 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2917 } catch (Exception e) {
2918 Slog.e(TAG, "exception setting interface for pid: " + e);
2919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 }
2921 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002922 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002924 }
2925
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002926 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002927 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2928 NETWORK_RESTORE_DELAY_PROP_NAME);
2929 if(restoreDefaultNetworkDelayStr != null &&
2930 restoreDefaultNetworkDelayStr.length() != 0) {
2931 try {
2932 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2933 } catch (NumberFormatException e) {
2934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002936 // if the system property isn't set, use the value for the apn type
2937 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2938
2939 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2940 (mNetConfigs[networkType] != null)) {
2941 ret = mNetConfigs[networkType].restoreTime;
2942 }
2943 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945
2946 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002947 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2948 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002949 if (mContext.checkCallingOrSelfPermission(
2950 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002952 pw.println("Permission Denial: can't dump ConnectivityService " +
2953 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2954 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 return;
2956 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002957
2958 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002960 for (int i = 0; i < mNetTrackers.length; i++) {
2961 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002962 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002963 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2964 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002965 if (nst.getNetworkInfo().isConnected()) {
2966 pw.println("Active network: " + nst.getNetworkInfo().
2967 getTypeName());
2968 }
2969 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002970 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002971 pw.println(nst);
2972 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002973 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002976
2977 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002978 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002979 for (int net : mPriorityList) {
2980 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002981 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002982 pidString = pidString + pid.toString() + ", ";
2983 }
2984 pw.println(pidString);
2985 }
2986 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002987 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002988
2989 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002990 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002991 for (Object requester : mFeatureUsers) {
2992 pw.println(requester.toString());
2993 }
2994 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002995 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002996
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002997 synchronized (this) {
2998 pw.println("NetworkTranstionWakeLock is currently " +
2999 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
3000 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
3001 }
3002 pw.println();
3003
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003004 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003005
3006 if (mInetLog != null) {
3007 pw.println();
3008 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07003009 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003010 for(int i = 0; i < mInetLog.size(); i++) {
3011 pw.println(mInetLog.get(i));
3012 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07003013 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 }
3016
Robert Greenwalt42acef32009-08-12 16:08:25 -07003017 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003018 private class NetworkStateTrackerHandler extends Handler {
3019 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07003020 super(looper);
3021 }
3022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 @Override
3024 public void handleMessage(Message msg) {
3025 NetworkInfo info;
3026 switch (msg.what) {
Wink Saville948282b2013-08-29 08:55:16 -07003027 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08003029 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08003030
Wink Savillec9acde92011-09-21 11:05:43 -07003031 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville67c38212013-09-05 12:02:25 -07003032 (state == NetworkInfo.State.DISCONNECTED) ||
3033 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillec9acde92011-09-21 11:05:43 -07003034 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07003035 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08003036 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07003037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038
Wink Saville948282b2013-08-29 08:55:16 -07003039 // Since mobile has the notion of a network/apn that can be used for
3040 // provisioning we need to check every time we're connected as
3041 // CaptiveProtalTracker won't detected it because DCT doesn't report it
3042 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
3043 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
3044 // is received by MDST and sent here as EVENT_STATE_CHANGED.
3045 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillefde1ac92013-07-16 17:16:37 -07003046 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
3047 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Saville127beff2013-09-14 09:04:53 -07003048 && (((state == NetworkInfo.State.CONNECTED)
3049 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
3050 || info.isConnectedToProvisioningNetwork())) {
3051 log("ConnectivityChange checkMobileProvisioning for"
3052 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville948282b2013-08-29 08:55:16 -07003053 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillefde1ac92013-07-16 17:16:37 -07003054 }
3055
Jeff Sharkey2528b502012-11-09 15:57:02 -08003056 EventLogTags.writeConnectivityStateChanged(
3057 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07003058
3059 if (info.getDetailedState() ==
3060 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07003062 } else if (info.getDetailedState() ==
3063 DetailedState.CAPTIVE_PORTAL_CHECK) {
3064 handleCaptivePortalTrackerCheck(info);
Wink Saville67c38212013-09-05 12:02:25 -07003065 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -07003066 /**
3067 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
3068 * for now its an in between network, its a network that
3069 * is actually a default network but we don't want it to be
3070 * announced as such to keep background applications from
3071 * trying to use it. It turns out that some still try so we
3072 * take the additional step of clearing any default routes
3073 * to the link that may have incorrectly setup by the lower
3074 * levels.
3075 */
3076 LinkProperties lp = getLinkProperties(info.getType());
3077 if (DBG) {
3078 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3079 }
3080
3081 // Clear any default routes setup by the radio so
3082 // any activity by applications trying to use this
3083 // connection will fail until the provisioning network
3084 // is enabled.
3085 for (RouteInfo r : lp.getRoutes()) {
3086 removeRoute(lp, r, TO_DEFAULT_TABLE);
3087 }
Robert Greenwalt511288a2009-12-07 11:33:18 -08003088 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08003090 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07003092 // the logic here is, handle SUSPENDED the same as
3093 // DISCONNECTED. The only difference being we are
3094 // broadcasting an intent with NetworkInfo that's
3095 // suspended. This allows the applications an
3096 // opportunity to handle DISCONNECTED and SUSPENDED
3097 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08003099 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 handleConnect(info);
3101 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003102 if (mLockdownTracker != null) {
3103 mLockdownTracker.onNetworkInfoChanged(info);
3104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 break;
Wink Saville948282b2013-08-29 08:55:16 -07003106 }
3107 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07003108 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05003109 // TODO: Temporary allowing network configuration
3110 // change not resetting sockets.
3111 // @see bug/4455071
3112 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 break;
Wink Saville948282b2013-08-29 08:55:16 -07003114 }
3115 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltd14e1762012-08-20 11:15:39 -07003116 info = (NetworkInfo) msg.obj;
Wink Saville948282b2013-08-29 08:55:16 -07003117 int type = info.getType();
Robert Greenwalt30a2bc82014-02-28 16:44:00 -08003118 if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]);
Robert Greenwaltd14e1762012-08-20 11:15:39 -07003119 break;
Wink Saville948282b2013-08-29 08:55:16 -07003120 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003121 }
3122 }
3123 }
3124
3125 private class InternalHandler extends Handler {
3126 public InternalHandler(Looper looper) {
3127 super(looper);
3128 }
3129
3130 @Override
3131 public void handleMessage(Message msg) {
3132 NetworkInfo info;
3133 switch (msg.what) {
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003134 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003135 String causedBy = null;
3136 synchronized (ConnectivityService.this) {
3137 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3138 mNetTransitionWakeLock.isHeld()) {
3139 mNetTransitionWakeLock.release();
3140 causedBy = mNetTransitionWakeLockCausedBy;
3141 }
3142 }
3143 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003144 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003145 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003146 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003147 }
3148 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07003149 FeatureUser u = (FeatureUser)msg.obj;
3150 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003151 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003152 }
3153 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003154 int netType = msg.arg1;
3155 int condition = msg.arg2;
3156 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003157 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003158 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003159 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003160 int netType = msg.arg1;
3161 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00003162 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003163 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003164 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003165 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003166 int preference = msg.arg1;
3167 handleSetNetworkPreference(preference);
3168 break;
3169 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003170 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003171 boolean enabled = (msg.arg1 == ENABLED);
3172 handleSetMobileData(enabled);
3173 break;
3174 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003175 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003176 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003177 break;
3178 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003179 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003180 boolean met = (msg.arg1 == ENABLED);
3181 handleSetDependencyMet(msg.arg2, met);
3182 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003183 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003184 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07003185 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07003186 sendStickyBroadcast(intent);
3187 break;
3188 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003189 case EVENT_SET_POLICY_DATA_ENABLE: {
3190 final int networkType = msg.arg1;
3191 final boolean enabled = msg.arg2 == ENABLED;
3192 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003193 break;
3194 }
3195 case EVENT_VPN_STATE_CHANGED: {
3196 if (mLockdownTracker != null) {
3197 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3198 }
3199 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003200 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003201 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3202 int tag = mEnableFailFastMobileDataTag.get();
3203 if (msg.arg1 == tag) {
3204 MobileDataStateTracker mobileDst =
3205 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3206 if (mobileDst != null) {
3207 mobileDst.setEnableFailFastMobileData(msg.arg2);
3208 }
3209 } else {
3210 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3211 + " != tag:" + tag);
3212 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003213 break;
Wink Savilleab9321d2013-06-29 21:10:57 -07003214 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003215 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003216 handleNetworkSamplingTimeout();
3217 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003218 }
Jason Monkdecd2952013-10-10 14:02:51 -04003219 case EVENT_PROXY_HAS_CHANGED: {
3220 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3221 break;
3222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224 }
3225 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003226
3227 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08003228 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003229 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08003230
3231 if (isTetheringSupported()) {
3232 return mTethering.tether(iface);
3233 } else {
3234 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3235 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003236 }
3237
3238 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08003239 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003240 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08003241
3242 if (isTetheringSupported()) {
3243 return mTethering.untether(iface);
3244 } else {
3245 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3246 }
3247 }
3248
3249 // javadoc from interface
3250 public int getLastTetherError(String iface) {
3251 enforceTetherAccessPermission();
3252
3253 if (isTetheringSupported()) {
3254 return mTethering.getLastTetherError(iface);
3255 } else {
3256 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3257 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003258 }
3259
3260 // TODO - proper iface API for selection by property, inspection, etc
3261 public String[] getTetherableUsbRegexs() {
3262 enforceTetherAccessPermission();
3263 if (isTetheringSupported()) {
3264 return mTethering.getTetherableUsbRegexs();
3265 } else {
3266 return new String[0];
3267 }
3268 }
3269
3270 public String[] getTetherableWifiRegexs() {
3271 enforceTetherAccessPermission();
3272 if (isTetheringSupported()) {
3273 return mTethering.getTetherableWifiRegexs();
3274 } else {
3275 return new String[0];
3276 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003277 }
3278
Danica Chang6fdd0c62010-08-11 14:54:43 -07003279 public String[] getTetherableBluetoothRegexs() {
3280 enforceTetherAccessPermission();
3281 if (isTetheringSupported()) {
3282 return mTethering.getTetherableBluetoothRegexs();
3283 } else {
3284 return new String[0];
3285 }
3286 }
3287
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003288 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003289 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003290 if (isTetheringSupported()) {
3291 return mTethering.setUsbTethering(enable);
3292 } else {
3293 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3294 }
3295 }
3296
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003297 // TODO - move iface listing, queries, etc to new module
3298 // javadoc from interface
3299 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003300 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003301 return mTethering.getTetherableIfaces();
3302 }
3303
3304 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003305 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003306 return mTethering.getTetheredIfaces();
3307 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003308
Robert Greenwalt5a735062010-03-02 17:25:02 -08003309 public String[] getTetheringErroredIfaces() {
3310 enforceTetherAccessPermission();
3311 return mTethering.getErroredIfaces();
3312 }
3313
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003314 // if ro.tether.denied = true we default to no tethering
3315 // gservices could set the secure setting to 1 though to enable it on a build where it
3316 // had previously been turned off.
3317 public boolean isTetheringSupported() {
3318 enforceTetherAccessPermission();
3319 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003320 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3321 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003322 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3323 mTethering.getTetherableWifiRegexs().length != 0 ||
3324 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3325 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003326 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003327
3328 // An API NetworkStateTrackers can call when they lose their network.
3329 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3330 // whichever happens first. The timer is started by the first caller and not
3331 // restarted by subsequent callers.
3332 public void requestNetworkTransitionWakelock(String forWhom) {
3333 enforceConnectivityInternalPermission();
3334 synchronized (this) {
3335 if (mNetTransitionWakeLock.isHeld()) return;
3336 mNetTransitionWakeLockSerialNumber++;
3337 mNetTransitionWakeLock.acquire();
3338 mNetTransitionWakeLockCausedBy = forWhom;
3339 }
3340 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003341 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003342 mNetTransitionWakeLockSerialNumber, 0),
3343 mNetTransitionWakeLockTimeout);
3344 return;
3345 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003346
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003347 // 100 percent is full good, 0 is full bad.
3348 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003349 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003350 mContext.enforceCallingOrSelfPermission(
3351 android.Manifest.permission.STATUS_BAR,
3352 "ConnectivityService");
3353
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003354 if (DBG) {
3355 int pid = getCallingPid();
3356 int uid = getCallingUid();
3357 String s = pid + "(" + uid + ") reports inet is " +
3358 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3359 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3360 mInetLog.add(s);
3361 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3362 mInetLog.remove(0);
3363 }
3364 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003365 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003366 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3367 }
3368
3369 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003370 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003371 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003372 return;
3373 }
3374 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003375 if (DBG) log("handleInetConditionChange: net=" + netType +
3376 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003377 return;
3378 }
Wink Savillec9acde92011-09-21 11:05:43 -07003379 if (VDBG) {
3380 log("handleInetConditionChange: net=" +
3381 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003382 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003383 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003384 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003385 int delay;
3386 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003387 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003388 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003389 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003390 delay = Settings.Global.getInt(mContext.getContentResolver(),
3391 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003392 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003393 delay = Settings.Global.getInt(mContext.getContentResolver(),
3394 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003395 }
3396 mInetConditionChangeInFlight = true;
3397 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003398 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003399 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003400 // we've set the new condition, when this hold ends that will get picked up
3401 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003402 }
3403 }
3404
Wink Saville5b7573e2013-01-31 00:30:13 +00003405 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003406 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003407 log("handleInetConditionHoldEnd: net=" + netType +
3408 ", condition=" + mDefaultInetCondition +
3409 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003410 }
3411 mInetConditionChangeInFlight = false;
3412
3413 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003414 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003415 return;
3416 }
3417 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003418 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003419 return;
3420 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003421 // TODO: Figure out why this optimization sometimes causes a
3422 // change in mDefaultInetCondition to be missed and the
3423 // UI to not be updated.
3424 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3425 // if (DBG) log("no change in condition - aborting");
3426 // return;
3427 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003428 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3429 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003430 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003431 return;
3432 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003433 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003434 sendInetConditionBroadcast(networkInfo);
3435 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003436 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003437
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003438 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003439 // this information is already available as a world read/writable jvm property
3440 // so this API change wouldn't have a benifit. It also breaks the passing
3441 // of proxy info to all the JVMs.
3442 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003443 synchronized (mProxyLock) {
Jason Monk602b2322013-07-03 17:04:33 -04003444 ProxyProperties ret = mGlobalProxy;
3445 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3446 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003447 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003448 }
3449
3450 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003451 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003452
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003453 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 if (proxyProperties == mGlobalProxy) return;
3455 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3456 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3457
3458 String host = "";
3459 int port = 0;
3460 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003461 String pacFileUrl = "";
3462 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3463 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003464 if (!proxyProperties.isValid()) {
3465 if (DBG)
3466 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3467 return;
3468 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 mGlobalProxy = new ProxyProperties(proxyProperties);
3470 host = mGlobalProxy.getHost();
3471 port = mGlobalProxy.getPort();
3472 exclList = mGlobalProxy.getExclusionList();
Jason Monk602b2322013-07-03 17:04:33 -04003473 if (proxyProperties.getPacFileUrl() != null) {
3474 pacFileUrl = proxyProperties.getPacFileUrl();
3475 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 } else {
3477 mGlobalProxy = null;
3478 }
3479 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003480 final long token = Binder.clearCallingIdentity();
3481 try {
3482 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3483 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3484 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3485 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003486 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003487 } finally {
3488 Binder.restoreCallingIdentity(token);
3489 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003490 }
3491
3492 if (mGlobalProxy == null) {
3493 proxyProperties = mDefaultProxy;
3494 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003495 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003496 }
3497
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003498 private void loadGlobalProxy() {
3499 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003500 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3501 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3502 String exclList = Settings.Global.getString(res,
3503 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003504 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3505 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3506 ProxyProperties proxyProperties;
3507 if (!TextUtils.isEmpty(pacFileUrl)) {
3508 proxyProperties = new ProxyProperties(pacFileUrl);
3509 } else {
3510 proxyProperties = new ProxyProperties(host, port, exclList);
3511 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003512 if (!proxyProperties.isValid()) {
3513 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3514 return;
3515 }
3516
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003517 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003518 mGlobalProxy = proxyProperties;
3519 }
3520 }
3521 }
3522
Robert Greenwalt434203a2010-10-11 16:00:27 -07003523 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003524 // this information is already available as a world read/writable jvm property
3525 // so this API change wouldn't have a benifit. It also breaks the passing
3526 // of proxy info to all the JVMs.
3527 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003528 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003529 return mGlobalProxy;
3530 }
3531 }
3532
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003533 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003534 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3535 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003536 proxy = null;
3537 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003538 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003539 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003540 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003541 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003542 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3543 return;
3544 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003545 mDefaultProxy = proxy;
3546
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003547 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003548 if (!mDefaultProxyDisabled) {
3549 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003550 }
3551 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003552 }
3553
3554 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003555 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3556 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003557 if (!TextUtils.isEmpty(proxy)) {
3558 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003559 if (data.length == 0) {
3560 return;
3561 }
3562
Robert Greenwalt434203a2010-10-11 16:00:27 -07003563 String proxyHost = data[0];
3564 int proxyPort = 8080;
3565 if (data.length > 1) {
3566 try {
3567 proxyPort = Integer.parseInt(data[1]);
3568 } catch (NumberFormatException e) {
3569 return;
3570 }
3571 }
3572 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3573 setGlobalProxy(p);
3574 }
3575 }
3576
3577 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003578 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003579 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003580 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003581 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003582 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3583 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003584 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003585 final long ident = Binder.clearCallingIdentity();
3586 try {
3587 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3588 } finally {
3589 Binder.restoreCallingIdentity(ident);
3590 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003591 }
3592
3593 private static class SettingsObserver extends ContentObserver {
3594 private int mWhat;
3595 private Handler mHandler;
3596 SettingsObserver(Handler handler, int what) {
3597 super(handler);
3598 mHandler = handler;
3599 mWhat = what;
3600 }
3601
3602 void observe(Context context) {
3603 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003604 resolver.registerContentObserver(Settings.Global.getUriFor(
3605 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003606 }
3607
3608 @Override
3609 public void onChange(boolean selfChange) {
3610 mHandler.obtainMessage(mWhat).sendToTarget();
3611 }
3612 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003613
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003614 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003615 Slog.d(TAG, s);
3616 }
3617
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003618 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003619 Slog.e(TAG, s);
3620 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003621
repo syncaea743a2011-07-29 23:55:49 -07003622 int convertFeatureToNetworkType(int networkType, String feature) {
3623 int usedNetworkType = networkType;
3624
3625 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3626 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3627 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3628 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3629 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3630 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3631 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3632 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3633 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3634 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3635 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3636 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3637 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3638 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3639 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3640 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3641 } else {
3642 Slog.e(TAG, "Can't match any mobile netTracker!");
3643 }
3644 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3645 if (TextUtils.equals(feature, "p2p")) {
3646 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3647 } else {
3648 Slog.e(TAG, "Can't match any wifi netTracker!");
3649 }
3650 } else {
3651 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003652 }
repo syncaea743a2011-07-29 23:55:49 -07003653 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003654 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003655
3656 private static <T> T checkNotNull(T value, String message) {
3657 if (value == null) {
3658 throw new NullPointerException(message);
3659 }
3660 return value;
3661 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003662
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003663 /**
3664 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003665 * VpnBuilder and not available in ConnectivityManager. Permissions
3666 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003667 * @hide
3668 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003669 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003670 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003671 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003672 try {
3673 int type = mActiveDefaultNetwork;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003674 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003675 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003676 synchronized(mVpns) {
Chad Brubaker7c2b1622014-03-14 16:27:58 +00003677 mVpns.get(user).protect(socket);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003678 }
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003679 return true;
3680 }
3681 } catch (Exception e) {
3682 // ignore
3683 } finally {
3684 try {
3685 socket.close();
3686 } catch (Exception e) {
3687 // ignore
3688 }
3689 }
3690 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003691 }
3692
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003693 /**
3694 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003695 * and not available in ConnectivityManager. Permissions are checked
3696 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003697 * @hide
3698 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003699 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003700 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003701 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003702 int user = UserHandle.getUserId(Binder.getCallingUid());
3703 synchronized(mVpns) {
3704 return mVpns.get(user).prepare(oldPackage, newPackage);
3705 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003706 }
3707
Chad Brubakerd475c702013-07-11 13:29:30 -07003708 @Override
3709 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3710 enforceMarkNetworkSocketPermission();
3711 final long token = Binder.clearCallingIdentity();
3712 try {
3713 int mark = mNetd.getMarkForUid(uid);
3714 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3715 if (mark == -1) {
3716 mark = 0;
3717 }
3718 NetworkUtils.markSocket(socket.getFd(), mark);
3719 } catch (RemoteException e) {
3720 } finally {
3721 Binder.restoreCallingIdentity(token);
3722 }
3723 }
3724
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003725 /**
3726 * Configure a TUN interface and return its file descriptor. Parameters
3727 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003728 * and not available in ConnectivityManager. Permissions are checked in
3729 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003730 * @hide
3731 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003732 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003733 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003734 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003735 int user = UserHandle.getUserId(Binder.getCallingUid());
3736 synchronized(mVpns) {
3737 return mVpns.get(user).establish(config);
3738 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003739 }
3740
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003741 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003742 * Start legacy VPN, controlling native daemons as needed. Creates a
3743 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003744 */
3745 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003746 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003747 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003748 final LinkProperties egress = getActiveLinkProperties();
3749 if (egress == null) {
3750 throw new IllegalStateException("Missing active network connection");
3751 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003752 int user = UserHandle.getUserId(Binder.getCallingUid());
3753 synchronized(mVpns) {
3754 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3755 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003756 }
3757
3758 /**
3759 * Return the information of the ongoing legacy VPN. This method is used
3760 * by VpnSettings and not available in ConnectivityManager. Permissions
3761 * are checked in Vpn class.
3762 * @hide
3763 */
3764 @Override
3765 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003766 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003767 int user = UserHandle.getUserId(Binder.getCallingUid());
3768 synchronized(mVpns) {
3769 return mVpns.get(user).getLegacyVpnInfo();
3770 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003771 }
3772
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003773 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003774 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3775 * not available in ConnectivityManager.
3776 * Permissions are checked in Vpn class.
3777 * @hide
3778 */
3779 @Override
3780 public VpnConfig getVpnConfig() {
3781 int user = UserHandle.getUserId(Binder.getCallingUid());
3782 synchronized(mVpns) {
3783 return mVpns.get(user).getVpnConfig();
3784 }
3785 }
3786
3787 /**
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003788 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3789 * through NetworkStateTracker since it works differently. For example, it
3790 * needs to override DNS servers but never takes the default routes. It
3791 * relies on another data network, and it could keep existing connections
3792 * alive after reconnecting, switching between networks, or even resuming
3793 * from deep sleep. Calls from applications should be done synchronously
3794 * to avoid race conditions. As these are all hidden APIs, refactoring can
3795 * be done whenever a better abstraction is developed.
3796 */
3797 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003798 private VpnCallback() {
3799 }
3800
Jeff Sharkey899223b2012-08-04 15:24:58 -07003801 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003802 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003803 }
3804
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003805 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003806 if (dnsServers == null) {
3807 restore();
3808 return;
3809 }
3810
3811 // Convert DNS servers into addresses.
3812 List<InetAddress> addresses = new ArrayList<InetAddress>();
3813 for (String address : dnsServers) {
3814 // Double check the addresses and remove invalid ones.
3815 try {
3816 addresses.add(InetAddress.parseNumericAddress(address));
3817 } catch (Exception e) {
3818 // ignore
3819 }
3820 }
3821 if (addresses.isEmpty()) {
3822 restore();
3823 return;
3824 }
3825
3826 // Concatenate search domains into a string.
3827 StringBuilder buffer = new StringBuilder();
3828 if (searchDomains != null) {
3829 for (String domain : searchDomains) {
3830 buffer.append(domain).append(' ');
3831 }
3832 }
3833 String domains = buffer.toString().trim();
3834
3835 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003836 synchronized (mDnsLock) {
Chad Brubaker20a7e882013-07-23 17:13:36 -07003837 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003838 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003839
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003840 // Temporarily disable the default proxy (not global).
3841 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003842 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003843 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003844 sendProxyBroadcast(null);
3845 }
3846 }
3847
3848 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003849 }
3850
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003851 public void restore() {
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003852 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003853 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003854 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003855 sendProxyBroadcast(mDefaultProxy);
3856 }
3857 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003858 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003859
3860 public void protect(ParcelFileDescriptor socket) {
3861 try {
3862 final int mark = mNetd.getMarkForProtect();
3863 NetworkUtils.markSocket(socket.getFd(), mark);
3864 } catch (RemoteException e) {
3865 }
3866 }
3867
3868 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3869 for (RouteInfo route : routes) {
3870 try {
3871 mNetd.setMarkedForwardingRoute(interfaze, route);
3872 } catch (RemoteException e) {
3873 }
3874 }
3875 }
3876
3877 public void setMarkedForwarding(String interfaze) {
3878 try {
3879 mNetd.setMarkedForwarding(interfaze);
3880 } catch (RemoteException e) {
3881 }
3882 }
3883
3884 public void clearMarkedForwarding(String interfaze) {
3885 try {
3886 mNetd.clearMarkedForwarding(interfaze);
3887 } catch (RemoteException e) {
3888 }
3889 }
3890
Robert Greenwalt69887e82013-09-24 11:05:57 -07003891 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003892 int uidStart = uid * UserHandle.PER_USER_RANGE;
3893 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt69887e82013-09-24 11:05:57 -07003894 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003895 }
3896
Robert Greenwalt69887e82013-09-24 11:05:57 -07003897 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003898 int uidStart = uid * UserHandle.PER_USER_RANGE;
3899 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt69887e82013-09-24 11:05:57 -07003900 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003901 }
3902
Robert Greenwalt69887e82013-09-24 11:05:57 -07003903 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3904 boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003905 try {
3906 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt69887e82013-09-24 11:05:57 -07003907 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003908 } catch (RemoteException e) {
3909 }
3910
3911 }
3912
Robert Greenwalt69887e82013-09-24 11:05:57 -07003913 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3914 boolean forwardDns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003915 try {
3916 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt69887e82013-09-24 11:05:57 -07003917 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003918 } catch (RemoteException e) {
3919 }
3920
3921 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003922 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003923
3924 @Override
3925 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003926 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3927 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3928 return false;
3929 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003930
3931 // Tear down existing lockdown if profile was removed
3932 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3933 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003934 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003935 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3936 return false;
3937 }
3938
3939 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3940 final VpnProfile profile = VpnProfile.decode(
3941 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003942 int user = UserHandle.getUserId(Binder.getCallingUid());
3943 synchronized(mVpns) {
3944 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3945 profile));
3946 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003947 } else {
3948 setLockdownTracker(null);
3949 }
3950
3951 return true;
3952 }
3953
3954 /**
3955 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3956 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3957 */
3958 private void setLockdownTracker(LockdownVpnTracker tracker) {
3959 // Shutdown any existing tracker
3960 final LockdownVpnTracker existing = mLockdownTracker;
3961 mLockdownTracker = null;
3962 if (existing != null) {
3963 existing.shutdown();
3964 }
3965
3966 try {
3967 if (tracker != null) {
3968 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003969 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003970 mLockdownTracker = tracker;
3971 mLockdownTracker.init();
3972 } else {
3973 mNetd.setFirewallEnabled(false);
3974 }
3975 } catch (RemoteException e) {
3976 // ignored; NMS lives inside system_server
3977 }
3978 }
3979
3980 private void throwIfLockdownEnabled() {
3981 if (mLockdownEnabled) {
3982 throw new IllegalStateException("Unavailable in lockdown mode");
3983 }
3984 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003985
3986 public void supplyMessenger(int networkType, Messenger messenger) {
3987 enforceConnectivityInternalPermission();
3988
3989 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3990 mNetTrackers[networkType].supplyMessenger(messenger);
3991 }
3992 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003993
3994 public int findConnectionTypeForIface(String iface) {
3995 enforceConnectivityInternalPermission();
3996
3997 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3998 for (NetworkStateTracker tracker : mNetTrackers) {
3999 if (tracker != null) {
4000 LinkProperties lp = tracker.getLinkProperties();
4001 if (lp != null && iface.equals(lp.getInterfaceName())) {
4002 return tracker.getNetworkInfo().getType();
4003 }
4004 }
4005 }
4006 return ConnectivityManager.TYPE_NONE;
4007 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004008
4009 /**
4010 * Have mobile data fail fast if enabled.
4011 *
4012 * @param enabled DctConstants.ENABLED/DISABLED
4013 */
4014 private void setEnableFailFastMobileData(int enabled) {
4015 int tag;
4016
4017 if (enabled == DctConstants.ENABLED) {
4018 tag = mEnableFailFastMobileDataTag.incrementAndGet();
4019 } else {
4020 tag = mEnableFailFastMobileDataTag.get();
4021 }
4022 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
4023 enabled));
4024 }
4025
Wink Savilledce52cd2013-08-16 17:17:28 -07004026 private boolean isMobileDataStateTrackerReady() {
4027 MobileDataStateTracker mdst =
Wink Saville948282b2013-08-29 08:55:16 -07004028 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilledce52cd2013-08-16 17:17:28 -07004029 return (mdst != null) && (mdst.isReady());
4030 }
4031
Wink Saville948282b2013-08-29 08:55:16 -07004032 /**
4033 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
4034 */
4035
4036 /**
4037 * No connection was possible to the network.
Wink Saville4fea0412013-09-06 09:53:08 -07004038 * This is NOT a warm sim.
Wink Saville948282b2013-08-29 08:55:16 -07004039 */
Wink Saville4fea0412013-09-06 09:53:08 -07004040 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville948282b2013-08-29 08:55:16 -07004041
4042 /**
4043 * A connection was made to the internet, all is well.
Wink Saville4fea0412013-09-06 09:53:08 -07004044 * This is NOT a warm sim.
Wink Saville948282b2013-08-29 08:55:16 -07004045 */
Wink Saville4fea0412013-09-06 09:53:08 -07004046 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville948282b2013-08-29 08:55:16 -07004047
4048 /**
4049 * A connection was made but no dns server was available to resolve a name to address.
Wink Saville4fea0412013-09-06 09:53:08 -07004050 * This is NOT a warm sim since provisioning network is supported.
Wink Saville948282b2013-08-29 08:55:16 -07004051 */
Wink Saville4fea0412013-09-06 09:53:08 -07004052 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville948282b2013-08-29 08:55:16 -07004053
4054 /**
4055 * A connection was made but could not open a TCP connection.
Wink Saville4fea0412013-09-06 09:53:08 -07004056 * This is NOT a warm sim since provisioning network is supported.
Wink Saville948282b2013-08-29 08:55:16 -07004057 */
Wink Saville4fea0412013-09-06 09:53:08 -07004058 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
4059
4060 /**
4061 * A connection was made but there was a redirection, we appear to be in walled garden.
4062 * This is an indication of a warm sim on a mobile network such as T-Mobile.
4063 */
4064 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville948282b2013-08-29 08:55:16 -07004065
4066 /**
4067 * The mobile network is a provisioning network.
Wink Saville4fea0412013-09-06 09:53:08 -07004068 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville948282b2013-08-29 08:55:16 -07004069 */
Wink Saville4fea0412013-09-06 09:53:08 -07004070 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville948282b2013-08-29 08:55:16 -07004071
Wink Saville4fea0412013-09-06 09:53:08 -07004072 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville948282b2013-08-29 08:55:16 -07004073
Wink Savilleab9321d2013-06-29 21:10:57 -07004074 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004075 public int checkMobileProvisioning(int suggestedTimeOutMs) {
4076 int timeOutMs = -1;
4077 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4078 enforceConnectivityInternalPermission();
Wink Saville68e6c642013-07-02 10:55:14 -07004079
Wink Savilleab9321d2013-06-29 21:10:57 -07004080 final long token = Binder.clearCallingIdentity();
4081 try {
Wink Saville948282b2013-08-29 08:55:16 -07004082 timeOutMs = suggestedTimeOutMs;
4083 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4084 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4085 }
4086
4087 // Check that mobile networks are supported
4088 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4089 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4090 if (DBG) log("checkMobileProvisioning: X no mobile network");
4091 return timeOutMs;
4092 }
4093
4094 // If we're already checking don't do it again
4095 // TODO: Add a queue of results...
4096 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4097 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4098 return timeOutMs;
4099 }
4100
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004101 // Start off with mobile notification off
4102 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville948282b2013-08-29 08:55:16 -07004103
Wink Savilleab9321d2013-06-29 21:10:57 -07004104 CheckMp checkMp = new CheckMp(mContext, this);
4105 CheckMp.CallBack cb = new CheckMp.CallBack() {
4106 @Override
4107 void onComplete(Integer result) {
Wink Saville948282b2013-08-29 08:55:16 -07004108 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Savilleab9321d2013-06-29 21:10:57 -07004109 NetworkInfo ni =
4110 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4111 switch(result) {
Wink Saville948282b2013-08-29 08:55:16 -07004112 case CMP_RESULT_CODE_CONNECTABLE:
Wink Saville4fea0412013-09-06 09:53:08 -07004113 case CMP_RESULT_CODE_NO_CONNECTION:
4114 case CMP_RESULT_CODE_NO_DNS:
4115 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville948282b2013-08-29 08:55:16 -07004116 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Savilleab9321d2013-06-29 21:10:57 -07004117 break;
4118 }
Wink Saville948282b2013-08-29 08:55:16 -07004119 case CMP_RESULT_CODE_REDIRECTED: {
4120 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004121 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07004122 if (TextUtils.isEmpty(url)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004123 url = getMobileRedirectedProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07004124 }
4125 if (TextUtils.isEmpty(url) == false) {
Wink Saville948282b2013-08-29 08:55:16 -07004126 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004127 setProvNotificationVisible(true,
4128 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville948282b2013-08-29 08:55:16 -07004129 url);
Wink Savilleab9321d2013-06-29 21:10:57 -07004130 } else {
Wink Saville948282b2013-08-29 08:55:16 -07004131 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Savilleab9321d2013-06-29 21:10:57 -07004132 }
4133 break;
4134 }
Wink Saville4fea0412013-09-06 09:53:08 -07004135 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004136 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07004137 if (TextUtils.isEmpty(url) == false) {
Wink Saville948282b2013-08-29 08:55:16 -07004138 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004139 setProvNotificationVisible(true,
4140 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville948282b2013-08-29 08:55:16 -07004141 url);
Wink Savilleab9321d2013-06-29 21:10:57 -07004142 } else {
Wink Saville948282b2013-08-29 08:55:16 -07004143 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Savilleab9321d2013-06-29 21:10:57 -07004144 }
4145 break;
4146 }
4147 default: {
4148 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4149 break;
4150 }
4151 }
Wink Saville948282b2013-08-29 08:55:16 -07004152 mIsCheckingMobileProvisioning.set(false);
Wink Savilleab9321d2013-06-29 21:10:57 -07004153 }
4154 };
4155 CheckMp.Params params =
4156 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville948282b2013-08-29 08:55:16 -07004157 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Savilleab9321d2013-06-29 21:10:57 -07004158 checkMp.execute(params);
4159 } finally {
4160 Binder.restoreCallingIdentity(token);
Wink Saville948282b2013-08-29 08:55:16 -07004161 if (DBG) log("checkMobileProvisioning: X");
Wink Savilleab9321d2013-06-29 21:10:57 -07004162 }
4163 return timeOutMs;
4164 }
4165
4166 static class CheckMp extends
4167 AsyncTask<CheckMp.Params, Void, Integer> {
4168 private static final String CHECKMP_TAG = "CheckMp";
Wink Saville1d3a89e2013-10-31 06:35:22 -07004169
4170 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4171 private static boolean mTestingFailures;
4172
4173 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4174 private static final int MAX_LOOPS = 4;
4175
4176 // Number of milli-seconds to complete all of the retires
Wink Savilleab9321d2013-06-29 21:10:57 -07004177 public static final int MAX_TIMEOUT_MS = 60000;
Wink Saville1d3a89e2013-10-31 06:35:22 -07004178
4179 // The socket should retry only 5 seconds, the default is longer
Wink Savilleab9321d2013-06-29 21:10:57 -07004180 private static final int SOCKET_TIMEOUT_MS = 5000;
Wink Saville1d3a89e2013-10-31 06:35:22 -07004181
4182 // Sleep time for network errors
4183 private static final int NET_ERROR_SLEEP_SEC = 3;
4184
4185 // Sleep time for network route establishment
4186 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4187
4188 // Short sleep time for polling :(
4189 private static final int POLLING_SLEEP_SEC = 1;
4190
Wink Savilleab9321d2013-06-29 21:10:57 -07004191 private Context mContext;
4192 private ConnectivityService mCs;
4193 private TelephonyManager mTm;
4194 private Params mParams;
4195
4196 /**
4197 * Parameters for AsyncTask.execute
4198 */
4199 static class Params {
4200 private String mUrl;
4201 private long mTimeOutMs;
4202 private CallBack mCb;
4203
4204 Params(String url, long timeOutMs, CallBack cb) {
4205 mUrl = url;
4206 mTimeOutMs = timeOutMs;
4207 mCb = cb;
4208 }
4209
4210 @Override
4211 public String toString() {
4212 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4213 }
4214 }
4215
Wink Saville1d3a89e2013-10-31 06:35:22 -07004216 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4217 // issued by name or ip address, for Google its by name so when we construct
4218 // this HostnameVerifier we'll pass the original Uri and use it to verify
4219 // the host. If the host name in the original uril fails we'll test the
4220 // hostname parameter just incase things change.
4221 static class CheckMpHostnameVerifier implements HostnameVerifier {
4222 Uri mOrgUri;
4223
4224 CheckMpHostnameVerifier(Uri orgUri) {
4225 mOrgUri = orgUri;
4226 }
4227
4228 @Override
4229 public boolean verify(String hostname, SSLSession session) {
4230 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4231 String orgUriHost = mOrgUri.getHost();
4232 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4233 if (DBG) {
4234 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4235 + " orgUriHost=" + orgUriHost);
4236 }
4237 return retVal;
4238 }
4239 }
4240
Wink Savilleab9321d2013-06-29 21:10:57 -07004241 /**
4242 * The call back object passed in Params. onComplete will be called
4243 * on the main thread.
4244 */
4245 abstract static class CallBack {
4246 // Called on the main thread.
4247 abstract void onComplete(Integer result);
4248 }
4249
4250 public CheckMp(Context context, ConnectivityService cs) {
Wink Saville1d3a89e2013-10-31 06:35:22 -07004251 if (Build.IS_DEBUGGABLE) {
4252 mTestingFailures =
4253 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4254 } else {
4255 mTestingFailures = false;
4256 }
4257
Wink Savilleab9321d2013-06-29 21:10:57 -07004258 mContext = context;
4259 mCs = cs;
4260
4261 // Setup access to TelephonyService we'll be using.
4262 mTm = (TelephonyManager) mContext.getSystemService(
4263 Context.TELEPHONY_SERVICE);
4264 }
4265
4266 /**
4267 * Get the default url to use for the test.
4268 */
4269 public String getDefaultUrl() {
4270 // See http://go/clientsdns for usage approval
4271 String server = Settings.Global.getString(mContext.getContentResolver(),
4272 Settings.Global.CAPTIVE_PORTAL_SERVER);
4273 if (server == null) {
4274 server = "clients3.google.com";
4275 }
4276 return "http://" + server + "/generate_204";
4277 }
4278
4279 /**
4280 * Detect if its possible to connect to the http url. DNS based detection techniques
4281 * do not work at all hotspots. The best way to check is to perform a request to
4282 * a known address that fetches the data we expect.
4283 */
4284 private synchronized Integer isMobileOk(Params params) {
Wink Saville948282b2013-08-29 08:55:16 -07004285 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savilleab9321d2013-06-29 21:10:57 -07004286 Uri orgUri = Uri.parse(params.mUrl);
4287 Random rand = new Random();
4288 mParams = params;
4289
Wink Savilleafe58b02013-08-13 12:41:06 -07004290 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville948282b2013-08-29 08:55:16 -07004291 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savilled95ccc52013-09-13 12:40:11 -07004292 log("isMobileOk: X not mobile capable result=" + result);
4293 return result;
4294 }
4295
4296 // See if we've already determined we've got a provisioning connection,
4297 // if so we don't need to do anything active.
4298 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4299 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4300 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4301 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4302
4303 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4304 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4305 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4306 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4307
4308 if (isDefaultProvisioning || isHipriProvisioning) {
4309 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4310 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Savilleafe58b02013-08-13 12:41:06 -07004311 return result;
4312 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004313
Wink Savilleafe58b02013-08-13 12:41:06 -07004314 try {
Wink Savilleab9321d2013-06-29 21:10:57 -07004315 // Continue trying to connect until time has run out
4316 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville7f6ee2e2013-08-07 11:02:57 -07004317
Wink Savilledce52cd2013-08-16 17:17:28 -07004318 if (!mCs.isMobileDataStateTrackerReady()) {
4319 // Wait for MobileDataStateTracker to be ready.
4320 if (DBG) log("isMobileOk: mdst is not ready");
4321 while(SystemClock.elapsedRealtime() < endTime) {
4322 if (mCs.isMobileDataStateTrackerReady()) {
4323 // Enable fail fast as we'll do retries here and use a
4324 // hipri connection so the default connection stays active.
4325 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4326 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4327 break;
4328 }
Wink Saville1d3a89e2013-10-31 06:35:22 -07004329 sleep(POLLING_SLEEP_SEC);
Wink Savilledce52cd2013-08-16 17:17:28 -07004330 }
4331 }
4332
4333 log("isMobileOk: start hipri url=" + params.mUrl);
4334
Wink Saville7f6ee2e2013-08-07 11:02:57 -07004335 // First wait until we can start using hipri
4336 Binder binder = new Binder();
4337 while(SystemClock.elapsedRealtime() < endTime) {
4338 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4339 Phone.FEATURE_ENABLE_HIPRI, binder);
4340 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4341 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4342 log("isMobileOk: hipri started");
4343 break;
4344 }
4345 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville948282b2013-08-29 08:55:16 -07004346 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville1d3a89e2013-10-31 06:35:22 -07004347 sleep(POLLING_SLEEP_SEC);
Wink Saville7f6ee2e2013-08-07 11:02:57 -07004348 }
4349
4350 // Continue trying to connect until time has run out
Wink Savilleab9321d2013-06-29 21:10:57 -07004351 while(SystemClock.elapsedRealtime() < endTime) {
4352 try {
4353 // Wait for hipri to connect.
4354 // TODO: Don't poll and handle situation where hipri fails
4355 // because default is retrying. See b/9569540
4356 NetworkInfo.State state = mCs
4357 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4358 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville948282b2013-08-29 08:55:16 -07004359 if (true/*VDBG*/) {
Wink Saville1aef7fc2013-07-31 15:49:04 -07004360 log("isMobileOk: not connected ni=" +
Wink Savilleab9321d2013-06-29 21:10:57 -07004361 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville1aef7fc2013-07-31 15:49:04 -07004362 }
Wink Saville1d3a89e2013-10-31 06:35:22 -07004363 sleep(POLLING_SLEEP_SEC);
Wink Saville948282b2013-08-29 08:55:16 -07004364 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savilleab9321d2013-06-29 21:10:57 -07004365 continue;
4366 }
4367
Wink Saville948282b2013-08-29 08:55:16 -07004368 // Hipri has started check if this is a provisioning url
4369 MobileDataStateTracker mdst = (MobileDataStateTracker)
4370 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4371 if (mdst.isProvisioningNetwork()) {
Wink Saville4fea0412013-09-06 09:53:08 -07004372 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Savilled95ccc52013-09-13 12:40:11 -07004373 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville948282b2013-08-29 08:55:16 -07004374 return result;
4375 } else {
4376 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4377 }
4378
Wink Savilleab9321d2013-06-29 21:10:57 -07004379 // Get of the addresses associated with the url host. We need to use the
4380 // address otherwise HttpURLConnection object will use the name to get
Wink Saville1d3a89e2013-10-31 06:35:22 -07004381 // the addresses and will try every address but that will bypass the
Wink Savilleab9321d2013-06-29 21:10:57 -07004382 // route to host we setup and the connection could succeed as the default
4383 // interface might be connected to the internet via wifi or other interface.
4384 InetAddress[] addresses;
4385 try {
4386 addresses = InetAddress.getAllByName(orgUri.getHost());
4387 } catch (UnknownHostException e) {
Wink Saville948282b2013-08-29 08:55:16 -07004388 result = CMP_RESULT_CODE_NO_DNS;
Wink Savilled95ccc52013-09-13 12:40:11 -07004389 log("isMobileOk: X UnknownHostException result=" + result);
Wink Savilleab9321d2013-06-29 21:10:57 -07004390 return result;
4391 }
4392 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4393
4394 // Get the type of addresses supported by this link
4395 LinkProperties lp = mCs.getLinkProperties(
4396 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti4faa0272013-08-08 11:00:12 +09004397 boolean linkHasIpv4 = lp.hasIPv4Address();
4398 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Savilleab9321d2013-06-29 21:10:57 -07004399 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4400 + " linkHasIpv6=" + linkHasIpv6);
4401
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004402 final ArrayList<InetAddress> validAddresses =
4403 new ArrayList<InetAddress>(addresses.length);
Wink Savilleab9321d2013-06-29 21:10:57 -07004404
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004405 for (InetAddress addr : addresses) {
4406 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4407 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4408 validAddresses.add(addr);
Wink Savilleab9321d2013-06-29 21:10:57 -07004409 }
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004410 }
4411
4412 if (validAddresses.size() == 0) {
4413 return CMP_RESULT_CODE_NO_CONNECTION;
4414 }
4415
4416 int addrTried = 0;
4417 while (true) {
Wink Saville1d3a89e2013-10-31 06:35:22 -07004418 // Loop through at most MAX_LOOPS valid addresses or until
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004419 // we run out of time
Wink Saville1d3a89e2013-10-31 06:35:22 -07004420 if (addrTried++ >= MAX_LOOPS) {
4421 log("isMobileOk: too many loops tried - giving up");
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004422 break;
4423 }
4424 if (SystemClock.elapsedRealtime() >= endTime) {
Wink Saville1d3a89e2013-10-31 06:35:22 -07004425 log("isMobileOk: spend too much time - giving up");
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004426 break;
4427 }
4428
4429 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4430 validAddresses.size()));
Wink Savilleab9321d2013-06-29 21:10:57 -07004431
4432 // Make a route to host so we check the specific interface.
4433 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
Chad Brubakerf5729a62014-03-13 18:18:36 +00004434 hostAddr.getAddress(), null)) {
Wink Savilleab9321d2013-06-29 21:10:57 -07004435 // Wait a short time to be sure the route is established ??
4436 log("isMobileOk:"
4437 + " wait to establish route to hostAddr=" + hostAddr);
Wink Saville1d3a89e2013-10-31 06:35:22 -07004438 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
Wink Savilleab9321d2013-06-29 21:10:57 -07004439 } else {
4440 log("isMobileOk:"
4441 + " could not establish route to hostAddr=" + hostAddr);
Wink Saville1d3a89e2013-10-31 06:35:22 -07004442 // Wait a short time before the next attempt
4443 sleep(NET_ERROR_SLEEP_SEC);
Wink Savilleab9321d2013-06-29 21:10:57 -07004444 continue;
4445 }
4446
Wink Saville1d3a89e2013-10-31 06:35:22 -07004447 // Rewrite the url to have numeric address to use the specific route
4448 // using http for half the attempts and https for the other half.
4449 // Doing https first and http second as on a redirected walled garden
4450 // such as t-mobile uses we get a SocketTimeoutException: "SSL
4451 // handshake timed out" which we declare as
4452 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4453 // having http second we will be using logic used for some time.
4454 URL newUrl;
4455 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4456 newUrl = new URL(scheme, hostAddr.getHostAddress(),
4457 orgUri.getPath());
Wink Savilleab9321d2013-06-29 21:10:57 -07004458 log("isMobileOk: newUrl=" + newUrl);
4459
4460 HttpURLConnection urlConn = null;
4461 try {
Wink Saville1d3a89e2013-10-31 06:35:22 -07004462 // Open the connection set the request headers and get the response
4463 urlConn = (HttpURLConnection)newUrl.openConnection(
Wink Savilleab9321d2013-06-29 21:10:57 -07004464 java.net.Proxy.NO_PROXY);
Wink Saville1d3a89e2013-10-31 06:35:22 -07004465 if (scheme.equals("https")) {
4466 ((HttpsURLConnection)urlConn).setHostnameVerifier(
4467 new CheckMpHostnameVerifier(orgUri));
4468 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004469 urlConn.setInstanceFollowRedirects(false);
4470 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4471 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4472 urlConn.setUseCaches(false);
4473 urlConn.setAllowUserInteraction(false);
Lorenzo Colitti143a2cf2013-10-08 10:41:25 +09004474 // Set the "Connection" to "Close" as by default "Keep-Alive"
4475 // is used which is useless in this case.
Wink Savilleab9321d2013-06-29 21:10:57 -07004476 urlConn.setRequestProperty("Connection", "close");
4477 int responseCode = urlConn.getResponseCode();
Wink Saville4fea0412013-09-06 09:53:08 -07004478
4479 // For debug display the headers
4480 Map<String, List<String>> headers = urlConn.getHeaderFields();
4481 log("isMobileOk: headers=" + headers);
4482
4483 // Close the connection
Wink Savilleab9321d2013-06-29 21:10:57 -07004484 urlConn.disconnect();
4485 urlConn = null;
Wink Saville4fea0412013-09-06 09:53:08 -07004486
Wink Saville1d3a89e2013-10-31 06:35:22 -07004487 if (mTestingFailures) {
4488 // Pretend no connection, this tests using http and https
4489 result = CMP_RESULT_CODE_NO_CONNECTION;
4490 log("isMobileOk: TESTING_FAILURES, pretend no connction");
4491 continue;
4492 }
4493
Wink Saville4fea0412013-09-06 09:53:08 -07004494 if (responseCode == 204) {
4495 // Return
Wink Saville4fea0412013-09-06 09:53:08 -07004496 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville1d3a89e2013-10-31 06:35:22 -07004497 log("isMobileOk: X got expected responseCode=" + responseCode
Wink Savilled95ccc52013-09-13 12:40:11 -07004498 + " result=" + result);
Wink Saville4fea0412013-09-06 09:53:08 -07004499 return result;
4500 } else {
4501 // Retry to be sure this was redirected, we've gotten
4502 // occasions where a server returned 200 even though
4503 // the device didn't have a "warm" sim.
4504 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwaltb9acff32013-10-14 18:03:02 -07004505 // TODO - it would be nice in the single-address case to do
4506 // another DNS resolve here, but flushing the cache is a bit
4507 // heavy-handed.
Wink Saville4fea0412013-09-06 09:53:08 -07004508 result = CMP_RESULT_CODE_REDIRECTED;
4509 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004510 } catch (Exception e) {
Wink Saville1d3a89e2013-10-31 06:35:22 -07004511 log("isMobileOk: HttpURLConnection Exception" + e);
Wink Saville4fea0412013-09-06 09:53:08 -07004512 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Savilleab9321d2013-06-29 21:10:57 -07004513 if (urlConn != null) {
4514 urlConn.disconnect();
4515 urlConn = null;
4516 }
Wink Saville1d3a89e2013-10-31 06:35:22 -07004517 sleep(NET_ERROR_SLEEP_SEC);
4518 continue;
Wink Savilleab9321d2013-06-29 21:10:57 -07004519 }
4520 }
Wink Savilled95ccc52013-09-13 12:40:11 -07004521 log("isMobileOk: X loops|timed out result=" + result);
Wink Savilleab9321d2013-06-29 21:10:57 -07004522 return result;
4523 } catch (Exception e) {
4524 log("isMobileOk: Exception e=" + e);
4525 continue;
4526 }
4527 }
4528 log("isMobileOk: timed out");
4529 } finally {
4530 log("isMobileOk: F stop hipri");
4531 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4532 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4533 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville948282b2013-08-29 08:55:16 -07004534
4535 // Wait for hipri to disconnect.
4536 long endTime = SystemClock.elapsedRealtime() + 5000;
4537
4538 while(SystemClock.elapsedRealtime() < endTime) {
4539 NetworkInfo.State state = mCs
4540 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4541 if (state != NetworkInfo.State.DISCONNECTED) {
4542 if (VDBG) {
4543 log("isMobileOk: connected ni=" +
4544 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4545 }
Wink Saville1d3a89e2013-10-31 06:35:22 -07004546 sleep(POLLING_SLEEP_SEC);
Wink Saville948282b2013-08-29 08:55:16 -07004547 continue;
4548 }
4549 }
4550
Wink Savilleab9321d2013-06-29 21:10:57 -07004551 log("isMobileOk: X result=" + result);
4552 }
4553 return result;
4554 }
4555
4556 @Override
4557 protected Integer doInBackground(Params... params) {
4558 return isMobileOk(params[0]);
4559 }
4560
4561 @Override
4562 protected void onPostExecute(Integer result) {
4563 log("onPostExecute: result=" + result);
4564 if ((mParams != null) && (mParams.mCb != null)) {
4565 mParams.mCb.onComplete(result);
4566 }
4567 }
4568
4569 private String inetAddressesToString(InetAddress[] addresses) {
4570 StringBuffer sb = new StringBuffer();
4571 boolean firstTime = true;
4572 for(InetAddress addr : addresses) {
4573 if (firstTime) {
4574 firstTime = false;
4575 } else {
4576 sb.append(",");
4577 }
4578 sb.append(addr);
4579 }
4580 return sb.toString();
4581 }
4582
4583 private void printNetworkInfo() {
4584 boolean hasIccCard = mTm.hasIccCard();
4585 int simState = mTm.getSimState();
4586 log("hasIccCard=" + hasIccCard
4587 + " simState=" + simState);
4588 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4589 if (ni != null) {
4590 log("ni.length=" + ni.length);
4591 for (NetworkInfo netInfo: ni) {
4592 log("netInfo=" + netInfo.toString());
4593 }
4594 } else {
4595 log("no network info ni=null");
4596 }
4597 }
4598
4599 /**
4600 * Sleep for a few seconds then return.
4601 * @param seconds
4602 */
4603 private static void sleep(int seconds) {
4604 try {
4605 Thread.sleep(seconds * 1000);
4606 } catch (InterruptedException e) {
4607 e.printStackTrace();
4608 }
4609 }
4610
Wink Saville1d3a89e2013-10-31 06:35:22 -07004611 private static void log(String s) {
Wink Savilleab9321d2013-06-29 21:10:57 -07004612 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4613 }
4614 }
4615
Wink Saville948282b2013-08-29 08:55:16 -07004616 // TODO: Move to ConnectivityManager and make public?
4617 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4618 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Savilleab9321d2013-06-29 21:10:57 -07004619
Wink Saville948282b2013-08-29 08:55:16 -07004620 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4621 @Override
4622 public void onReceive(Context context, Intent intent) {
4623 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4624 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4625 }
4626 }
4627 };
4628
4629 private void handleMobileProvisioningAction(String url) {
4630 // Notication mark notification as not visible
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004631 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville948282b2013-08-29 08:55:16 -07004632
4633 // If provisioning network handle as a special case,
4634 // otherwise launch browser with the intent directly.
4635 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville67c38212013-09-05 12:02:25 -07004636 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -07004637 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4638 MobileDataStateTracker mdst = (MobileDataStateTracker)
4639 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4640 mdst.enableMobileProvisioning(url);
4641 } else {
4642 if (DBG) log("handleMobileProvisioningAction: on default network");
Robert Greenwalt536b3c22013-10-17 12:46:52 -07004643 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4644 Intent.CATEGORY_APP_BROWSER);
4645 newIntent.setData(Uri.parse(url));
Wink Saville948282b2013-08-29 08:55:16 -07004646 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4647 Intent.FLAG_ACTIVITY_NEW_TASK);
4648 try {
4649 mContext.startActivity(newIntent);
4650 } catch (ActivityNotFoundException e) {
4651 loge("handleMobileProvisioningAction: startActivity failed" + e);
4652 }
4653 }
4654 }
4655
4656 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4657 private volatile boolean mIsNotificationVisible = false;
4658
4659 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4660 String url) {
4661 if (DBG) {
4662 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4663 + " extraInfo=" + extraInfo + " url=" + url);
4664 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004665
4666 Resources r = Resources.getSystem();
4667 NotificationManager notificationManager = (NotificationManager) mContext
4668 .getSystemService(Context.NOTIFICATION_SERVICE);
4669
4670 if (visible) {
4671 CharSequence title;
4672 CharSequence details;
4673 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07004674 Intent intent;
4675 Notification notification = new Notification();
4676 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07004677 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07004678 title = r.getString(R.string.wifi_available_sign_in, 0);
4679 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07004680 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07004681 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville948282b2013-08-29 08:55:16 -07004682 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4683 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4684 Intent.FLAG_ACTIVITY_NEW_TASK);
4685 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Savilleab9321d2013-06-29 21:10:57 -07004686 break;
4687 case ConnectivityManager.TYPE_MOBILE:
4688 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07004689 title = r.getString(R.string.network_available_sign_in, 0);
4690 // TODO: Change this to pull from NetworkInfo once a printable
4691 // name has been added to it
4692 details = mTelephonyManager.getNetworkOperatorName();
4693 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville948282b2013-08-29 08:55:16 -07004694 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4695 intent.putExtra("EXTRA_URL", url);
4696 intent.setFlags(0);
4697 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Savilleab9321d2013-06-29 21:10:57 -07004698 break;
4699 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07004700 title = r.getString(R.string.network_available_sign_in, 0);
4701 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07004702 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07004703 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville948282b2013-08-29 08:55:16 -07004704 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4705 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4706 Intent.FLAG_ACTIVITY_NEW_TASK);
4707 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Savilleab9321d2013-06-29 21:10:57 -07004708 break;
4709 }
4710
Wink Savilleab9321d2013-06-29 21:10:57 -07004711 notification.when = 0;
4712 notification.icon = icon;
4713 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07004714 notification.tickerText = title;
4715 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4716
Wink Saville948282b2013-08-29 08:55:16 -07004717 try {
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004718 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville948282b2013-08-29 08:55:16 -07004719 } catch (NullPointerException npe) {
4720 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4721 npe.printStackTrace();
4722 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004723 } else {
Wink Saville948282b2013-08-29 08:55:16 -07004724 try {
Wink Saville3ec8e7f2013-10-03 08:34:46 -07004725 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville948282b2013-08-29 08:55:16 -07004726 } catch (NullPointerException npe) {
4727 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4728 npe.printStackTrace();
4729 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004730 }
Wink Saville948282b2013-08-29 08:55:16 -07004731 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07004732 }
4733
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004734 /** Location to an updatable file listing carrier provisioning urls.
4735 * An example:
4736 *
4737 * <?xml version="1.0" encoding="utf-8"?>
4738 * <provisioningUrls>
4739 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4740 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4741 * </provisioningUrls>
4742 */
4743 private static final String PROVISIONING_URL_PATH =
4744 "/data/misc/radio/provisioning_urls.xml";
4745 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004746
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004747 /** XML tag for root element. */
4748 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4749 /** XML tag for individual url */
4750 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4751 /** XML tag for redirected url */
4752 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4753 /** XML attribute for mcc */
4754 private static final String ATTR_MCC = "mcc";
4755 /** XML attribute for mnc */
4756 private static final String ATTR_MNC = "mnc";
4757
4758 private static final int REDIRECTED_PROVISIONING = 1;
4759 private static final int PROVISIONING = 2;
4760
4761 private String getProvisioningUrlBaseFromFile(int type) {
4762 FileReader fileReader = null;
4763 XmlPullParser parser = null;
4764 Configuration config = mContext.getResources().getConfiguration();
4765 String tagType;
4766
4767 switch (type) {
4768 case PROVISIONING:
4769 tagType = TAG_PROVISIONING_URL;
4770 break;
4771 case REDIRECTED_PROVISIONING:
4772 tagType = TAG_REDIRECTED_URL;
4773 break;
4774 default:
4775 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4776 type);
4777 }
4778
4779 try {
4780 fileReader = new FileReader(mProvisioningUrlFile);
4781 parser = Xml.newPullParser();
4782 parser.setInput(fileReader);
4783 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4784
4785 while (true) {
4786 XmlUtils.nextElement(parser);
4787
4788 String element = parser.getName();
4789 if (element == null) break;
4790
4791 if (element.equals(tagType)) {
4792 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4793 try {
4794 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4795 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4796 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4797 parser.next();
4798 if (parser.getEventType() == XmlPullParser.TEXT) {
4799 return parser.getText();
4800 }
4801 }
4802 }
4803 } catch (NumberFormatException e) {
4804 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4805 }
4806 }
4807 }
4808 return null;
4809 } catch (FileNotFoundException e) {
4810 loge("Carrier Provisioning Urls file not found");
4811 } catch (XmlPullParserException e) {
4812 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4813 } catch (IOException e) {
4814 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4815 } finally {
4816 if (fileReader != null) {
4817 try {
4818 fileReader.close();
4819 } catch (IOException e) {}
4820 }
4821 }
4822 return null;
4823 }
4824
Wink Saville42d4f082013-07-20 20:31:59 -07004825 @Override
4826 public String getMobileRedirectedProvisioningUrl() {
4827 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004828 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4829 if (TextUtils.isEmpty(url)) {
4830 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4831 }
4832 return url;
4833 }
4834
Wink Saville42d4f082013-07-20 20:31:59 -07004835 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004836 public String getMobileProvisioningUrl() {
4837 enforceConnectivityInternalPermission();
4838 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4839 if (TextUtils.isEmpty(url)) {
4840 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004841 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004842 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004843 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004844 }
Wink Saville8cf35602013-07-10 23:00:07 -07004845 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004846 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004847 String phoneNumber = mTelephonyManager.getLine1Number();
4848 if (TextUtils.isEmpty(phoneNumber)) {
4849 phoneNumber = "0000000000";
4850 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004851 url = String.format(url,
4852 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4853 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004854 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004855 }
4856
Wink Savilleab9321d2013-06-29 21:10:57 -07004857 return url;
4858 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004859
Wink Saville948282b2013-08-29 08:55:16 -07004860 @Override
4861 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4862 String extraInfo, String url) {
4863 enforceConnectivityInternalPermission();
4864 setProvNotificationVisible(visible, networkType, extraInfo, url);
4865 }
Wink Saville7788c612013-08-29 14:57:08 -07004866
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004867 @Override
4868 public void setAirplaneMode(boolean enable) {
4869 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004870 final long ident = Binder.clearCallingIdentity();
4871 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004872 final ContentResolver cr = mContext.getContentResolver();
4873 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4874 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4875 intent.putExtra("state", enable);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004876 mContext.sendBroadcast(intent);
4877 } finally {
4878 Binder.restoreCallingIdentity(ident);
4879 }
4880 }
4881
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004882 private void onUserStart(int userId) {
4883 synchronized(mVpns) {
4884 Vpn userVpn = mVpns.get(userId);
4885 if (userVpn != null) {
4886 loge("Starting user already has a VPN");
4887 return;
4888 }
4889 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4890 mVpns.put(userId, userVpn);
4891 userVpn.startMonitoring(mContext, mTrackerHandler);
4892 }
4893 }
4894
4895 private void onUserStop(int userId) {
4896 synchronized(mVpns) {
4897 Vpn userVpn = mVpns.get(userId);
4898 if (userVpn == null) {
4899 loge("Stopping user has no VPN");
4900 return;
4901 }
4902 mVpns.delete(userId);
4903 }
4904 }
4905
4906 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4907 @Override
4908 public void onReceive(Context context, Intent intent) {
4909 final String action = intent.getAction();
4910 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4911 if (userId == UserHandle.USER_NULL) return;
4912
4913 if (Intent.ACTION_USER_STARTING.equals(action)) {
4914 onUserStart(userId);
4915 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4916 onUserStop(userId);
4917 }
4918 }
4919 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004920
4921 @Override
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004922 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004923 enforceAccessPermission();
4924 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004925 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004926 } else {
4927 return null;
4928 }
4929 }
4930
4931 @Override
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004932 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004933 enforceAccessPermission();
4934 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004935 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004936 } else {
4937 return null;
4938 }
4939 }
4940
4941 @Override
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004942 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004943 enforceAccessPermission();
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004944 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004945 for (NetworkStateTracker tracker : mNetTrackers) {
4946 if (tracker != null) {
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004947 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004948 if (li != null) {
4949 result.add(li);
4950 }
4951 }
4952 }
4953
Vinit Deshapnde6a2d3252013-09-04 14:11:24 -07004954 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004955 }
4956
4957 /* Infrastructure for network sampling */
4958
4959 private void handleNetworkSamplingTimeout() {
4960
4961 log("Sampling interval elapsed, updating statistics ..");
4962
4963 // initialize list of interfaces ..
4964 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4965 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4966 for (NetworkStateTracker tracker : mNetTrackers) {
4967 if (tracker != null) {
4968 String ifaceName = tracker.getNetworkInterfaceName();
4969 if (ifaceName != null) {
4970 mapIfaceToSample.put(ifaceName, null);
4971 }
4972 }
4973 }
4974
4975 // Read samples for all interfaces
4976 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4977
4978 // process samples for all networks
4979 for (NetworkStateTracker tracker : mNetTrackers) {
4980 if (tracker != null) {
4981 String ifaceName = tracker.getNetworkInterfaceName();
4982 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4983 if (ss != null) {
4984 // end the previous sampling cycle
4985 tracker.stopSampling(ss);
4986 // start a new sampling cycle ..
4987 tracker.startSampling(ss);
4988 }
4989 }
4990 }
4991
4992 log("Done.");
4993
4994 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4995 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4996 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4997
4998 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4999
5000 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
5001 }
5002
5003 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
5004 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
5005 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
5006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007}