ConnectivityService.java revision d7063e66ab03f68a85ec96df2e83e2af551bef77
10c1bc742181ded4930842b46e9507372f0b1b963James Dong/*
20c1bc742181ded4930842b46e9507372f0b1b963James Dong * Copyright (C) 2008 The Android Open Source Project
30c1bc742181ded4930842b46e9507372f0b1b963James Dong *
40c1bc742181ded4930842b46e9507372f0b1b963James Dong * Licensed under the Apache License, Version 2.0 (the "License");
50c1bc742181ded4930842b46e9507372f0b1b963James Dong * you may not use this file except in compliance with the License.
60c1bc742181ded4930842b46e9507372f0b1b963James Dong * You may obtain a copy of the License at
70c1bc742181ded4930842b46e9507372f0b1b963James Dong *
80c1bc742181ded4930842b46e9507372f0b1b963James Dong *      http://www.apache.org/licenses/LICENSE-2.0
90c1bc742181ded4930842b46e9507372f0b1b963James Dong *
100c1bc742181ded4930842b46e9507372f0b1b963James Dong * Unless required by applicable law or agreed to in writing, software
110c1bc742181ded4930842b46e9507372f0b1b963James Dong * distributed under the License is distributed on an "AS IS" BASIS,
120c1bc742181ded4930842b46e9507372f0b1b963James Dong * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
130c1bc742181ded4930842b46e9507372f0b1b963James Dong * See the License for the specific language governing permissions and
140c1bc742181ded4930842b46e9507372f0b1b963James Dong * limitations under the License.
150c1bc742181ded4930842b46e9507372f0b1b963James Dong */
160c1bc742181ded4930842b46e9507372f0b1b963James Dong
170c1bc742181ded4930842b46e9507372f0b1b963James Dongpackage com.android.server;
180c1bc742181ded4930842b46e9507372f0b1b963James Dong
190c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.Manifest.permission.MANAGE_NETWORK_POLICY;
200c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
210c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
220c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
230c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_BLUETOOTH;
240c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_DUMMY;
250c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE;
260c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
270c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
280c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
290c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
300c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
310c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
320c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_IA;
330c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
340c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_NONE;
350c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_WIFI;
360c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_WIMAX;
370c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.TYPE_PROXY;
380c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.getNetworkTypeName;
390c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.ConnectivityManager.isNetworkTypeValid;
400c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
410c1bc742181ded4930842b46e9507372f0b1b963James Dongimport static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
420c1bc742181ded4930842b46e9507372f0b1b963James Dong
430c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.app.AlarmManager;
440c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.app.Notification;
450c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.app.NotificationManager;
460c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.app.PendingIntent;
470c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.ActivityNotFoundException;
480c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.BroadcastReceiver;
490c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.ContentResolver;
500c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.Context;
510c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.ContextWrapper;
520c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.Intent;
530c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.IntentFilter;
540c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.pm.PackageManager;
550c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.res.Configuration;
560c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.content.res.Resources;
570c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.database.ContentObserver;
580c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.ConnectivityManager;
590c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.IConnectivityManager;
600c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.INetworkManagementEventObserver;
610c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.INetworkPolicyListener;
620c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.INetworkPolicyManager;
630c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.INetworkStatsService;
640c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.LinkAddress;
650c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.LinkProperties;
660c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.LinkProperties.CompareResult;
670c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.LinkQualityInfo;
680c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.MobileDataStateTracker;
690c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.Network;
700c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkAgent;
710c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkCapabilities;
720c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkConfig;
730c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkInfo;
740c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkInfo.DetailedState;
750c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkFactory;
760c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkMisc;
770c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkQuotaInfo;
780c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkRequest;
790c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkState;
800c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkStateTracker;
810c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.NetworkUtils;
820c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.Proxy;
830c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.ProxyDataTracker;
840c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.ProxyInfo;
850c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.RouteInfo;
860c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.SamplingDataTracker;
870c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.UidRange;
880c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.Uri;
890c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.net.wimax.WimaxManagerConstants;
900c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.AsyncTask;
910c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Binder;
920c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Build;
930c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.FileUtils;
940c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Handler;
950c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.HandlerThread;
960c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.IBinder;
970c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.INetworkManagementService;
980c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Looper;
990c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Message;
1000c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Messenger;
1010c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.ParcelFileDescriptor;
1020c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.PowerManager;
1030c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.Process;
1040c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.RemoteException;
1050c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.ServiceManager;
1060c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.SystemClock;
1070c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.SystemProperties;
1080c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.UserHandle;
1090c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.os.UserManager;
1100c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.provider.Settings;
1110c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.security.Credentials;
1120c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.security.KeyStore;
1130c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.telephony.TelephonyManager;
1140c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.text.TextUtils;
1150c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.util.Slog;
1160c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.util.SparseArray;
1170c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.util.SparseIntArray;
1180c1bc742181ded4930842b46e9507372f0b1b963James Dongimport android.util.Xml;
1190c1bc742181ded4930842b46e9507372f0b1b963James Dong
1200c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.R;
1210c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.annotations.GuardedBy;
1220c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.app.IBatteryStats;
1230c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.net.LegacyVpnInfo;
1240c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.net.NetworkStatsFactory;
1250c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.net.VpnConfig;
1260c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.net.VpnProfile;
1270c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.telephony.DctConstants;
1280c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.telephony.Phone;
1290c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.telephony.PhoneConstants;
1300c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.telephony.TelephonyIntents;
1310c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.util.AsyncChannel;
1320c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.util.IndentingPrintWriter;
1330c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.internal.util.XmlUtils;
1340c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.am.BatteryStatsService;
1350c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.DataConnectionStats;
1360c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.Nat464Xlat;
1370c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.NetworkAgentInfo;
1380c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.NetworkMonitor;
1390c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.PacManager;
1400c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.Tethering;
1410c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.connectivity.Vpn;
1420c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.net.BaseNetworkObserver;
1430c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.android.server.net.LockdownVpnTracker;
1440c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.google.android.collect.Lists;
1450c1bc742181ded4930842b46e9507372f0b1b963James Dongimport com.google.android.collect.Sets;
1460c1bc742181ded4930842b46e9507372f0b1b963James Dong
1470c1bc742181ded4930842b46e9507372f0b1b963James Dongimport dalvik.system.DexClassLoader;
1480c1bc742181ded4930842b46e9507372f0b1b963James Dong
1490c1bc742181ded4930842b46e9507372f0b1b963James Dongimport org.xmlpull.v1.XmlPullParser;
1500c1bc742181ded4930842b46e9507372f0b1b963James Dongimport org.xmlpull.v1.XmlPullParserException;
1510c1bc742181ded4930842b46e9507372f0b1b963James Dong
1520c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.io.File;
1530c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.io.FileDescriptor;
1540c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.io.FileNotFoundException;
1550c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.io.FileReader;
1560c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.io.IOException;
1570c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.io.PrintWriter;
1580c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.lang.reflect.Constructor;
1590c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.net.HttpURLConnection;
1600c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.net.Inet4Address;
1610c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.net.Inet6Address;
1620c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.net.InetAddress;
1630c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.net.URL;
1640c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.net.UnknownHostException;
1650c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.ArrayList;
1660c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.Arrays;
1670c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.Collection;
1680c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.GregorianCalendar;
1690c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.HashMap;
1700c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.HashSet;
1710c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.List;
1720c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.Map;
1730c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.Random;
1740c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.concurrent.atomic.AtomicBoolean;
1750c1bc742181ded4930842b46e9507372f0b1b963James Dongimport java.util.concurrent.atomic.AtomicInteger;
1760c1bc742181ded4930842b46e9507372f0b1b963James Dong
1770c1bc742181ded4930842b46e9507372f0b1b963James Dongimport javax.net.ssl.HostnameVerifier;
1780c1bc742181ded4930842b46e9507372f0b1b963James Dongimport javax.net.ssl.HttpsURLConnection;
1790c1bc742181ded4930842b46e9507372f0b1b963James Dongimport javax.net.ssl.SSLSession;
1800c1bc742181ded4930842b46e9507372f0b1b963James Dong
1810c1bc742181ded4930842b46e9507372f0b1b963James Dong/**
1820c1bc742181ded4930842b46e9507372f0b1b963James Dong * @hide
1830c1bc742181ded4930842b46e9507372f0b1b963James Dong */
1840c1bc742181ded4930842b46e9507372f0b1b963James Dongpublic class ConnectivityService extends IConnectivityManager.Stub {
1850c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final String TAG = "ConnectivityService";
1860c1bc742181ded4930842b46e9507372f0b1b963James Dong
1870c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final boolean DBG = true;
1880c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final boolean VDBG = false;
1890c1bc742181ded4930842b46e9507372f0b1b963James Dong
1900c1bc742181ded4930842b46e9507372f0b1b963James Dong    // network sampling debugging
1910c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final boolean SAMPLE_DBG = false;
1920c1bc742181ded4930842b46e9507372f0b1b963James Dong
1930c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final boolean LOGD_RULES = false;
1940c1bc742181ded4930842b46e9507372f0b1b963James Dong
1950c1bc742181ded4930842b46e9507372f0b1b963James Dong    // TODO: create better separation between radio types and network types
1960c1bc742181ded4930842b46e9507372f0b1b963James Dong
1970c1bc742181ded4930842b46e9507372f0b1b963James Dong    // how long to wait before switching back to a radio's default network
1980c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
1990c1bc742181ded4930842b46e9507372f0b1b963James Dong    // system property that can override the above value
2000c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
2010c1bc742181ded4930842b46e9507372f0b1b963James Dong            "android.telephony.apn-restore";
2020c1bc742181ded4930842b46e9507372f0b1b963James Dong
2030c1bc742181ded4930842b46e9507372f0b1b963James Dong    // Default value if FAIL_FAST_TIME_MS is not set
2040c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
2050c1bc742181ded4930842b46e9507372f0b1b963James Dong    // system property that can override DEFAULT_FAIL_FAST_TIME_MS
2060c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final String FAIL_FAST_TIME_MS =
2070c1bc742181ded4930842b46e9507372f0b1b963James Dong            "persist.radio.fail_fast_time_ms";
2080c1bc742181ded4930842b46e9507372f0b1b963James Dong
2090c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
2100c1bc742181ded4930842b46e9507372f0b1b963James Dong            "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
2110c1bc742181ded4930842b46e9507372f0b1b963James Dong
2120c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
2130c1bc742181ded4930842b46e9507372f0b1b963James Dong
2140c1bc742181ded4930842b46e9507372f0b1b963James Dong    private PendingIntent mSampleIntervalElapsedIntent;
2150c1bc742181ded4930842b46e9507372f0b1b963James Dong
2160c1bc742181ded4930842b46e9507372f0b1b963James Dong    // Set network sampling interval at 12 minutes, this way, even if the timers get
2170c1bc742181ded4930842b46e9507372f0b1b963James Dong    // aggregated, it will fire at around 15 minutes, which should allow us to
2180c1bc742181ded4930842b46e9507372f0b1b963James Dong    // aggregate this timer with other timers (specially the socket keep alive timers)
2190c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60);
2200c1bc742181ded4930842b46e9507372f0b1b963James Dong
2210c1bc742181ded4930842b46e9507372f0b1b963James Dong    // start network sampling a minute after booting ...
2220c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60);
2230c1bc742181ded4930842b46e9507372f0b1b963James Dong
2240c1bc742181ded4930842b46e9507372f0b1b963James Dong    AlarmManager mAlarmManager;
2250c1bc742181ded4930842b46e9507372f0b1b963James Dong
2260c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Tethering mTethering;
2270c1bc742181ded4930842b46e9507372f0b1b963James Dong
2280c1bc742181ded4930842b46e9507372f0b1b963James Dong    private KeyStore mKeyStore;
2290c1bc742181ded4930842b46e9507372f0b1b963James Dong
2300c1bc742181ded4930842b46e9507372f0b1b963James Dong    @GuardedBy("mVpns")
2310c1bc742181ded4930842b46e9507372f0b1b963James Dong    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
2320c1bc742181ded4930842b46e9507372f0b1b963James Dong
2330c1bc742181ded4930842b46e9507372f0b1b963James Dong    private boolean mLockdownEnabled;
2340c1bc742181ded4930842b46e9507372f0b1b963James Dong    private LockdownVpnTracker mLockdownTracker;
2350c1bc742181ded4930842b46e9507372f0b1b963James Dong
2360c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Nat464Xlat mClat;
2370c1bc742181ded4930842b46e9507372f0b1b963James Dong
2380c1bc742181ded4930842b46e9507372f0b1b963James Dong    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
2390c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Object mRulesLock = new Object();
2400c1bc742181ded4930842b46e9507372f0b1b963James Dong    /** Currently active network rules by UID. */
2410c1bc742181ded4930842b46e9507372f0b1b963James Dong    private SparseIntArray mUidRules = new SparseIntArray();
2420c1bc742181ded4930842b46e9507372f0b1b963James Dong    /** Set of ifaces that are costly. */
2430c1bc742181ded4930842b46e9507372f0b1b963James Dong    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
2440c1bc742181ded4930842b46e9507372f0b1b963James Dong
2450c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
2460c1bc742181ded4930842b46e9507372f0b1b963James Dong     * Sometimes we want to refer to the individual network state
2470c1bc742181ded4930842b46e9507372f0b1b963James Dong     * trackers separately, and sometimes we just want to treat them
2480c1bc742181ded4930842b46e9507372f0b1b963James Dong     * abstractly.
2490c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
2500c1bc742181ded4930842b46e9507372f0b1b963James Dong    private NetworkStateTracker mNetTrackers[];
2510c1bc742181ded4930842b46e9507372f0b1b963James Dong
2520c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Context mContext;
2530c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mNetworkPreference;
2540c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mActiveDefaultNetwork = -1;
2550c1bc742181ded4930842b46e9507372f0b1b963James Dong    // 0 is full bad, 100 is full good
2560c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mDefaultInetConditionPublished = 0;
2570c1bc742181ded4930842b46e9507372f0b1b963James Dong
2580c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Object mDnsLock = new Object();
2590c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mNumDnsEntries;
2600c1bc742181ded4930842b46e9507372f0b1b963James Dong
2610c1bc742181ded4930842b46e9507372f0b1b963James Dong    private boolean mTestMode;
2620c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static ConnectivityService sServiceInstance;
2630c1bc742181ded4930842b46e9507372f0b1b963James Dong
2640c1bc742181ded4930842b46e9507372f0b1b963James Dong    private INetworkManagementService mNetd;
2650c1bc742181ded4930842b46e9507372f0b1b963James Dong    private INetworkPolicyManager mPolicyManager;
2660c1bc742181ded4930842b46e9507372f0b1b963James Dong
2670c1bc742181ded4930842b46e9507372f0b1b963James Dong    private String mCurrentTcpBufferSizes;
2680c1bc742181ded4930842b46e9507372f0b1b963James Dong
2690c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int ENABLED  = 1;
2700c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int DISABLED = 0;
2710c1bc742181ded4930842b46e9507372f0b1b963James Dong
2720c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
2730c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to change our mobile data enabled flag
2740c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
2750c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
2760c1bc742181ded4930842b46e9507372f0b1b963James Dong
2770c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
2780c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to clear a wakelock when transitioning
2790c1bc742181ded4930842b46e9507372f0b1b963James Dong     * from one net to another.  Clear happens when we get a new
2800c1bc742181ded4930842b46e9507372f0b1b963James Dong     * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
2810c1bc742181ded4930842b46e9507372f0b1b963James Dong     * after a timeout if no network is found (typically 1 min).
2820c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
2830c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
2840c1bc742181ded4930842b46e9507372f0b1b963James Dong
2850c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
2860c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to reload global proxy settings
2870c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
2880c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
2890c1bc742181ded4930842b46e9507372f0b1b963James Dong
2900c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
2910c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to set external dependency met/unmet
2920c1bc742181ded4930842b46e9507372f0b1b963James Dong     * arg1 = ENABLED (met) or DISABLED (unmet)
2930c1bc742181ded4930842b46e9507372f0b1b963James Dong     * arg2 = NetworkType
2940c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
2950c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_SET_DEPENDENCY_MET = 10;
2960c1bc742181ded4930842b46e9507372f0b1b963James Dong
2970c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
2980c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to send a sticky broadcast delayed.
2990c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3000c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
3010c1bc742181ded4930842b46e9507372f0b1b963James Dong
3020c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3030c1bc742181ded4930842b46e9507372f0b1b963James Dong     * Used internally to
3040c1bc742181ded4930842b46e9507372f0b1b963James Dong     * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
3050c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3060c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
3070c1bc742181ded4930842b46e9507372f0b1b963James Dong
3080c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3090c1bc742181ded4930842b46e9507372f0b1b963James Dong     * Used internally to disable fail fast of mobile data
3100c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3110c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
3120c1bc742181ded4930842b46e9507372f0b1b963James Dong
3130c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3140c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to indicate that data sampling interval is up
3150c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3160c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
3170c1bc742181ded4930842b46e9507372f0b1b963James Dong
3180c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3190c1bc742181ded4930842b46e9507372f0b1b963James Dong     * PAC manager has received new port.
3200c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3210c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_PROXY_HAS_CHANGED = 16;
3220c1bc742181ded4930842b46e9507372f0b1b963James Dong
3230c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3240c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally when registering NetworkFactories
3250c1bc742181ded4930842b46e9507372f0b1b963James Dong     * obj = NetworkFactoryInfo
3260c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3270c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
3280c1bc742181ded4930842b46e9507372f0b1b963James Dong
3290c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3300c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally when registering NetworkAgents
3310c1bc742181ded4930842b46e9507372f0b1b963James Dong     * obj = Messenger
3320c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3330c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
3340c1bc742181ded4930842b46e9507372f0b1b963James Dong
3350c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3360c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used to add a network request
3370c1bc742181ded4930842b46e9507372f0b1b963James Dong     * includes a NetworkRequestInfo
3380c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3390c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
3400c1bc742181ded4930842b46e9507372f0b1b963James Dong
3410c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3420c1bc742181ded4930842b46e9507372f0b1b963James Dong     * indicates a timeout period is over - check if we had a network yet or not
3430c1bc742181ded4930842b46e9507372f0b1b963James Dong     * and if not, call the timeout calback (but leave the request live until they
3440c1bc742181ded4930842b46e9507372f0b1b963James Dong     * cancel it.
3450c1bc742181ded4930842b46e9507372f0b1b963James Dong     * includes a NetworkRequestInfo
3460c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3470c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
3480c1bc742181ded4930842b46e9507372f0b1b963James Dong
3490c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3500c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used to add a network listener - no request
3510c1bc742181ded4930842b46e9507372f0b1b963James Dong     * includes a NetworkRequestInfo
3520c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3530c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
3540c1bc742181ded4930842b46e9507372f0b1b963James Dong
3550c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3560c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used to remove a network request, either a listener or a real request
3570c1bc742181ded4930842b46e9507372f0b1b963James Dong     * arg1 = UID of caller
3580c1bc742181ded4930842b46e9507372f0b1b963James Dong     * obj  = NetworkRequest
3590c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3600c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
3610c1bc742181ded4930842b46e9507372f0b1b963James Dong
3620c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3630c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally when registering NetworkFactories
3640c1bc742181ded4930842b46e9507372f0b1b963James Dong     * obj = Messenger
3650c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3660c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
3670c1bc742181ded4930842b46e9507372f0b1b963James Dong
3680c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3690c1bc742181ded4930842b46e9507372f0b1b963James Dong     * used internally to expire a wakelock when transitioning
3700c1bc742181ded4930842b46e9507372f0b1b963James Dong     * from one net to another.  Expire happens when we fail to find
3710c1bc742181ded4930842b46e9507372f0b1b963James Dong     * a new network (typically after 1 minute) -
3720c1bc742181ded4930842b46e9507372f0b1b963James Dong     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
3730c1bc742181ded4930842b46e9507372f0b1b963James Dong     * a replacement network.
3740c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3750c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
3760c1bc742181ded4930842b46e9507372f0b1b963James Dong
3770c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
3780c1bc742181ded4930842b46e9507372f0b1b963James Dong     * Used internally to indicate the system is ready.
3790c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
3800c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int EVENT_SYSTEM_READY = 25;
3810c1bc742181ded4930842b46e9507372f0b1b963James Dong
3820c1bc742181ded4930842b46e9507372f0b1b963James Dong
3830c1bc742181ded4930842b46e9507372f0b1b963James Dong    /** Handler used for internal events. */
3840c1bc742181ded4930842b46e9507372f0b1b963James Dong    final private InternalHandler mHandler;
3850c1bc742181ded4930842b46e9507372f0b1b963James Dong    /** Handler used for incoming {@link NetworkStateTracker} events. */
3860c1bc742181ded4930842b46e9507372f0b1b963James Dong    final private NetworkStateTrackerHandler mTrackerHandler;
3870c1bc742181ded4930842b46e9507372f0b1b963James Dong
3880c1bc742181ded4930842b46e9507372f0b1b963James Dong    private boolean mSystemReady;
3890c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Intent mInitialBroadcast;
3900c1bc742181ded4930842b46e9507372f0b1b963James Dong
3910c1bc742181ded4930842b46e9507372f0b1b963James Dong    private PowerManager.WakeLock mNetTransitionWakeLock;
3920c1bc742181ded4930842b46e9507372f0b1b963James Dong    private String mNetTransitionWakeLockCausedBy = "";
3930c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mNetTransitionWakeLockSerialNumber;
3940c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mNetTransitionWakeLockTimeout;
3950c1bc742181ded4930842b46e9507372f0b1b963James Dong
3960c1bc742181ded4930842b46e9507372f0b1b963James Dong    private InetAddress mDefaultDns;
3970c1bc742181ded4930842b46e9507372f0b1b963James Dong
3980c1bc742181ded4930842b46e9507372f0b1b963James Dong    // used in DBG mode to track inet condition reports
3990c1bc742181ded4930842b46e9507372f0b1b963James Dong    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
4000c1bc742181ded4930842b46e9507372f0b1b963James Dong    private ArrayList mInetLog;
4010c1bc742181ded4930842b46e9507372f0b1b963James Dong
4020c1bc742181ded4930842b46e9507372f0b1b963James Dong    // track the current default http proxy - tell the world if we get a new one (real change)
4030c1bc742181ded4930842b46e9507372f0b1b963James Dong    private ProxyInfo mDefaultProxy = null;
4040c1bc742181ded4930842b46e9507372f0b1b963James Dong    private Object mProxyLock = new Object();
4050c1bc742181ded4930842b46e9507372f0b1b963James Dong    private boolean mDefaultProxyDisabled = false;
4060c1bc742181ded4930842b46e9507372f0b1b963James Dong
4070c1bc742181ded4930842b46e9507372f0b1b963James Dong    // track the global proxy.
4080c1bc742181ded4930842b46e9507372f0b1b963James Dong    private ProxyInfo mGlobalProxy = null;
4090c1bc742181ded4930842b46e9507372f0b1b963James Dong
4100c1bc742181ded4930842b46e9507372f0b1b963James Dong    private PacManager mPacManager = null;
4110c1bc742181ded4930842b46e9507372f0b1b963James Dong
4120c1bc742181ded4930842b46e9507372f0b1b963James Dong    private SettingsObserver mSettingsObserver;
4130c1bc742181ded4930842b46e9507372f0b1b963James Dong
4140c1bc742181ded4930842b46e9507372f0b1b963James Dong    private UserManager mUserManager;
4150c1bc742181ded4930842b46e9507372f0b1b963James Dong
4160c1bc742181ded4930842b46e9507372f0b1b963James Dong    NetworkConfig[] mNetConfigs;
4170c1bc742181ded4930842b46e9507372f0b1b963James Dong    int mNetworksDefined;
4180c1bc742181ded4930842b46e9507372f0b1b963James Dong
4190c1bc742181ded4930842b46e9507372f0b1b963James Dong    // the set of network types that can only be enabled by system/sig apps
4200c1bc742181ded4930842b46e9507372f0b1b963James Dong    List mProtectedNetworks;
4210c1bc742181ded4930842b46e9507372f0b1b963James Dong
4220c1bc742181ded4930842b46e9507372f0b1b963James Dong    private DataConnectionStats mDataConnectionStats;
4230c1bc742181ded4930842b46e9507372f0b1b963James Dong
4240c1bc742181ded4930842b46e9507372f0b1b963James Dong    private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
4250c1bc742181ded4930842b46e9507372f0b1b963James Dong
4260c1bc742181ded4930842b46e9507372f0b1b963James Dong    TelephonyManager mTelephonyManager;
4270c1bc742181ded4930842b46e9507372f0b1b963James Dong
4280c1bc742181ded4930842b46e9507372f0b1b963James Dong    // sequence number for Networks
4290c1bc742181ded4930842b46e9507372f0b1b963James Dong    private final static int MIN_NET_ID = 10; // some reserved marks
4300c1bc742181ded4930842b46e9507372f0b1b963James Dong    private final static int MAX_NET_ID = 65535;
4310c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mNextNetId = MIN_NET_ID;
4320c1bc742181ded4930842b46e9507372f0b1b963James Dong
4330c1bc742181ded4930842b46e9507372f0b1b963James Dong    // sequence number of NetworkRequests
4340c1bc742181ded4930842b46e9507372f0b1b963James Dong    private int mNextNetworkRequestId = 1;
4350c1bc742181ded4930842b46e9507372f0b1b963James Dong
4360c1bc742181ded4930842b46e9507372f0b1b963James Dong    /**
4370c1bc742181ded4930842b46e9507372f0b1b963James Dong     * Implements support for the legacy "one network per network type" model.
4380c1bc742181ded4930842b46e9507372f0b1b963James Dong     *
4390c1bc742181ded4930842b46e9507372f0b1b963James Dong     * We used to have a static array of NetworkStateTrackers, one for each
4400c1bc742181ded4930842b46e9507372f0b1b963James Dong     * network type, but that doesn't work any more now that we can have,
4410c1bc742181ded4930842b46e9507372f0b1b963James Dong     * for example, more that one wifi network. This class stores all the
4420c1bc742181ded4930842b46e9507372f0b1b963James Dong     * NetworkAgentInfo objects that support a given type, but the legacy
4430c1bc742181ded4930842b46e9507372f0b1b963James Dong     * API will only see the first one.
4440c1bc742181ded4930842b46e9507372f0b1b963James Dong     *
4450c1bc742181ded4930842b46e9507372f0b1b963James Dong     * It serves two main purposes:
4460c1bc742181ded4930842b46e9507372f0b1b963James Dong     *
4470c1bc742181ded4930842b46e9507372f0b1b963James Dong     * 1. Provide information about "the network for a given type" (since this
4480c1bc742181ded4930842b46e9507372f0b1b963James Dong     *    API only supports one).
4490c1bc742181ded4930842b46e9507372f0b1b963James Dong     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
4500c1bc742181ded4930842b46e9507372f0b1b963James Dong     *    the first network for a given type changes, or if the default network
4510c1bc742181ded4930842b46e9507372f0b1b963James Dong     *    changes.
4520c1bc742181ded4930842b46e9507372f0b1b963James Dong     */
4530c1bc742181ded4930842b46e9507372f0b1b963James Dong    private class LegacyTypeTracker {
4540c1bc742181ded4930842b46e9507372f0b1b963James Dong
4550c1bc742181ded4930842b46e9507372f0b1b963James Dong        private static final boolean DBG = true;
4560c1bc742181ded4930842b46e9507372f0b1b963James Dong        private static final boolean VDBG = false;
4570c1bc742181ded4930842b46e9507372f0b1b963James Dong        private static final String TAG = "CSLegacyTypeTracker";
4580c1bc742181ded4930842b46e9507372f0b1b963James Dong
4590c1bc742181ded4930842b46e9507372f0b1b963James Dong        /**
4600c1bc742181ded4930842b46e9507372f0b1b963James Dong         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
4610c1bc742181ded4930842b46e9507372f0b1b963James Dong         * Each list holds references to all NetworkAgentInfos that are used to
4620c1bc742181ded4930842b46e9507372f0b1b963James Dong         * satisfy requests for that network type.
4630c1bc742181ded4930842b46e9507372f0b1b963James Dong         *
4640c1bc742181ded4930842b46e9507372f0b1b963James Dong         * This array is built out at startup such that an unsupported network
4650c1bc742181ded4930842b46e9507372f0b1b963James Dong         * doesn't get an ArrayList instance, making this a tristate:
4660c1bc742181ded4930842b46e9507372f0b1b963James Dong         * unsupported, supported but not active and active.
4670c1bc742181ded4930842b46e9507372f0b1b963James Dong         *
4680c1bc742181ded4930842b46e9507372f0b1b963James Dong         * The actual lists are populated when we scan the network types that
4690c1bc742181ded4930842b46e9507372f0b1b963James Dong         * are supported on this device.
4700c1bc742181ded4930842b46e9507372f0b1b963James Dong         */
4710c1bc742181ded4930842b46e9507372f0b1b963James Dong        private ArrayList<NetworkAgentInfo> mTypeLists[];
4720c1bc742181ded4930842b46e9507372f0b1b963James Dong
4730c1bc742181ded4930842b46e9507372f0b1b963James Dong        public LegacyTypeTracker() {
4740c1bc742181ded4930842b46e9507372f0b1b963James Dong            mTypeLists = (ArrayList<NetworkAgentInfo>[])
4750c1bc742181ded4930842b46e9507372f0b1b963James Dong                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
4760c1bc742181ded4930842b46e9507372f0b1b963James Dong        }
4770c1bc742181ded4930842b46e9507372f0b1b963James Dong
4780c1bc742181ded4930842b46e9507372f0b1b963James Dong        public void addSupportedType(int type) {
4790c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (mTypeLists[type] != null) {
4800c1bc742181ded4930842b46e9507372f0b1b963James Dong                throw new IllegalStateException(
4810c1bc742181ded4930842b46e9507372f0b1b963James Dong                        "legacy list for type " + type + "already initialized");
4820c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
4830c1bc742181ded4930842b46e9507372f0b1b963James Dong            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
4840c1bc742181ded4930842b46e9507372f0b1b963James Dong        }
4850c1bc742181ded4930842b46e9507372f0b1b963James Dong
4860c1bc742181ded4930842b46e9507372f0b1b963James Dong        public boolean isTypeSupported(int type) {
4870c1bc742181ded4930842b46e9507372f0b1b963James Dong            return isNetworkTypeValid(type) && mTypeLists[type] != null;
4880c1bc742181ded4930842b46e9507372f0b1b963James Dong        }
4890c1bc742181ded4930842b46e9507372f0b1b963James Dong
4900c1bc742181ded4930842b46e9507372f0b1b963James Dong        public NetworkAgentInfo getNetworkForType(int type) {
4910c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
4920c1bc742181ded4930842b46e9507372f0b1b963James Dong                return mTypeLists[type].get(0);
4930c1bc742181ded4930842b46e9507372f0b1b963James Dong            } else {
4940c1bc742181ded4930842b46e9507372f0b1b963James Dong                return null;
4950c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
4960c1bc742181ded4930842b46e9507372f0b1b963James Dong        }
4970c1bc742181ded4930842b46e9507372f0b1b963James Dong
4980c1bc742181ded4930842b46e9507372f0b1b963James Dong        private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4990c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (DBG) {
5000c1bc742181ded4930842b46e9507372f0b1b963James Dong                log("Sending " + (connected ? "connected" : "disconnected") +
5010c1bc742181ded4930842b46e9507372f0b1b963James Dong                        " broadcast for type " + type + " " + nai.name() +
5020c1bc742181ded4930842b46e9507372f0b1b963James Dong                        " isDefaultNetwork=" + isDefaultNetwork(nai));
5030c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
5040c1bc742181ded4930842b46e9507372f0b1b963James Dong        }
5050c1bc742181ded4930842b46e9507372f0b1b963James Dong
5060c1bc742181ded4930842b46e9507372f0b1b963James Dong        /** Adds the given network to the specified legacy type list. */
5070c1bc742181ded4930842b46e9507372f0b1b963James Dong        public void add(int type, NetworkAgentInfo nai) {
5080c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (!isTypeSupported(type)) {
5090c1bc742181ded4930842b46e9507372f0b1b963James Dong                return;  // Invalid network type.
5100c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
5110c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
5120c1bc742181ded4930842b46e9507372f0b1b963James Dong
5130c1bc742181ded4930842b46e9507372f0b1b963James Dong            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
5140c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (list.contains(nai)) {
5150c1bc742181ded4930842b46e9507372f0b1b963James Dong                loge("Attempting to register duplicate agent for type " + type + ": " + nai);
5160c1bc742181ded4930842b46e9507372f0b1b963James Dong                return;
5170c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
5180c1bc742181ded4930842b46e9507372f0b1b963James Dong
5190c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (list.isEmpty() || isDefaultNetwork(nai)) {
5200c1bc742181ded4930842b46e9507372f0b1b963James Dong                maybeLogBroadcast(nai, true, type);
5210c1bc742181ded4930842b46e9507372f0b1b963James Dong                sendLegacyNetworkBroadcast(nai, true, type);
5220c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
5230c1bc742181ded4930842b46e9507372f0b1b963James Dong            list.add(nai);
5240c1bc742181ded4930842b46e9507372f0b1b963James Dong        }
5250c1bc742181ded4930842b46e9507372f0b1b963James Dong
5260c1bc742181ded4930842b46e9507372f0b1b963James Dong        /** Removes the given network from the specified legacy type list. */
5270c1bc742181ded4930842b46e9507372f0b1b963James Dong        public void remove(int type, NetworkAgentInfo nai) {
5280c1bc742181ded4930842b46e9507372f0b1b963James Dong            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
5290c1bc742181ded4930842b46e9507372f0b1b963James Dong            if (list == null || list.isEmpty()) {
5300c1bc742181ded4930842b46e9507372f0b1b963James Dong                return;
5310c1bc742181ded4930842b46e9507372f0b1b963James Dong            }
532
533            boolean wasFirstNetwork = list.get(0).equals(nai);
534
535            if (!list.remove(nai)) {
536                return;
537            }
538
539            if (wasFirstNetwork || isDefaultNetwork(nai)) {
540                maybeLogBroadcast(nai, false, type);
541                sendLegacyNetworkBroadcast(nai, false, type);
542            }
543
544            if (!list.isEmpty() && wasFirstNetwork) {
545                if (DBG) log("Other network available for type " + type +
546                              ", sending connected broadcast");
547                maybeLogBroadcast(list.get(0), false, type);
548                sendLegacyNetworkBroadcast(list.get(0), false, type);
549            }
550        }
551
552        /** Removes the given network from all legacy type lists. */
553        public void remove(NetworkAgentInfo nai) {
554            if (VDBG) log("Removing agent " + nai);
555            for (int type = 0; type < mTypeLists.length; type++) {
556                remove(type, nai);
557            }
558        }
559
560        private String naiToString(NetworkAgentInfo nai) {
561            String name = (nai != null) ? nai.name() : "null";
562            String state = (nai.networkInfo != null) ?
563                    nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
564                    "???/???";
565            return name + " " + state;
566        }
567
568        public void dump(IndentingPrintWriter pw) {
569            for (int type = 0; type < mTypeLists.length; type++) {
570                if (mTypeLists[type] == null) continue;
571                pw.print(type + " ");
572                pw.increaseIndent();
573                if (mTypeLists[type].size() == 0) pw.println("none");
574                for (NetworkAgentInfo nai : mTypeLists[type]) {
575                    pw.println(naiToString(nai));
576                }
577                pw.decreaseIndent();
578            }
579        }
580
581        // This class needs its own log method because it has a different TAG.
582        private void log(String s) {
583            Slog.d(TAG, s);
584        }
585
586    }
587    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
588
589    public ConnectivityService(Context context, INetworkManagementService netManager,
590            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
591        if (DBG) log("ConnectivityService starting up");
592
593        NetworkCapabilities netCap = new NetworkCapabilities();
594        netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
595        netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
596        mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
597        NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
598                NetworkRequestInfo.REQUEST);
599        mNetworkRequests.put(mDefaultRequest, nri);
600
601        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
602        handlerThread.start();
603        mHandler = new InternalHandler(handlerThread.getLooper());
604        mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
605
606        // setup our unique device name
607        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
608            String id = Settings.Secure.getString(context.getContentResolver(),
609                    Settings.Secure.ANDROID_ID);
610            if (id != null && id.length() > 0) {
611                String name = new String("android-").concat(id);
612                SystemProperties.set("net.hostname", name);
613            }
614        }
615
616        // read our default dns server ip
617        String dns = Settings.Global.getString(context.getContentResolver(),
618                Settings.Global.DEFAULT_DNS_SERVER);
619        if (dns == null || dns.length() == 0) {
620            dns = context.getResources().getString(
621                    com.android.internal.R.string.config_default_dns_server);
622        }
623        try {
624            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
625        } catch (IllegalArgumentException e) {
626            loge("Error setting defaultDns using " + dns);
627        }
628
629        mContext = checkNotNull(context, "missing Context");
630        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
631        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
632        mKeyStore = KeyStore.getInstance();
633        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
634
635        try {
636            mPolicyManager.registerListener(mPolicyListener);
637        } catch (RemoteException e) {
638            // ouch, no rules updates means some processes may never get network
639            loge("unable to register INetworkPolicyListener" + e.toString());
640        }
641
642        final PowerManager powerManager = (PowerManager) context.getSystemService(
643                Context.POWER_SERVICE);
644        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
645        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
646                com.android.internal.R.integer.config_networkTransitionTimeout);
647
648        mNetTrackers = new NetworkStateTracker[
649                ConnectivityManager.MAX_NETWORK_TYPE+1];
650
651        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
652
653        // TODO: What is the "correct" way to do determine if this is a wifi only device?
654        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
655        log("wifiOnly=" + wifiOnly);
656        String[] naStrings = context.getResources().getStringArray(
657                com.android.internal.R.array.networkAttributes);
658        for (String naString : naStrings) {
659            try {
660                NetworkConfig n = new NetworkConfig(naString);
661                if (VDBG) log("naString=" + naString + " config=" + n);
662                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
663                    loge("Error in networkAttributes - ignoring attempt to define type " +
664                            n.type);
665                    continue;
666                }
667                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
668                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
669                            n.type);
670                    continue;
671                }
672                if (mNetConfigs[n.type] != null) {
673                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
674                            n.type);
675                    continue;
676                }
677                mLegacyTypeTracker.addSupportedType(n.type);
678
679                mNetConfigs[n.type] = n;
680                mNetworksDefined++;
681            } catch(Exception e) {
682                // ignore it - leave the entry null
683            }
684        }
685        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
686
687        mProtectedNetworks = new ArrayList<Integer>();
688        int[] protectedNetworks = context.getResources().getIntArray(
689                com.android.internal.R.array.config_protectedNetworks);
690        for (int p : protectedNetworks) {
691            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
692                mProtectedNetworks.add(p);
693            } else {
694                if (DBG) loge("Ignoring protectedNetwork " + p);
695            }
696        }
697
698        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
699                && SystemProperties.get("ro.build.type").equals("eng");
700
701        mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
702
703        //set up the listener for user state for creating user VPNs
704        IntentFilter intentFilter = new IntentFilter();
705        intentFilter.addAction(Intent.ACTION_USER_STARTING);
706        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
707        mContext.registerReceiverAsUser(
708                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
709        mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
710
711        try {
712            mNetd.registerObserver(mTethering);
713            mNetd.registerObserver(mDataActivityObserver);
714            mNetd.registerObserver(mClat);
715        } catch (RemoteException e) {
716            loge("Error registering observer :" + e);
717        }
718
719        if (DBG) {
720            mInetLog = new ArrayList();
721        }
722
723        mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
724        mSettingsObserver.observe(mContext);
725
726        mDataConnectionStats = new DataConnectionStats(mContext);
727        mDataConnectionStats.startMonitoring();
728
729        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
730
731        IntentFilter filter = new IntentFilter();
732        filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
733        mContext.registerReceiver(
734                new BroadcastReceiver() {
735                    @Override
736                    public void onReceive(Context context, Intent intent) {
737                        String action = intent.getAction();
738                        if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
739                            mHandler.sendMessage(mHandler.obtainMessage
740                                    (EVENT_SAMPLE_INTERVAL_ELAPSED));
741                        }
742                    }
743                },
744                new IntentFilter(filter));
745
746        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
747
748        filter = new IntentFilter();
749        filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
750        mContext.registerReceiver(mProvisioningReceiver, filter);
751
752        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
753    }
754
755    private synchronized int nextNetworkRequestId() {
756        return mNextNetworkRequestId++;
757    }
758
759    private void assignNextNetId(NetworkAgentInfo nai) {
760        synchronized (mNetworkForNetId) {
761            for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
762                int netId = mNextNetId;
763                if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
764                // Make sure NetID unused.  http://b/16815182
765                if (mNetworkForNetId.get(netId) == null) {
766                    nai.network = new Network(netId);
767                    mNetworkForNetId.put(netId, nai);
768                    return;
769                }
770            }
771        }
772        throw new IllegalStateException("No free netIds");
773    }
774
775    private int getConnectivityChangeDelay() {
776        final ContentResolver cr = mContext.getContentResolver();
777
778        /** Check system properties for the default value then use secure settings value, if any. */
779        int defaultDelay = SystemProperties.getInt(
780                "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
781                ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
782        return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
783                defaultDelay);
784    }
785
786    private boolean teardown(NetworkStateTracker netTracker) {
787        if (netTracker.teardown()) {
788            netTracker.setTeardownRequested(true);
789            return true;
790        } else {
791            return false;
792        }
793    }
794
795    /**
796     * Check if UID should be blocked from using the network represented by the
797     * given {@link NetworkStateTracker}.
798     */
799    private boolean isNetworkBlocked(int networkType, int uid) {
800        final boolean networkCostly;
801        final int uidRules;
802
803        LinkProperties lp = getLinkPropertiesForType(networkType);
804        final String iface = (lp == null ? "" : lp.getInterfaceName());
805        synchronized (mRulesLock) {
806            networkCostly = mMeteredIfaces.contains(iface);
807            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
808        }
809
810        if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
811            return true;
812        }
813
814        // no restrictive rules; network is visible
815        return false;
816    }
817
818    /**
819     * Return a filtered {@link NetworkInfo}, potentially marked
820     * {@link DetailedState#BLOCKED} based on
821     * {@link #isNetworkBlocked}.
822     */
823    private NetworkInfo getFilteredNetworkInfo(int networkType, int uid) {
824        NetworkInfo info = getNetworkInfoForType(networkType);
825        return getFilteredNetworkInfo(info, networkType, uid);
826    }
827
828    private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, int networkType, int uid) {
829        if (isNetworkBlocked(networkType, uid)) {
830            // network is blocked; clone and override state
831            info = new NetworkInfo(info);
832            info.setDetailedState(DetailedState.BLOCKED, null, null);
833            if (DBG) log("returning Blocked NetworkInfo");
834        }
835        if (mLockdownTracker != null) {
836            info = mLockdownTracker.augmentNetworkInfo(info);
837            if (DBG) log("returning Locked NetworkInfo");
838        }
839        return info;
840    }
841
842    /**
843     * Return NetworkInfo for the active (i.e., connected) network interface.
844     * It is assumed that at most one network is active at a time. If more
845     * than one is active, it is indeterminate which will be returned.
846     * @return the info for the active network, or {@code null} if none is
847     * active
848     */
849    @Override
850    public NetworkInfo getActiveNetworkInfo() {
851        enforceAccessPermission();
852        final int uid = Binder.getCallingUid();
853        return getNetworkInfo(mActiveDefaultNetwork, uid);
854    }
855
856    // only called when the default request is satisfied
857    private void updateActiveDefaultNetwork(NetworkAgentInfo nai) {
858        if (nai != null) {
859            mActiveDefaultNetwork = nai.networkInfo.getType();
860        } else {
861            mActiveDefaultNetwork = TYPE_NONE;
862        }
863    }
864
865    /**
866     * Find the first Provisioning network.
867     *
868     * @return NetworkInfo or null if none.
869     */
870    private NetworkInfo getProvisioningNetworkInfo() {
871        enforceAccessPermission();
872
873        // Find the first Provisioning Network
874        NetworkInfo provNi = null;
875        for (NetworkInfo ni : getAllNetworkInfo()) {
876            if (ni.isConnectedToProvisioningNetwork()) {
877                provNi = ni;
878                break;
879            }
880        }
881        if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
882        return provNi;
883    }
884
885    /**
886     * Find the first Provisioning network or the ActiveDefaultNetwork
887     * if there is no Provisioning network
888     *
889     * @return NetworkInfo or null if none.
890     */
891    @Override
892    public NetworkInfo getProvisioningOrActiveNetworkInfo() {
893        enforceAccessPermission();
894
895        NetworkInfo provNi = getProvisioningNetworkInfo();
896        if (provNi == null) {
897            final int uid = Binder.getCallingUid();
898            provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
899        }
900        if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
901        return provNi;
902    }
903
904    public NetworkInfo getActiveNetworkInfoUnfiltered() {
905        enforceAccessPermission();
906        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
907            return getNetworkInfoForType(mActiveDefaultNetwork);
908        }
909        return null;
910    }
911
912    @Override
913    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
914        enforceConnectivityInternalPermission();
915        return getNetworkInfo(mActiveDefaultNetwork, uid);
916    }
917
918    @Override
919    public NetworkInfo getNetworkInfo(int networkType) {
920        enforceAccessPermission();
921        final int uid = Binder.getCallingUid();
922        return getNetworkInfo(networkType, uid);
923    }
924
925    private NetworkInfo getNetworkInfo(int networkType, int uid) {
926        NetworkInfo info = null;
927        if (isNetworkTypeValid(networkType)) {
928            if (getNetworkInfoForType(networkType) != null) {
929                info = getFilteredNetworkInfo(networkType, uid);
930            }
931        }
932        return info;
933    }
934
935    @Override
936    public NetworkInfo getNetworkInfoForNetwork(Network network) {
937        enforceAccessPermission();
938        if (network == null) return null;
939
940        final int uid = Binder.getCallingUid();
941        NetworkAgentInfo nai = null;
942        synchronized (mNetworkForNetId) {
943            nai = mNetworkForNetId.get(network.netId);
944        }
945        if (nai == null) return null;
946        synchronized (nai) {
947            if (nai.networkInfo == null) return null;
948
949            return getFilteredNetworkInfo(nai.networkInfo, nai.networkInfo.getType(), uid);
950        }
951    }
952
953    @Override
954    public NetworkInfo[] getAllNetworkInfo() {
955        enforceAccessPermission();
956        final int uid = Binder.getCallingUid();
957        final ArrayList<NetworkInfo> result = Lists.newArrayList();
958        synchronized (mRulesLock) {
959            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
960                    networkType++) {
961                if (getNetworkInfoForType(networkType) != null) {
962                    result.add(getFilteredNetworkInfo(networkType, uid));
963                }
964            }
965        }
966        return result.toArray(new NetworkInfo[result.size()]);
967    }
968
969    @Override
970    public Network getNetworkForType(int networkType) {
971        enforceAccessPermission();
972        final int uid = Binder.getCallingUid();
973        if (isNetworkBlocked(networkType, uid)) {
974            return null;
975        }
976        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
977        return (nai == null) ? null : nai.network;
978    }
979
980    @Override
981    public Network[] getAllNetworks() {
982        enforceAccessPermission();
983        final ArrayList<Network> result = new ArrayList();
984        synchronized (mNetworkForNetId) {
985            for (int i = 0; i < mNetworkForNetId.size(); i++) {
986                result.add(new Network(mNetworkForNetId.valueAt(i).network));
987            }
988        }
989        return result.toArray(new Network[result.size()]);
990    }
991
992    @Override
993    public boolean isNetworkSupported(int networkType) {
994        enforceAccessPermission();
995        return (isNetworkTypeValid(networkType) && (getNetworkInfoForType(networkType) != null));
996    }
997
998    /**
999     * Return LinkProperties for the active (i.e., connected) default
1000     * network interface.  It is assumed that at most one default network
1001     * is active at a time. If more than one is active, it is indeterminate
1002     * which will be returned.
1003     * @return the ip properties for the active network, or {@code null} if
1004     * none is active
1005     */
1006    @Override
1007    public LinkProperties getActiveLinkProperties() {
1008        return getLinkPropertiesForType(mActiveDefaultNetwork);
1009    }
1010
1011    @Override
1012    public LinkProperties getLinkPropertiesForType(int networkType) {
1013        enforceAccessPermission();
1014        if (isNetworkTypeValid(networkType)) {
1015            return getLinkPropertiesForTypeInternal(networkType);
1016        }
1017        return null;
1018    }
1019
1020    // TODO - this should be ALL networks
1021    @Override
1022    public LinkProperties getLinkProperties(Network network) {
1023        enforceAccessPermission();
1024        NetworkAgentInfo nai = null;
1025        synchronized (mNetworkForNetId) {
1026            nai = mNetworkForNetId.get(network.netId);
1027        }
1028
1029        if (nai != null) {
1030            synchronized (nai) {
1031                return new LinkProperties(nai.linkProperties);
1032            }
1033        }
1034        return null;
1035    }
1036
1037    @Override
1038    public NetworkCapabilities getNetworkCapabilities(Network network) {
1039        enforceAccessPermission();
1040        NetworkAgentInfo nai = null;
1041        synchronized (mNetworkForNetId) {
1042            nai = mNetworkForNetId.get(network.netId);
1043        }
1044        if (nai != null) {
1045            synchronized (nai) {
1046                return new NetworkCapabilities(nai.networkCapabilities);
1047            }
1048        }
1049        return null;
1050    }
1051
1052    @Override
1053    public NetworkState[] getAllNetworkState() {
1054        enforceAccessPermission();
1055        final int uid = Binder.getCallingUid();
1056        final ArrayList<NetworkState> result = Lists.newArrayList();
1057        synchronized (mRulesLock) {
1058            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1059                    networkType++) {
1060                if (getNetworkInfoForType(networkType) != null) {
1061                    final NetworkInfo info = getFilteredNetworkInfo(networkType, uid);
1062                    final LinkProperties lp = getLinkPropertiesForTypeInternal(networkType);
1063                    final NetworkCapabilities netcap = getNetworkCapabilitiesForType(networkType);
1064                    result.add(new NetworkState(info, lp, netcap));
1065                }
1066            }
1067        }
1068        return result.toArray(new NetworkState[result.size()]);
1069    }
1070
1071    private NetworkState getNetworkStateUnchecked(int networkType) {
1072        if (isNetworkTypeValid(networkType)) {
1073            NetworkInfo info = getNetworkInfoForType(networkType);
1074            if (info != null) {
1075                return new NetworkState(info,
1076                        getLinkPropertiesForTypeInternal(networkType),
1077                        getNetworkCapabilitiesForType(networkType));
1078            }
1079        }
1080        return null;
1081    }
1082
1083    @Override
1084    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1085        enforceAccessPermission();
1086
1087        final long token = Binder.clearCallingIdentity();
1088        try {
1089            final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1090            if (state != null) {
1091                try {
1092                    return mPolicyManager.getNetworkQuotaInfo(state);
1093                } catch (RemoteException e) {
1094                }
1095            }
1096            return null;
1097        } finally {
1098            Binder.restoreCallingIdentity(token);
1099        }
1100    }
1101
1102    @Override
1103    public boolean isActiveNetworkMetered() {
1104        enforceAccessPermission();
1105        final long token = Binder.clearCallingIdentity();
1106        try {
1107            return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1108        } finally {
1109            Binder.restoreCallingIdentity(token);
1110        }
1111    }
1112
1113    private boolean isNetworkMeteredUnchecked(int networkType) {
1114        final NetworkState state = getNetworkStateUnchecked(networkType);
1115        if (state != null) {
1116            try {
1117                return mPolicyManager.isNetworkMetered(state);
1118            } catch (RemoteException e) {
1119            }
1120        }
1121        return false;
1122    }
1123
1124    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1125        @Override
1126        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1127            int deviceType = Integer.parseInt(label);
1128            sendDataActivityBroadcast(deviceType, active, tsNanos);
1129        }
1130    };
1131
1132    /**
1133     * Ensure that a network route exists to deliver traffic to the specified
1134     * host via the specified network interface.
1135     * @param networkType the type of the network over which traffic to the
1136     * specified host is to be routed
1137     * @param hostAddress the IP address of the host to which the route is
1138     * desired
1139     * @return {@code true} on success, {@code false} on failure
1140     */
1141    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1142        enforceChangePermission();
1143        if (mProtectedNetworks.contains(networkType)) {
1144            enforceConnectivityInternalPermission();
1145        }
1146
1147        InetAddress addr;
1148        try {
1149            addr = InetAddress.getByAddress(hostAddress);
1150        } catch (UnknownHostException e) {
1151            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1152            return false;
1153        }
1154
1155        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1156            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1157            return false;
1158        }
1159
1160        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1161        if (nai == null) {
1162            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1163                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1164            } else {
1165                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1166            }
1167            return false;
1168        }
1169
1170        DetailedState netState;
1171        synchronized (nai) {
1172            netState = nai.networkInfo.getDetailedState();
1173        }
1174
1175        if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
1176            if (VDBG) {
1177                log("requestRouteToHostAddress on down network "
1178                        + "(" + networkType + ") - dropped"
1179                        + " netState=" + netState);
1180            }
1181            return false;
1182        }
1183
1184        final int uid = Binder.getCallingUid();
1185        final long token = Binder.clearCallingIdentity();
1186        try {
1187            LinkProperties lp;
1188            int netId;
1189            synchronized (nai) {
1190                lp = nai.linkProperties;
1191                netId = nai.network.netId;
1192            }
1193            boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
1194            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1195            return ok;
1196        } finally {
1197            Binder.restoreCallingIdentity(token);
1198        }
1199    }
1200
1201    private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
1202        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1203        if (bestRoute == null) {
1204            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1205        } else {
1206            String iface = bestRoute.getInterface();
1207            if (bestRoute.getGateway().equals(addr)) {
1208                // if there is no better route, add the implied hostroute for our gateway
1209                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1210            } else {
1211                // if we will connect to this through another route, add a direct route
1212                // to it's gateway
1213                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1214            }
1215        }
1216        if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
1217        try {
1218            mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1219        } catch (Exception e) {
1220            // never crash - catch them all
1221            if (DBG) loge("Exception trying to add a route: " + e);
1222            return false;
1223        }
1224        return true;
1225    }
1226
1227    public void setDataDependency(int networkType, boolean met) {
1228        enforceConnectivityInternalPermission();
1229
1230        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1231                (met ? ENABLED : DISABLED), networkType));
1232    }
1233
1234    private void handleSetDependencyMet(int networkType, boolean met) {
1235        if (mNetTrackers[networkType] != null) {
1236            if (DBG) {
1237                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1238            }
1239            mNetTrackers[networkType].setDependencyMet(met);
1240        }
1241    }
1242
1243    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1244        @Override
1245        public void onUidRulesChanged(int uid, int uidRules) {
1246            // caller is NPMS, since we only register with them
1247            if (LOGD_RULES) {
1248                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1249            }
1250
1251            synchronized (mRulesLock) {
1252                // skip update when we've already applied rules
1253                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1254                if (oldRules == uidRules) return;
1255
1256                mUidRules.put(uid, uidRules);
1257            }
1258
1259            // TODO: notify UID when it has requested targeted updates
1260        }
1261
1262        @Override
1263        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1264            // caller is NPMS, since we only register with them
1265            if (LOGD_RULES) {
1266                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1267            }
1268
1269            synchronized (mRulesLock) {
1270                mMeteredIfaces.clear();
1271                for (String iface : meteredIfaces) {
1272                    mMeteredIfaces.add(iface);
1273                }
1274            }
1275        }
1276
1277        @Override
1278        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1279            // caller is NPMS, since we only register with them
1280            if (LOGD_RULES) {
1281                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1282            }
1283
1284            // kick off connectivity change broadcast for active network, since
1285            // global background policy change is radical.
1286            final int networkType = mActiveDefaultNetwork;
1287            if (isNetworkTypeValid(networkType)) {
1288                final NetworkStateTracker tracker = mNetTrackers[networkType];
1289                if (tracker != null) {
1290                    final NetworkInfo info = tracker.getNetworkInfo();
1291                    if (info != null && info.isConnected()) {
1292                        sendConnectedBroadcast(info);
1293                    }
1294                }
1295            }
1296        }
1297    };
1298
1299    @Override
1300    public void setPolicyDataEnable(int networkType, boolean enabled) {
1301        // only someone like NPMS should only be calling us
1302        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1303
1304        mHandler.sendMessage(mHandler.obtainMessage(
1305                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1306    }
1307
1308    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1309   // TODO - handle this passing to factories
1310//        if (isNetworkTypeValid(networkType)) {
1311//            final NetworkStateTracker tracker = mNetTrackers[networkType];
1312//            if (tracker != null) {
1313//                tracker.setPolicyDataEnable(enabled);
1314//            }
1315//        }
1316    }
1317
1318    private void enforceAccessPermission() {
1319        mContext.enforceCallingOrSelfPermission(
1320                android.Manifest.permission.ACCESS_NETWORK_STATE,
1321                "ConnectivityService");
1322    }
1323
1324    private void enforceChangePermission() {
1325        mContext.enforceCallingOrSelfPermission(
1326                android.Manifest.permission.CHANGE_NETWORK_STATE,
1327                "ConnectivityService");
1328    }
1329
1330    // TODO Make this a special check when it goes public
1331    private void enforceTetherChangePermission() {
1332        mContext.enforceCallingOrSelfPermission(
1333                android.Manifest.permission.CHANGE_NETWORK_STATE,
1334                "ConnectivityService");
1335    }
1336
1337    private void enforceTetherAccessPermission() {
1338        mContext.enforceCallingOrSelfPermission(
1339                android.Manifest.permission.ACCESS_NETWORK_STATE,
1340                "ConnectivityService");
1341    }
1342
1343    private void enforceConnectivityInternalPermission() {
1344        mContext.enforceCallingOrSelfPermission(
1345                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1346                "ConnectivityService");
1347    }
1348
1349    public void sendConnectedBroadcast(NetworkInfo info) {
1350        enforceConnectivityInternalPermission();
1351        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1352        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1353    }
1354
1355    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1356        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1357        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1358    }
1359
1360    private void sendInetConditionBroadcast(NetworkInfo info) {
1361        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1362    }
1363
1364    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1365        if (mLockdownTracker != null) {
1366            info = mLockdownTracker.augmentNetworkInfo(info);
1367        }
1368
1369        Intent intent = new Intent(bcastType);
1370        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1371        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1372        if (info.isFailover()) {
1373            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1374            info.setFailover(false);
1375        }
1376        if (info.getReason() != null) {
1377            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1378        }
1379        if (info.getExtraInfo() != null) {
1380            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1381                    info.getExtraInfo());
1382        }
1383        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1384        return intent;
1385    }
1386
1387    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1388        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1389    }
1390
1391    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1392        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1393    }
1394
1395    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
1396        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1397        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1398        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1399        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
1400        final long ident = Binder.clearCallingIdentity();
1401        try {
1402            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1403                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1404        } finally {
1405            Binder.restoreCallingIdentity(ident);
1406        }
1407    }
1408
1409    private void sendStickyBroadcast(Intent intent) {
1410        synchronized(this) {
1411            if (!mSystemReady) {
1412                mInitialBroadcast = new Intent(intent);
1413            }
1414            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1415            if (DBG) {
1416                log("sendStickyBroadcast: action=" + intent.getAction());
1417            }
1418
1419            final long ident = Binder.clearCallingIdentity();
1420            try {
1421                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1422            } finally {
1423                Binder.restoreCallingIdentity(ident);
1424            }
1425        }
1426    }
1427
1428    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1429        if (delayMs <= 0) {
1430            sendStickyBroadcast(intent);
1431        } else {
1432            if (VDBG) {
1433                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1434                        + intent.getAction());
1435            }
1436            mHandler.sendMessageDelayed(mHandler.obtainMessage(
1437                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1438        }
1439    }
1440
1441    void systemReady() {
1442        // start network sampling ..
1443        Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
1444        intent.setPackage(mContext.getPackageName());
1445
1446        mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
1447                SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
1448        setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
1449
1450        loadGlobalProxy();
1451
1452        synchronized(this) {
1453            mSystemReady = true;
1454            if (mInitialBroadcast != null) {
1455                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1456                mInitialBroadcast = null;
1457            }
1458        }
1459        // load the global proxy at startup
1460        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1461
1462        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1463        // for user to unlock device.
1464        if (!updateLockdownVpn()) {
1465            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1466            mContext.registerReceiver(mUserPresentReceiver, filter);
1467        }
1468
1469        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
1470    }
1471
1472    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1473        @Override
1474        public void onReceive(Context context, Intent intent) {
1475            // Try creating lockdown tracker, since user present usually means
1476            // unlocked keystore.
1477            if (updateLockdownVpn()) {
1478                mContext.unregisterReceiver(this);
1479            }
1480        }
1481    };
1482
1483    /** @hide */
1484    @Override
1485    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1486        enforceConnectivityInternalPermission();
1487        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
1488//        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
1489    }
1490
1491    /**
1492     * Setup data activity tracking for the given network.
1493     *
1494     * Every {@code setupDataActivityTracking} should be paired with a
1495     * {@link #removeDataActivityTracking} for cleanup.
1496     */
1497    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1498        final String iface = networkAgent.linkProperties.getInterfaceName();
1499
1500        final int timeout;
1501        int type = ConnectivityManager.TYPE_NONE;
1502
1503        if (networkAgent.networkCapabilities.hasTransport(
1504                NetworkCapabilities.TRANSPORT_CELLULAR)) {
1505            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1506                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
1507                                             5);
1508            type = ConnectivityManager.TYPE_MOBILE;
1509        } else if (networkAgent.networkCapabilities.hasTransport(
1510                NetworkCapabilities.TRANSPORT_WIFI)) {
1511            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1512                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
1513                                             0);
1514            type = ConnectivityManager.TYPE_WIFI;
1515        } else {
1516            // do not track any other networks
1517            timeout = 0;
1518        }
1519
1520        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
1521            try {
1522                mNetd.addIdleTimer(iface, timeout, type);
1523            } catch (Exception e) {
1524                // You shall not crash!
1525                loge("Exception in setupDataActivityTracking " + e);
1526            }
1527        }
1528    }
1529
1530    /**
1531     * Remove data activity tracking when network disconnects.
1532     */
1533    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1534        final String iface = networkAgent.linkProperties.getInterfaceName();
1535        final NetworkCapabilities caps = networkAgent.networkCapabilities;
1536
1537        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1538                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
1539            try {
1540                // the call fails silently if no idletimer setup for this interface
1541                mNetd.removeIdleTimer(iface);
1542            } catch (Exception e) {
1543                loge("Exception in removeDataActivityTracking " + e);
1544            }
1545        }
1546    }
1547
1548    /**
1549     * Reads the network specific MTU size from reources.
1550     * and set it on it's iface.
1551     */
1552    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1553        final String iface = newLp.getInterfaceName();
1554        final int mtu = newLp.getMtu();
1555        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1556            if (VDBG) log("identical MTU - not setting");
1557            return;
1558        }
1559
1560        if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
1561            loge("Unexpected mtu value: " + mtu + ", " + iface);
1562            return;
1563        }
1564
1565        // Cannot set MTU without interface name
1566        if (TextUtils.isEmpty(iface)) {
1567            loge("Setting MTU size with null iface.");
1568            return;
1569        }
1570
1571        try {
1572            if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
1573            mNetd.setMtu(iface, mtu);
1574        } catch (Exception e) {
1575            Slog.e(TAG, "exception in setMtu()" + e);
1576        }
1577    }
1578
1579    private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
1580
1581    private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1582        if (isDefaultNetwork(nai) == false) {
1583            return;
1584        }
1585
1586        String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1587        String[] values = null;
1588        if (tcpBufferSizes != null) {
1589            values = tcpBufferSizes.split(",");
1590        }
1591
1592        if (values == null || values.length != 6) {
1593            if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
1594            tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1595            values = tcpBufferSizes.split(",");
1596        }
1597
1598        if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1599
1600        try {
1601            if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
1602
1603            final String prefix = "/sys/kernel/ipv4/tcp_";
1604            FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1605            FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1606            FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1607            FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1608            FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1609            FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1610            mCurrentTcpBufferSizes = tcpBufferSizes;
1611        } catch (IOException e) {
1612            loge("Can't set TCP buffer sizes:" + e);
1613        }
1614
1615        final String defaultRwndKey = "net.tcp.default_init_rwnd";
1616        int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1617        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1618            Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1619        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1620        if (rwndValue != 0) {
1621            SystemProperties.set(sysctlKey, rwndValue.toString());
1622        }
1623    }
1624
1625    private void flushVmDnsCache() {
1626        /*
1627         * Tell the VMs to toss their DNS caches
1628         */
1629        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1630        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1631        /*
1632         * Connectivity events can happen before boot has completed ...
1633         */
1634        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1635        final long ident = Binder.clearCallingIdentity();
1636        try {
1637            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1638        } finally {
1639            Binder.restoreCallingIdentity(ident);
1640        }
1641    }
1642
1643    @Override
1644    public int getRestoreDefaultNetworkDelay(int networkType) {
1645        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1646                NETWORK_RESTORE_DELAY_PROP_NAME);
1647        if(restoreDefaultNetworkDelayStr != null &&
1648                restoreDefaultNetworkDelayStr.length() != 0) {
1649            try {
1650                return Integer.valueOf(restoreDefaultNetworkDelayStr);
1651            } catch (NumberFormatException e) {
1652            }
1653        }
1654        // if the system property isn't set, use the value for the apn type
1655        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1656
1657        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1658                (mNetConfigs[networkType] != null)) {
1659            ret = mNetConfigs[networkType].restoreTime;
1660        }
1661        return ret;
1662    }
1663
1664    @Override
1665    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1666        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1667        if (mContext.checkCallingOrSelfPermission(
1668                android.Manifest.permission.DUMP)
1669                != PackageManager.PERMISSION_GRANTED) {
1670            pw.println("Permission Denial: can't dump ConnectivityService " +
1671                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1672                    Binder.getCallingUid());
1673            return;
1674        }
1675
1676        pw.println("NetworkFactories for:");
1677        pw.increaseIndent();
1678        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1679            pw.println(nfi.name);
1680        }
1681        pw.decreaseIndent();
1682        pw.println();
1683
1684        NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1685        pw.print("Active default network: ");
1686        if (defaultNai == null) {
1687            pw.println("none");
1688        } else {
1689            pw.println(defaultNai.network.netId);
1690        }
1691        pw.println();
1692
1693        pw.println("Current Networks:");
1694        pw.increaseIndent();
1695        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1696            pw.println(nai.toString());
1697            pw.increaseIndent();
1698            pw.println("Requests:");
1699            pw.increaseIndent();
1700            for (int i = 0; i < nai.networkRequests.size(); i++) {
1701                pw.println(nai.networkRequests.valueAt(i).toString());
1702            }
1703            pw.decreaseIndent();
1704            pw.println("Lingered:");
1705            pw.increaseIndent();
1706            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1707            pw.decreaseIndent();
1708            pw.decreaseIndent();
1709        }
1710        pw.decreaseIndent();
1711        pw.println();
1712
1713        pw.println("Network Requests:");
1714        pw.increaseIndent();
1715        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1716            pw.println(nri.toString());
1717        }
1718        pw.println();
1719        pw.decreaseIndent();
1720
1721        pw.print("mActiveDefaultNetwork: " + mActiveDefaultNetwork);
1722        if (mActiveDefaultNetwork != TYPE_NONE) {
1723            NetworkInfo activeNetworkInfo = getActiveNetworkInfo();
1724            if (activeNetworkInfo != null) {
1725                pw.print(" " + activeNetworkInfo.getState() +
1726                         "/" + activeNetworkInfo.getDetailedState());
1727            }
1728        }
1729        pw.println();
1730
1731        pw.println("mLegacyTypeTracker:");
1732        pw.increaseIndent();
1733        mLegacyTypeTracker.dump(pw);
1734        pw.decreaseIndent();
1735        pw.println();
1736
1737        synchronized (this) {
1738            pw.println("NetworkTransitionWakeLock is currently " +
1739                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1740            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1741        }
1742        pw.println();
1743
1744        mTethering.dump(fd, pw, args);
1745
1746        if (mInetLog != null) {
1747            pw.println();
1748            pw.println("Inet condition reports:");
1749            pw.increaseIndent();
1750            for(int i = 0; i < mInetLog.size(); i++) {
1751                pw.println(mInetLog.get(i));
1752            }
1753            pw.decreaseIndent();
1754        }
1755    }
1756
1757    private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
1758        final NetworkAgentInfo officialNai;
1759        synchronized (mNetworkForNetId) {
1760            officialNai = mNetworkForNetId.get(nai.network.netId);
1761        }
1762        if (officialNai != null && officialNai.equals(nai)) return true;
1763        if (officialNai != null || VDBG) {
1764            loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
1765                " - " + nai);
1766        }
1767        return false;
1768    }
1769
1770    // must be stateless - things change under us.
1771    private class NetworkStateTrackerHandler extends Handler {
1772        public NetworkStateTrackerHandler(Looper looper) {
1773            super(looper);
1774        }
1775
1776        @Override
1777        public void handleMessage(Message msg) {
1778            NetworkInfo info;
1779            switch (msg.what) {
1780                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
1781                    handleAsyncChannelHalfConnect(msg);
1782                    break;
1783                }
1784                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1785                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1786                    if (nai != null) nai.asyncChannel.disconnect();
1787                    break;
1788                }
1789                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1790                    handleAsyncChannelDisconnected(msg);
1791                    break;
1792                }
1793                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1794                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1795                    if (nai == null) {
1796                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1797                    } else {
1798                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
1799                    }
1800                    break;
1801                }
1802                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1803                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1804                    if (nai == null) {
1805                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1806                    } else {
1807                        if (VDBG) {
1808                            log("Update of LinkProperties for " + nai.name() +
1809                                    "; created=" + nai.created);
1810                        }
1811                        LinkProperties oldLp = nai.linkProperties;
1812                        synchronized (nai) {
1813                            nai.linkProperties = (LinkProperties)msg.obj;
1814                        }
1815                        if (nai.created) updateLinkProperties(nai, oldLp);
1816                    }
1817                    break;
1818                }
1819                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1820                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1821                    if (nai == null) {
1822                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1823                        break;
1824                    }
1825                    info = (NetworkInfo) msg.obj;
1826                    updateNetworkInfo(nai, info);
1827                    break;
1828                }
1829                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1830                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1831                    if (nai == null) {
1832                        loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1833                        break;
1834                    }
1835                    Integer score = (Integer) msg.obj;
1836                    if (score != null) updateNetworkScore(nai, score.intValue());
1837                    break;
1838                }
1839                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1840                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1841                    if (nai == null) {
1842                        loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1843                        break;
1844                    }
1845                    try {
1846                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1847                    } catch (Exception e) {
1848                        // Never crash!
1849                        loge("Exception in addVpnUidRanges: " + e);
1850                    }
1851                    break;
1852                }
1853                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1854                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1855                    if (nai == null) {
1856                        loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1857                        break;
1858                    }
1859                    try {
1860                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1861                    } catch (Exception e) {
1862                        // Never crash!
1863                        loge("Exception in removeVpnUidRanges: " + e);
1864                    }
1865                    break;
1866                }
1867                case NetworkAgent.EVENT_BLOCK_ADDRESS_FAMILY: {
1868                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1869                    if (nai == null) {
1870                        loge("EVENT_BLOCK_ADDRESS_FAMILY from unknown NetworkAgent");
1871                        break;
1872                    }
1873                    try {
1874                        mNetd.blockAddressFamily((Integer) msg.obj, nai.network.netId,
1875                                nai.linkProperties.getInterfaceName());
1876                    } catch (Exception e) {
1877                        // Never crash!
1878                        loge("Exception in blockAddressFamily: " + e);
1879                    }
1880                    break;
1881                }
1882                case NetworkAgent.EVENT_UNBLOCK_ADDRESS_FAMILY: {
1883                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1884                    if (nai == null) {
1885                        loge("EVENT_UNBLOCK_ADDRESS_FAMILY from unknown NetworkAgent");
1886                        break;
1887                    }
1888                    try {
1889                        mNetd.unblockAddressFamily((Integer) msg.obj, nai.network.netId,
1890                                nai.linkProperties.getInterfaceName());
1891                    } catch (Exception e) {
1892                        // Never crash!
1893                        loge("Exception in blockAddressFamily: " + e);
1894                    }
1895                    break;
1896                }
1897                case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
1898                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1899                    if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
1900                        handleConnectionValidated(nai);
1901                    }
1902                    break;
1903                }
1904                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
1905                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1906                    if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1907                        handleLingerComplete(nai);
1908                    }
1909                    break;
1910                }
1911                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
1912                    if (msg.arg1 == 0) {
1913                        setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1914                    } else {
1915                        NetworkAgentInfo nai = null;
1916                        synchronized (mNetworkForNetId) {
1917                            nai = mNetworkForNetId.get(msg.arg2);
1918                        }
1919                        if (nai == null) {
1920                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1921                            break;
1922                        }
1923                        setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1924                                nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
1925                    }
1926                    break;
1927                }
1928                case NetworkStateTracker.EVENT_STATE_CHANGED: {
1929                    info = (NetworkInfo) msg.obj;
1930                    NetworkInfo.State state = info.getState();
1931
1932                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
1933                            (state == NetworkInfo.State.DISCONNECTED) ||
1934                            (state == NetworkInfo.State.SUSPENDED)) {
1935                        log("ConnectivityChange for " +
1936                            info.getTypeName() + ": " +
1937                            state + "/" + info.getDetailedState());
1938                    }
1939
1940                    // Since mobile has the notion of a network/apn that can be used for
1941                    // provisioning we need to check every time we're connected as
1942                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
1943                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
1944                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
1945                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
1946                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
1947                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
1948                                        Settings.Global.DEVICE_PROVISIONED, 0))
1949                            && (((state == NetworkInfo.State.CONNECTED)
1950                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
1951                                || info.isConnectedToProvisioningNetwork())) {
1952                        log("ConnectivityChange checkMobileProvisioning for"
1953                                + " TYPE_MOBILE or ProvisioningNetwork");
1954                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
1955                    }
1956
1957                    EventLogTags.writeConnectivityStateChanged(
1958                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
1959
1960                    if (info.isConnectedToProvisioningNetwork()) {
1961                        /**
1962                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
1963                         * for now its an in between network, its a network that
1964                         * is actually a default network but we don't want it to be
1965                         * announced as such to keep background applications from
1966                         * trying to use it. It turns out that some still try so we
1967                         * take the additional step of clearing any default routes
1968                         * to the link that may have incorrectly setup by the lower
1969                         * levels.
1970                         */
1971                        LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
1972                        if (DBG) {
1973                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
1974                        }
1975
1976                        // Clear any default routes setup by the radio so
1977                        // any activity by applications trying to use this
1978                        // connection will fail until the provisioning network
1979                        // is enabled.
1980                        /*
1981                        for (RouteInfo r : lp.getRoutes()) {
1982                            removeRoute(lp, r, TO_DEFAULT_TABLE,
1983                                        mNetTrackers[info.getType()].getNetwork().netId);
1984                        }
1985                        */
1986                    } else if (state == NetworkInfo.State.DISCONNECTED) {
1987                    } else if (state == NetworkInfo.State.SUSPENDED) {
1988                    } else if (state == NetworkInfo.State.CONNECTED) {
1989                    //    handleConnect(info);
1990                    }
1991                    if (mLockdownTracker != null) {
1992                        mLockdownTracker.onNetworkInfoChanged(info);
1993                    }
1994                    break;
1995                }
1996                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
1997                    info = (NetworkInfo) msg.obj;
1998                    // TODO: Temporary allowing network configuration
1999                    //       change not resetting sockets.
2000                    //       @see bug/4455071
2001                    /*
2002                    handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
2003                            false);
2004                    */
2005                    break;
2006                }
2007            }
2008        }
2009    }
2010
2011    private void handleAsyncChannelHalfConnect(Message msg) {
2012        AsyncChannel ac = (AsyncChannel) msg.obj;
2013        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
2014            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2015                if (VDBG) log("NetworkFactory connected");
2016                // A network factory has connected.  Send it all current NetworkRequests.
2017                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2018                    if (nri.isRequest == false) continue;
2019                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2020                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2021                            (nai != null ? nai.currentScore : 0), 0, nri.request);
2022                }
2023            } else {
2024                loge("Error connecting NetworkFactory");
2025                mNetworkFactoryInfos.remove(msg.obj);
2026            }
2027        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2028            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2029                if (VDBG) log("NetworkAgent connected");
2030                // A network agent has requested a connection.  Establish the connection.
2031                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2032                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2033            } else {
2034                loge("Error connecting NetworkAgent");
2035                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2036                if (nai != null) {
2037                    synchronized (mNetworkForNetId) {
2038                        mNetworkForNetId.remove(nai.network.netId);
2039                    }
2040                    // Just in case.
2041                    mLegacyTypeTracker.remove(nai);
2042                }
2043            }
2044        }
2045    }
2046    private void handleAsyncChannelDisconnected(Message msg) {
2047        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2048        if (nai != null) {
2049            if (DBG) {
2050                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2051            }
2052            // A network agent has disconnected.
2053            if (nai.created) {
2054                // Tell netd to clean up the configuration for this network
2055                // (routing rules, DNS, etc).
2056                try {
2057                    mNetd.removeNetwork(nai.network.netId);
2058                } catch (Exception e) {
2059                    loge("Exception removing network: " + e);
2060                }
2061            }
2062            // TODO - if we move the logic to the network agent (have them disconnect
2063            // because they lost all their requests or because their score isn't good)
2064            // then they would disconnect organically, report their new state and then
2065            // disconnect the channel.
2066            if (nai.networkInfo.isConnected()) {
2067                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2068                        null, null);
2069            }
2070            if (isDefaultNetwork(nai)) {
2071                mDefaultInetConditionPublished = 0;
2072            }
2073            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2074            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2075            mNetworkAgentInfos.remove(msg.replyTo);
2076            updateClat(null, nai.linkProperties, nai);
2077            mLegacyTypeTracker.remove(nai);
2078            synchronized (mNetworkForNetId) {
2079                mNetworkForNetId.remove(nai.network.netId);
2080            }
2081            // Since we've lost the network, go through all the requests that
2082            // it was satisfying and see if any other factory can satisfy them.
2083            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
2084            for (int i = 0; i < nai.networkRequests.size(); i++) {
2085                NetworkRequest request = nai.networkRequests.valueAt(i);
2086                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2087                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2088                    if (DBG) {
2089                        log("Checking for replacement network to handle request " + request );
2090                    }
2091                    mNetworkForRequestId.remove(request.requestId);
2092                    sendUpdatedScoreToFactories(request, 0);
2093                    NetworkAgentInfo alternative = null;
2094                    for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
2095                        NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
2096                        if (existing.networkInfo.isConnected() &&
2097                                request.networkCapabilities.satisfiedByNetworkCapabilities(
2098                                existing.networkCapabilities) &&
2099                                (alternative == null ||
2100                                 alternative.currentScore < existing.currentScore)) {
2101                            alternative = existing;
2102                        }
2103                    }
2104                    if (alternative != null) {
2105                        if (DBG) log(" found replacement in " + alternative.name());
2106                        if (!toActivate.contains(alternative)) {
2107                            toActivate.add(alternative);
2108                        }
2109                    }
2110                }
2111            }
2112            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2113                removeDataActivityTracking(nai);
2114                mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
2115                requestNetworkTransitionWakelock(nai.name());
2116            }
2117            for (NetworkAgentInfo networkToActivate : toActivate) {
2118                networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2119            }
2120        }
2121    }
2122
2123    private void handleRegisterNetworkRequest(Message msg) {
2124        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2125        final NetworkCapabilities newCap = nri.request.networkCapabilities;
2126        int score = 0;
2127
2128        // Check for the best currently alive network that satisfies this request
2129        NetworkAgentInfo bestNetwork = null;
2130        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2131            if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
2132            if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
2133                if (DBG) log("apparently satisfied.  currentScore=" + network.currentScore);
2134                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
2135                    if (!nri.isRequest) {
2136                        // Not setting bestNetwork here as a listening NetworkRequest may be
2137                        // satisfied by multiple Networks.  Instead the request is added to
2138                        // each satisfying Network and notified about each.
2139                        network.addRequest(nri.request);
2140                        notifyNetworkCallback(network, nri);
2141                    } else {
2142                        bestNetwork = network;
2143                    }
2144                }
2145            }
2146        }
2147        if (bestNetwork != null) {
2148            if (DBG) log("using " + bestNetwork.name());
2149            if (bestNetwork.networkInfo.isConnected()) {
2150                // Cancel any lingering so the linger timeout doesn't teardown this network
2151                // even though we have a request for it.
2152                bestNetwork.networkLingered.clear();
2153                bestNetwork.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2154            }
2155            bestNetwork.addRequest(nri.request);
2156            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
2157            notifyNetworkCallback(bestNetwork, nri);
2158            score = bestNetwork.currentScore;
2159            if (nri.request.legacyType != TYPE_NONE) {
2160                mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2161            }
2162        }
2163        mNetworkRequests.put(nri.request, nri);
2164        if (nri.isRequest) {
2165            if (DBG) log("sending new NetworkRequest to factories");
2166            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2167                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
2168                        0, nri.request);
2169            }
2170        }
2171    }
2172
2173    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2174        NetworkRequestInfo nri = mNetworkRequests.get(request);
2175        if (nri != null) {
2176            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2177                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2178                return;
2179            }
2180            if (DBG) log("releasing NetworkRequest " + request);
2181            nri.unlinkDeathRecipient();
2182            mNetworkRequests.remove(request);
2183            if (nri.isRequest) {
2184                // Find all networks that are satisfying this request and remove the request
2185                // from their request lists.
2186                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2187                    if (nai.networkRequests.get(nri.request.requestId) != null) {
2188                        nai.networkRequests.remove(nri.request.requestId);
2189                        if (DBG) {
2190                            log(" Removing from current network " + nai.name() +
2191                                    ", leaving " + nai.networkRequests.size() +
2192                                    " requests.");
2193                        }
2194                        // check if has any requests remaining and if not,
2195                        // disconnect (unless it's a VPN).
2196                        boolean keep = nai.isVPN();
2197                        for (int i = 0; i < nai.networkRequests.size() && !keep; i++) {
2198                            NetworkRequest r = nai.networkRequests.valueAt(i);
2199                            if (mNetworkRequests.get(r).isRequest) keep = true;
2200                        }
2201                        if (!keep) {
2202                            if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2203                            nai.asyncChannel.disconnect();
2204                        }
2205                    }
2206                }
2207
2208                // Maintain the illusion.  When this request arrived, we might have preteneded
2209                // that a network connected to serve it, even though the network was already
2210                // connected.  Now that this request has gone away, we might have to pretend
2211                // that the network disconnected.  LegacyTypeTracker will generate that
2212                // phatom disconnect for this type.
2213                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2214                if (nai != null) {
2215                    mNetworkForRequestId.remove(nri.request.requestId);
2216                    if (nri.request.legacyType != TYPE_NONE) {
2217                        mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2218                    }
2219                }
2220
2221                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2222                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2223                            nri.request);
2224                }
2225            } else {
2226                // listens don't have a singular affectedNetwork.  Check all networks to see
2227                // if this listen request applies and remove it.
2228                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2229                    nai.networkRequests.remove(nri.request.requestId);
2230                }
2231            }
2232            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2233        }
2234    }
2235
2236    private class InternalHandler extends Handler {
2237        public InternalHandler(Looper looper) {
2238            super(looper);
2239        }
2240
2241        @Override
2242        public void handleMessage(Message msg) {
2243            NetworkInfo info;
2244            switch (msg.what) {
2245                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2246                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2247                    String causedBy = null;
2248                    synchronized (ConnectivityService.this) {
2249                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2250                                mNetTransitionWakeLock.isHeld()) {
2251                            mNetTransitionWakeLock.release();
2252                            causedBy = mNetTransitionWakeLockCausedBy;
2253                        } else {
2254                            break;
2255                        }
2256                    }
2257                    if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2258                        log("Failed to find a new network - expiring NetTransition Wakelock");
2259                    } else {
2260                        log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2261                                " cleared because we found a replacement network");
2262                    }
2263                    break;
2264                }
2265                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2266                    handleDeprecatedGlobalHttpProxy();
2267                    break;
2268                }
2269                case EVENT_SET_DEPENDENCY_MET: {
2270                    boolean met = (msg.arg1 == ENABLED);
2271                    handleSetDependencyMet(msg.arg2, met);
2272                    break;
2273                }
2274                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
2275                    Intent intent = (Intent)msg.obj;
2276                    sendStickyBroadcast(intent);
2277                    break;
2278                }
2279                case EVENT_SET_POLICY_DATA_ENABLE: {
2280                    final int networkType = msg.arg1;
2281                    final boolean enabled = msg.arg2 == ENABLED;
2282                    handleSetPolicyDataEnable(networkType, enabled);
2283                    break;
2284                }
2285                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2286                    int tag = mEnableFailFastMobileDataTag.get();
2287                    if (msg.arg1 == tag) {
2288                        MobileDataStateTracker mobileDst =
2289                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2290                        if (mobileDst != null) {
2291                            mobileDst.setEnableFailFastMobileData(msg.arg2);
2292                        }
2293                    } else {
2294                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2295                                + " != tag:" + tag);
2296                    }
2297                    break;
2298                }
2299                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
2300                    handleNetworkSamplingTimeout();
2301                    break;
2302                }
2303                case EVENT_PROXY_HAS_CHANGED: {
2304                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2305                    break;
2306                }
2307                case EVENT_REGISTER_NETWORK_FACTORY: {
2308                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2309                    break;
2310                }
2311                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2312                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2313                    break;
2314                }
2315                case EVENT_REGISTER_NETWORK_AGENT: {
2316                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2317                    break;
2318                }
2319                case EVENT_REGISTER_NETWORK_REQUEST:
2320                case EVENT_REGISTER_NETWORK_LISTENER: {
2321                    handleRegisterNetworkRequest(msg);
2322                    break;
2323                }
2324                case EVENT_RELEASE_NETWORK_REQUEST: {
2325                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2326                    break;
2327                }
2328                case EVENT_SYSTEM_READY: {
2329                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2330                        nai.networkMonitor.systemReady = true;
2331                    }
2332                    break;
2333                }
2334            }
2335        }
2336    }
2337
2338    // javadoc from interface
2339    public int tether(String iface) {
2340        enforceTetherChangePermission();
2341
2342        if (isTetheringSupported()) {
2343            return mTethering.tether(iface);
2344        } else {
2345            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2346        }
2347    }
2348
2349    // javadoc from interface
2350    public int untether(String iface) {
2351        enforceTetherChangePermission();
2352
2353        if (isTetheringSupported()) {
2354            return mTethering.untether(iface);
2355        } else {
2356            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2357        }
2358    }
2359
2360    // javadoc from interface
2361    public int getLastTetherError(String iface) {
2362        enforceTetherAccessPermission();
2363
2364        if (isTetheringSupported()) {
2365            return mTethering.getLastTetherError(iface);
2366        } else {
2367            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2368        }
2369    }
2370
2371    // TODO - proper iface API for selection by property, inspection, etc
2372    public String[] getTetherableUsbRegexs() {
2373        enforceTetherAccessPermission();
2374        if (isTetheringSupported()) {
2375            return mTethering.getTetherableUsbRegexs();
2376        } else {
2377            return new String[0];
2378        }
2379    }
2380
2381    public String[] getTetherableWifiRegexs() {
2382        enforceTetherAccessPermission();
2383        if (isTetheringSupported()) {
2384            return mTethering.getTetherableWifiRegexs();
2385        } else {
2386            return new String[0];
2387        }
2388    }
2389
2390    public String[] getTetherableBluetoothRegexs() {
2391        enforceTetherAccessPermission();
2392        if (isTetheringSupported()) {
2393            return mTethering.getTetherableBluetoothRegexs();
2394        } else {
2395            return new String[0];
2396        }
2397    }
2398
2399    public int setUsbTethering(boolean enable) {
2400        enforceTetherChangePermission();
2401        if (isTetheringSupported()) {
2402            return mTethering.setUsbTethering(enable);
2403        } else {
2404            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2405        }
2406    }
2407
2408    // TODO - move iface listing, queries, etc to new module
2409    // javadoc from interface
2410    public String[] getTetherableIfaces() {
2411        enforceTetherAccessPermission();
2412        return mTethering.getTetherableIfaces();
2413    }
2414
2415    public String[] getTetheredIfaces() {
2416        enforceTetherAccessPermission();
2417        return mTethering.getTetheredIfaces();
2418    }
2419
2420    public String[] getTetheringErroredIfaces() {
2421        enforceTetherAccessPermission();
2422        return mTethering.getErroredIfaces();
2423    }
2424
2425    public String[] getTetheredDhcpRanges() {
2426        enforceConnectivityInternalPermission();
2427        return mTethering.getTetheredDhcpRanges();
2428    }
2429
2430    // if ro.tether.denied = true we default to no tethering
2431    // gservices could set the secure setting to 1 though to enable it on a build where it
2432    // had previously been turned off.
2433    public boolean isTetheringSupported() {
2434        enforceTetherAccessPermission();
2435        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2436        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2437                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2438                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2439        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2440                mTethering.getTetherableWifiRegexs().length != 0 ||
2441                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2442                mTethering.getUpstreamIfaceTypes().length != 0);
2443    }
2444
2445    // Called when we lose the default network and have no replacement yet.
2446    // This will automatically be cleared after X seconds or a new default network
2447    // becomes CONNECTED, whichever happens first.  The timer is started by the
2448    // first caller and not restarted by subsequent callers.
2449    private void requestNetworkTransitionWakelock(String forWhom) {
2450        int serialNum = 0;
2451        synchronized (this) {
2452            if (mNetTransitionWakeLock.isHeld()) return;
2453            serialNum = ++mNetTransitionWakeLockSerialNumber;
2454            mNetTransitionWakeLock.acquire();
2455            mNetTransitionWakeLockCausedBy = forWhom;
2456        }
2457        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2458                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2459                mNetTransitionWakeLockTimeout);
2460        return;
2461    }
2462
2463    // 100 percent is full good, 0 is full bad.
2464    public void reportInetCondition(int networkType, int percentage) {
2465        if (percentage > 50) return;  // don't handle good network reports
2466        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2467        if (nai != null) reportBadNetwork(nai.network);
2468    }
2469
2470    public void reportBadNetwork(Network network) {
2471        //TODO
2472    }
2473
2474    public ProxyInfo getProxy() {
2475        // this information is already available as a world read/writable jvm property
2476        // so this API change wouldn't have a benifit.  It also breaks the passing
2477        // of proxy info to all the JVMs.
2478        // enforceAccessPermission();
2479        synchronized (mProxyLock) {
2480            ProxyInfo ret = mGlobalProxy;
2481            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2482            return ret;
2483        }
2484    }
2485
2486    public void setGlobalProxy(ProxyInfo proxyProperties) {
2487        enforceConnectivityInternalPermission();
2488
2489        synchronized (mProxyLock) {
2490            if (proxyProperties == mGlobalProxy) return;
2491            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2492            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2493
2494            String host = "";
2495            int port = 0;
2496            String exclList = "";
2497            String pacFileUrl = "";
2498            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2499                    (proxyProperties.getPacFileUrl() != null))) {
2500                if (!proxyProperties.isValid()) {
2501                    if (DBG)
2502                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2503                    return;
2504                }
2505                mGlobalProxy = new ProxyInfo(proxyProperties);
2506                host = mGlobalProxy.getHost();
2507                port = mGlobalProxy.getPort();
2508                exclList = mGlobalProxy.getExclusionListAsString();
2509                if (proxyProperties.getPacFileUrl() != null) {
2510                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2511                }
2512            } else {
2513                mGlobalProxy = null;
2514            }
2515            ContentResolver res = mContext.getContentResolver();
2516            final long token = Binder.clearCallingIdentity();
2517            try {
2518                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2519                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2520                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2521                        exclList);
2522                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2523            } finally {
2524                Binder.restoreCallingIdentity(token);
2525            }
2526        }
2527
2528        if (mGlobalProxy == null) {
2529            proxyProperties = mDefaultProxy;
2530        }
2531        sendProxyBroadcast(proxyProperties);
2532    }
2533
2534    private void loadGlobalProxy() {
2535        ContentResolver res = mContext.getContentResolver();
2536        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2537        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2538        String exclList = Settings.Global.getString(res,
2539                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2540        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2541        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2542            ProxyInfo proxyProperties;
2543            if (!TextUtils.isEmpty(pacFileUrl)) {
2544                proxyProperties = new ProxyInfo(pacFileUrl);
2545            } else {
2546                proxyProperties = new ProxyInfo(host, port, exclList);
2547            }
2548            if (!proxyProperties.isValid()) {
2549                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2550                return;
2551            }
2552
2553            synchronized (mProxyLock) {
2554                mGlobalProxy = proxyProperties;
2555            }
2556        }
2557    }
2558
2559    public ProxyInfo getGlobalProxy() {
2560        // this information is already available as a world read/writable jvm property
2561        // so this API change wouldn't have a benifit.  It also breaks the passing
2562        // of proxy info to all the JVMs.
2563        // enforceAccessPermission();
2564        synchronized (mProxyLock) {
2565            return mGlobalProxy;
2566        }
2567    }
2568
2569    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2570        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2571                && (proxy.getPacFileUrl() == null)) {
2572            proxy = null;
2573        }
2574        synchronized (mProxyLock) {
2575            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2576            if (mDefaultProxy == proxy) return; // catches repeated nulls
2577            if (proxy != null &&  !proxy.isValid()) {
2578                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2579                return;
2580            }
2581
2582            // This call could be coming from the PacManager, containing the port of the local
2583            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2584            // global (to get the correct local port), and send a broadcast.
2585            // TODO: Switch PacManager to have its own message to send back rather than
2586            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2587            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
2588                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2589                mGlobalProxy = proxy;
2590                sendProxyBroadcast(mGlobalProxy);
2591                return;
2592            }
2593            mDefaultProxy = proxy;
2594
2595            if (mGlobalProxy != null) return;
2596            if (!mDefaultProxyDisabled) {
2597                sendProxyBroadcast(proxy);
2598            }
2599        }
2600    }
2601
2602    private void handleDeprecatedGlobalHttpProxy() {
2603        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2604                Settings.Global.HTTP_PROXY);
2605        if (!TextUtils.isEmpty(proxy)) {
2606            String data[] = proxy.split(":");
2607            if (data.length == 0) {
2608                return;
2609            }
2610
2611            String proxyHost =  data[0];
2612            int proxyPort = 8080;
2613            if (data.length > 1) {
2614                try {
2615                    proxyPort = Integer.parseInt(data[1]);
2616                } catch (NumberFormatException e) {
2617                    return;
2618                }
2619            }
2620            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2621            setGlobalProxy(p);
2622        }
2623    }
2624
2625    private void sendProxyBroadcast(ProxyInfo proxy) {
2626        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2627        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2628        if (DBG) log("sending Proxy Broadcast for " + proxy);
2629        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2630        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2631            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2632        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2633        final long ident = Binder.clearCallingIdentity();
2634        try {
2635            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2636        } finally {
2637            Binder.restoreCallingIdentity(ident);
2638        }
2639    }
2640
2641    private static class SettingsObserver extends ContentObserver {
2642        private int mWhat;
2643        private Handler mHandler;
2644        SettingsObserver(Handler handler, int what) {
2645            super(handler);
2646            mHandler = handler;
2647            mWhat = what;
2648        }
2649
2650        void observe(Context context) {
2651            ContentResolver resolver = context.getContentResolver();
2652            resolver.registerContentObserver(Settings.Global.getUriFor(
2653                    Settings.Global.HTTP_PROXY), false, this);
2654        }
2655
2656        @Override
2657        public void onChange(boolean selfChange) {
2658            mHandler.obtainMessage(mWhat).sendToTarget();
2659        }
2660    }
2661
2662    private static void log(String s) {
2663        Slog.d(TAG, s);
2664    }
2665
2666    private static void loge(String s) {
2667        Slog.e(TAG, s);
2668    }
2669
2670    int convertFeatureToNetworkType(int networkType, String feature) {
2671        int usedNetworkType = networkType;
2672
2673        if(networkType == ConnectivityManager.TYPE_MOBILE) {
2674            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2675                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2676            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2677                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2678            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2679                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2680                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2681            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2682                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2683            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2684                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2685            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2686                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2687            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2688                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2689            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) {
2690                usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY;
2691            } else {
2692                Slog.e(TAG, "Can't match any mobile netTracker!");
2693            }
2694        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2695            if (TextUtils.equals(feature, "p2p")) {
2696                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2697            } else {
2698                Slog.e(TAG, "Can't match any wifi netTracker!");
2699            }
2700        } else {
2701            Slog.e(TAG, "Unexpected network type");
2702        }
2703        return usedNetworkType;
2704    }
2705
2706    private static <T> T checkNotNull(T value, String message) {
2707        if (value == null) {
2708            throw new NullPointerException(message);
2709        }
2710        return value;
2711    }
2712
2713    /**
2714     * Prepare for a VPN application. This method is used by VpnDialogs
2715     * and not available in ConnectivityManager. Permissions are checked
2716     * in Vpn class.
2717     * @hide
2718     */
2719    @Override
2720    public boolean prepareVpn(String oldPackage, String newPackage) {
2721        throwIfLockdownEnabled();
2722        int user = UserHandle.getUserId(Binder.getCallingUid());
2723        synchronized(mVpns) {
2724            return mVpns.get(user).prepare(oldPackage, newPackage);
2725        }
2726    }
2727
2728    /**
2729     * Set whether the current VPN package has the ability to launch VPNs without
2730     * user intervention. This method is used by system UIs and not available
2731     * in ConnectivityManager. Permissions are checked in Vpn class.
2732     * @hide
2733     */
2734    @Override
2735    public void setVpnPackageAuthorization(boolean authorized) {
2736        int user = UserHandle.getUserId(Binder.getCallingUid());
2737        synchronized(mVpns) {
2738            mVpns.get(user).setPackageAuthorization(authorized);
2739        }
2740    }
2741
2742    /**
2743     * Configure a TUN interface and return its file descriptor. Parameters
2744     * are encoded and opaque to this class. This method is used by VpnBuilder
2745     * and not available in ConnectivityManager. Permissions are checked in
2746     * Vpn class.
2747     * @hide
2748     */
2749    @Override
2750    public ParcelFileDescriptor establishVpn(VpnConfig config) {
2751        throwIfLockdownEnabled();
2752        int user = UserHandle.getUserId(Binder.getCallingUid());
2753        synchronized(mVpns) {
2754            return mVpns.get(user).establish(config);
2755        }
2756    }
2757
2758    /**
2759     * Start legacy VPN, controlling native daemons as needed. Creates a
2760     * secondary thread to perform connection work, returning quickly.
2761     */
2762    @Override
2763    public void startLegacyVpn(VpnProfile profile) {
2764        throwIfLockdownEnabled();
2765        final LinkProperties egress = getActiveLinkProperties();
2766        if (egress == null) {
2767            throw new IllegalStateException("Missing active network connection");
2768        }
2769        int user = UserHandle.getUserId(Binder.getCallingUid());
2770        synchronized(mVpns) {
2771            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2772        }
2773    }
2774
2775    /**
2776     * Return the information of the ongoing legacy VPN. This method is used
2777     * by VpnSettings and not available in ConnectivityManager. Permissions
2778     * are checked in Vpn class.
2779     * @hide
2780     */
2781    @Override
2782    public LegacyVpnInfo getLegacyVpnInfo() {
2783        throwIfLockdownEnabled();
2784        int user = UserHandle.getUserId(Binder.getCallingUid());
2785        synchronized(mVpns) {
2786            return mVpns.get(user).getLegacyVpnInfo();
2787        }
2788    }
2789
2790    /**
2791     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2792     * not available in ConnectivityManager.
2793     * Permissions are checked in Vpn class.
2794     * @hide
2795     */
2796    @Override
2797    public VpnConfig getVpnConfig() {
2798        int user = UserHandle.getUserId(Binder.getCallingUid());
2799        synchronized(mVpns) {
2800            return mVpns.get(user).getVpnConfig();
2801        }
2802    }
2803
2804    @Override
2805    public boolean updateLockdownVpn() {
2806        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2807            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
2808            return false;
2809        }
2810
2811        // Tear down existing lockdown if profile was removed
2812        mLockdownEnabled = LockdownVpnTracker.isEnabled();
2813        if (mLockdownEnabled) {
2814            if (!mKeyStore.isUnlocked()) {
2815                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
2816                return false;
2817            }
2818
2819            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
2820            final VpnProfile profile = VpnProfile.decode(
2821                    profileName, mKeyStore.get(Credentials.VPN + profileName));
2822            int user = UserHandle.getUserId(Binder.getCallingUid());
2823            synchronized(mVpns) {
2824                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
2825                            profile));
2826            }
2827        } else {
2828            setLockdownTracker(null);
2829        }
2830
2831        return true;
2832    }
2833
2834    /**
2835     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
2836     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
2837     */
2838    private void setLockdownTracker(LockdownVpnTracker tracker) {
2839        // Shutdown any existing tracker
2840        final LockdownVpnTracker existing = mLockdownTracker;
2841        mLockdownTracker = null;
2842        if (existing != null) {
2843            existing.shutdown();
2844        }
2845
2846        try {
2847            if (tracker != null) {
2848                mNetd.setFirewallEnabled(true);
2849                mNetd.setFirewallInterfaceRule("lo", true);
2850                mLockdownTracker = tracker;
2851                mLockdownTracker.init();
2852            } else {
2853                mNetd.setFirewallEnabled(false);
2854            }
2855        } catch (RemoteException e) {
2856            // ignored; NMS lives inside system_server
2857        }
2858    }
2859
2860    private void throwIfLockdownEnabled() {
2861        if (mLockdownEnabled) {
2862            throw new IllegalStateException("Unavailable in lockdown mode");
2863        }
2864    }
2865
2866    public void supplyMessenger(int networkType, Messenger messenger) {
2867        enforceConnectivityInternalPermission();
2868
2869        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
2870            mNetTrackers[networkType].supplyMessenger(messenger);
2871        }
2872    }
2873
2874    public int findConnectionTypeForIface(String iface) {
2875        enforceConnectivityInternalPermission();
2876
2877        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
2878
2879        synchronized(mNetworkForNetId) {
2880            for (int i = 0; i < mNetworkForNetId.size(); i++) {
2881                NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
2882                LinkProperties lp = nai.linkProperties;
2883                if (lp != null && iface.equals(lp.getInterfaceName()) && nai.networkInfo != null) {
2884                    return nai.networkInfo.getType();
2885                }
2886            }
2887        }
2888        return ConnectivityManager.TYPE_NONE;
2889    }
2890
2891    /**
2892     * Have mobile data fail fast if enabled.
2893     *
2894     * @param enabled DctConstants.ENABLED/DISABLED
2895     */
2896    private void setEnableFailFastMobileData(int enabled) {
2897        int tag;
2898
2899        if (enabled == DctConstants.ENABLED) {
2900            tag = mEnableFailFastMobileDataTag.incrementAndGet();
2901        } else {
2902            tag = mEnableFailFastMobileDataTag.get();
2903        }
2904        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
2905                         enabled));
2906    }
2907
2908    private boolean isMobileDataStateTrackerReady() {
2909        MobileDataStateTracker mdst =
2910                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
2911        return (mdst != null) && (mdst.isReady());
2912    }
2913
2914    /**
2915     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
2916     */
2917
2918    /**
2919     * No connection was possible to the network.
2920     * This is NOT a warm sim.
2921     */
2922    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
2923
2924    /**
2925     * A connection was made to the internet, all is well.
2926     * This is NOT a warm sim.
2927     */
2928    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
2929
2930    /**
2931     * A connection was made but no dns server was available to resolve a name to address.
2932     * This is NOT a warm sim since provisioning network is supported.
2933     */
2934    private static final int CMP_RESULT_CODE_NO_DNS = 2;
2935
2936    /**
2937     * A connection was made but could not open a TCP connection.
2938     * This is NOT a warm sim since provisioning network is supported.
2939     */
2940    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
2941
2942    /**
2943     * A connection was made but there was a redirection, we appear to be in walled garden.
2944     * This is an indication of a warm sim on a mobile network such as T-Mobile.
2945     */
2946    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
2947
2948    /**
2949     * The mobile network is a provisioning network.
2950     * This is an indication of a warm sim on a mobile network such as AT&T.
2951     */
2952    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
2953
2954    /**
2955     * The mobile network is provisioning
2956     */
2957    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
2958
2959    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
2960    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
2961
2962    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
2963
2964    @Override
2965    public int checkMobileProvisioning(int suggestedTimeOutMs) {
2966        int timeOutMs = -1;
2967        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
2968        enforceConnectivityInternalPermission();
2969
2970        final long token = Binder.clearCallingIdentity();
2971        try {
2972            timeOutMs = suggestedTimeOutMs;
2973            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
2974                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
2975            }
2976
2977            // Check that mobile networks are supported
2978            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
2979                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
2980                if (DBG) log("checkMobileProvisioning: X no mobile network");
2981                return timeOutMs;
2982            }
2983
2984            // If we're already checking don't do it again
2985            // TODO: Add a queue of results...
2986            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
2987                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
2988                return timeOutMs;
2989            }
2990
2991            // Start off with mobile notification off
2992            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
2993
2994            CheckMp checkMp = new CheckMp(mContext, this);
2995            CheckMp.CallBack cb = new CheckMp.CallBack() {
2996                @Override
2997                void onComplete(Integer result) {
2998                    if (DBG) log("CheckMp.onComplete: result=" + result);
2999                    NetworkInfo ni =
3000                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3001                    switch(result) {
3002                        case CMP_RESULT_CODE_CONNECTABLE:
3003                        case CMP_RESULT_CODE_NO_CONNECTION:
3004                        case CMP_RESULT_CODE_NO_DNS:
3005                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3006                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
3007                            break;
3008                        }
3009                        case CMP_RESULT_CODE_REDIRECTED: {
3010                            if (DBG) log("CheckMp.onComplete: warm sim");
3011                            String url = getMobileProvisioningUrl();
3012                            if (TextUtils.isEmpty(url)) {
3013                                url = getMobileRedirectedProvisioningUrl();
3014                            }
3015                            if (TextUtils.isEmpty(url) == false) {
3016                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
3017                                setProvNotificationVisible(true,
3018                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
3019                                        url);
3020                            } else {
3021                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
3022                            }
3023                            break;
3024                        }
3025                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
3026                            String url = getMobileProvisioningUrl();
3027                            if (TextUtils.isEmpty(url) == false) {
3028                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
3029                                setProvNotificationVisible(true,
3030                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
3031                                        url);
3032                                // Mark that we've got a provisioning network and
3033                                // Disable Mobile Data until user actually starts provisioning.
3034                                mIsProvisioningNetwork.set(true);
3035                                MobileDataStateTracker mdst = (MobileDataStateTracker)
3036                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3037
3038                                // Disable radio until user starts provisioning
3039                                mdst.setRadio(false);
3040                            } else {
3041                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
3042                            }
3043                            break;
3044                        }
3045                        case CMP_RESULT_CODE_IS_PROVISIONING: {
3046                            // FIXME: Need to know when provisioning is done. Probably we can
3047                            // check the completion status if successful we're done if we
3048                            // "timedout" or still connected to provisioning APN turn off data?
3049                            if (DBG) log("CheckMp.onComplete: provisioning started");
3050                            mIsStartingProvisioning.set(false);
3051                            break;
3052                        }
3053                        default: {
3054                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
3055                            break;
3056                        }
3057                    }
3058                    mIsCheckingMobileProvisioning.set(false);
3059                }
3060            };
3061            CheckMp.Params params =
3062                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3063            if (DBG) log("checkMobileProvisioning: params=" + params);
3064            // TODO: Reenable when calls to the now defunct
3065            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
3066            //       This code should be moved to the Telephony code.
3067            // checkMp.execute(params);
3068        } finally {
3069            Binder.restoreCallingIdentity(token);
3070            if (DBG) log("checkMobileProvisioning: X");
3071        }
3072        return timeOutMs;
3073    }
3074
3075    static class CheckMp extends
3076            AsyncTask<CheckMp.Params, Void, Integer> {
3077        private static final String CHECKMP_TAG = "CheckMp";
3078
3079        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
3080        private static boolean mTestingFailures;
3081
3082        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
3083        private static final int MAX_LOOPS = 4;
3084
3085        // Number of milli-seconds to complete all of the retires
3086        public static final int MAX_TIMEOUT_MS =  60000;
3087
3088        // The socket should retry only 5 seconds, the default is longer
3089        private static final int SOCKET_TIMEOUT_MS = 5000;
3090
3091        // Sleep time for network errors
3092        private static final int NET_ERROR_SLEEP_SEC = 3;
3093
3094        // Sleep time for network route establishment
3095        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
3096
3097        // Short sleep time for polling :(
3098        private static final int POLLING_SLEEP_SEC = 1;
3099
3100        private Context mContext;
3101        private ConnectivityService mCs;
3102        private TelephonyManager mTm;
3103        private Params mParams;
3104
3105        /**
3106         * Parameters for AsyncTask.execute
3107         */
3108        static class Params {
3109            private String mUrl;
3110            private long mTimeOutMs;
3111            private CallBack mCb;
3112
3113            Params(String url, long timeOutMs, CallBack cb) {
3114                mUrl = url;
3115                mTimeOutMs = timeOutMs;
3116                mCb = cb;
3117            }
3118
3119            @Override
3120            public String toString() {
3121                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3122            }
3123        }
3124
3125        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
3126        // issued by name or ip address, for Google its by name so when we construct
3127        // this HostnameVerifier we'll pass the original Uri and use it to verify
3128        // the host. If the host name in the original uril fails we'll test the
3129        // hostname parameter just incase things change.
3130        static class CheckMpHostnameVerifier implements HostnameVerifier {
3131            Uri mOrgUri;
3132
3133            CheckMpHostnameVerifier(Uri orgUri) {
3134                mOrgUri = orgUri;
3135            }
3136
3137            @Override
3138            public boolean verify(String hostname, SSLSession session) {
3139                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
3140                String orgUriHost = mOrgUri.getHost();
3141                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
3142                if (DBG) {
3143                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
3144                        + " orgUriHost=" + orgUriHost);
3145                }
3146                return retVal;
3147            }
3148        }
3149
3150        /**
3151         * The call back object passed in Params. onComplete will be called
3152         * on the main thread.
3153         */
3154        abstract static class CallBack {
3155            // Called on the main thread.
3156            abstract void onComplete(Integer result);
3157        }
3158
3159        public CheckMp(Context context, ConnectivityService cs) {
3160            if (Build.IS_DEBUGGABLE) {
3161                mTestingFailures =
3162                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
3163            } else {
3164                mTestingFailures = false;
3165            }
3166
3167            mContext = context;
3168            mCs = cs;
3169
3170            // Setup access to TelephonyService we'll be using.
3171            mTm = (TelephonyManager) mContext.getSystemService(
3172                    Context.TELEPHONY_SERVICE);
3173        }
3174
3175        /**
3176         * Get the default url to use for the test.
3177         */
3178        public String getDefaultUrl() {
3179            // See http://go/clientsdns for usage approval
3180            String server = Settings.Global.getString(mContext.getContentResolver(),
3181                    Settings.Global.CAPTIVE_PORTAL_SERVER);
3182            if (server == null) {
3183                server = "clients3.google.com";
3184            }
3185            return "http://" + server + "/generate_204";
3186        }
3187
3188        /**
3189         * Detect if its possible to connect to the http url. DNS based detection techniques
3190         * do not work at all hotspots. The best way to check is to perform a request to
3191         * a known address that fetches the data we expect.
3192         */
3193        private synchronized Integer isMobileOk(Params params) {
3194            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
3195            Uri orgUri = Uri.parse(params.mUrl);
3196            Random rand = new Random();
3197            mParams = params;
3198
3199            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3200                result = CMP_RESULT_CODE_NO_CONNECTION;
3201                log("isMobileOk: X not mobile capable result=" + result);
3202                return result;
3203            }
3204
3205            if (mCs.mIsStartingProvisioning.get()) {
3206                result = CMP_RESULT_CODE_IS_PROVISIONING;
3207                log("isMobileOk: X is provisioning result=" + result);
3208                return result;
3209            }
3210
3211            // See if we've already determined we've got a provisioning connection,
3212            // if so we don't need to do anything active.
3213            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
3214                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3215            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
3216            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
3217
3218            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
3219                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3220            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
3221            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
3222
3223            if (isDefaultProvisioning || isHipriProvisioning) {
3224                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
3225                log("isMobileOk: X default || hipri is provisioning result=" + result);
3226                return result;
3227            }
3228
3229            try {
3230                // Continue trying to connect until time has run out
3231                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3232
3233                if (!mCs.isMobileDataStateTrackerReady()) {
3234                    // Wait for MobileDataStateTracker to be ready.
3235                    if (DBG) log("isMobileOk: mdst is not ready");
3236                    while(SystemClock.elapsedRealtime() < endTime) {
3237                        if (mCs.isMobileDataStateTrackerReady()) {
3238                            // Enable fail fast as we'll do retries here and use a
3239                            // hipri connection so the default connection stays active.
3240                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
3241                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3242                            break;
3243                        }
3244                        sleep(POLLING_SLEEP_SEC);
3245                    }
3246                }
3247
3248                log("isMobileOk: start hipri url=" + params.mUrl);
3249
3250                // First wait until we can start using hipri
3251                Binder binder = new Binder();
3252/*
3253                while(SystemClock.elapsedRealtime() < endTime) {
3254                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3255                            Phone.FEATURE_ENABLE_HIPRI, binder);
3256                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3257                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3258                            log("isMobileOk: hipri started");
3259                            break;
3260                    }
3261                    if (VDBG) log("isMobileOk: hipri not started yet");
3262                    result = CMP_RESULT_CODE_NO_CONNECTION;
3263                    sleep(POLLING_SLEEP_SEC);
3264                }
3265*/
3266                // Continue trying to connect until time has run out
3267                while(SystemClock.elapsedRealtime() < endTime) {
3268                    try {
3269                        // Wait for hipri to connect.
3270                        // TODO: Don't poll and handle situation where hipri fails
3271                        // because default is retrying. See b/9569540
3272                        NetworkInfo.State state = mCs
3273                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3274                        if (state != NetworkInfo.State.CONNECTED) {
3275                            if (true/*VDBG*/) {
3276                                log("isMobileOk: not connected ni=" +
3277                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3278                            }
3279                            sleep(POLLING_SLEEP_SEC);
3280                            result = CMP_RESULT_CODE_NO_CONNECTION;
3281                            continue;
3282                        }
3283
3284                        // Hipri has started check if this is a provisioning url
3285                        MobileDataStateTracker mdst = (MobileDataStateTracker)
3286                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3287                        if (mdst.isProvisioningNetwork()) {
3288                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
3289                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
3290                            return result;
3291                        } else {
3292                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
3293                        }
3294
3295                        // Get of the addresses associated with the url host. We need to use the
3296                        // address otherwise HttpURLConnection object will use the name to get
3297                        // the addresses and will try every address but that will bypass the
3298                        // route to host we setup and the connection could succeed as the default
3299                        // interface might be connected to the internet via wifi or other interface.
3300                        InetAddress[] addresses;
3301                        try {
3302                            addresses = InetAddress.getAllByName(orgUri.getHost());
3303                        } catch (UnknownHostException e) {
3304                            result = CMP_RESULT_CODE_NO_DNS;
3305                            log("isMobileOk: X UnknownHostException result=" + result);
3306                            return result;
3307                        }
3308                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3309
3310                        // Get the type of addresses supported by this link
3311                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
3312                                ConnectivityManager.TYPE_MOBILE_HIPRI);
3313                        boolean linkHasIpv4 = lp.hasIPv4Address();
3314                        boolean linkHasIpv6 = lp.hasGlobalIPv6Address();
3315                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3316                                + " linkHasIpv6=" + linkHasIpv6);
3317
3318                        final ArrayList<InetAddress> validAddresses =
3319                                new ArrayList<InetAddress>(addresses.length);
3320
3321                        for (InetAddress addr : addresses) {
3322                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
3323                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
3324                                validAddresses.add(addr);
3325                            }
3326                        }
3327
3328                        if (validAddresses.size() == 0) {
3329                            return CMP_RESULT_CODE_NO_CONNECTION;
3330                        }
3331
3332                        int addrTried = 0;
3333                        while (true) {
3334                            // Loop through at most MAX_LOOPS valid addresses or until
3335                            // we run out of time
3336                            if (addrTried++ >= MAX_LOOPS) {
3337                                log("isMobileOk: too many loops tried - giving up");
3338                                break;
3339                            }
3340                            if (SystemClock.elapsedRealtime() >= endTime) {
3341                                log("isMobileOk: spend too much time - giving up");
3342                                break;
3343                            }
3344
3345                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
3346                                    validAddresses.size()));
3347
3348                            // Make a route to host so we check the specific interface.
3349                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3350                                    hostAddr.getAddress())) {
3351                                // Wait a short time to be sure the route is established ??
3352                                log("isMobileOk:"
3353                                        + " wait to establish route to hostAddr=" + hostAddr);
3354                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
3355                            } else {
3356                                log("isMobileOk:"
3357                                        + " could not establish route to hostAddr=" + hostAddr);
3358                                // Wait a short time before the next attempt
3359                                sleep(NET_ERROR_SLEEP_SEC);
3360                                continue;
3361                            }
3362
3363                            // Rewrite the url to have numeric address to use the specific route
3364                            // using http for half the attempts and https for the other half.
3365                            // Doing https first and http second as on a redirected walled garden
3366                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
3367                            // handshake timed out" which we declare as
3368                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
3369                            // having http second we will be using logic used for some time.
3370                            URL newUrl;
3371                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
3372                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
3373                                        orgUri.getPath());
3374                            log("isMobileOk: newUrl=" + newUrl);
3375
3376                            HttpURLConnection urlConn = null;
3377                            try {
3378                                // Open the connection set the request headers and get the response
3379                                urlConn = (HttpURLConnection)newUrl.openConnection(
3380                                        java.net.Proxy.NO_PROXY);
3381                                if (scheme.equals("https")) {
3382                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
3383                                            new CheckMpHostnameVerifier(orgUri));
3384                                }
3385                                urlConn.setInstanceFollowRedirects(false);
3386                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3387                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3388                                urlConn.setUseCaches(false);
3389                                urlConn.setAllowUserInteraction(false);
3390                                // Set the "Connection" to "Close" as by default "Keep-Alive"
3391                                // is used which is useless in this case.
3392                                urlConn.setRequestProperty("Connection", "close");
3393                                int responseCode = urlConn.getResponseCode();
3394
3395                                // For debug display the headers
3396                                Map<String, List<String>> headers = urlConn.getHeaderFields();
3397                                log("isMobileOk: headers=" + headers);
3398
3399                                // Close the connection
3400                                urlConn.disconnect();
3401                                urlConn = null;
3402
3403                                if (mTestingFailures) {
3404                                    // Pretend no connection, this tests using http and https
3405                                    result = CMP_RESULT_CODE_NO_CONNECTION;
3406                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
3407                                    continue;
3408                                }
3409
3410                                if (responseCode == 204) {
3411                                    // Return
3412                                    result = CMP_RESULT_CODE_CONNECTABLE;
3413                                    log("isMobileOk: X got expected responseCode=" + responseCode
3414                                            + " result=" + result);
3415                                    return result;
3416                                } else {
3417                                    // Retry to be sure this was redirected, we've gotten
3418                                    // occasions where a server returned 200 even though
3419                                    // the device didn't have a "warm" sim.
3420                                    log("isMobileOk: not expected responseCode=" + responseCode);
3421                                    // TODO - it would be nice in the single-address case to do
3422                                    // another DNS resolve here, but flushing the cache is a bit
3423                                    // heavy-handed.
3424                                    result = CMP_RESULT_CODE_REDIRECTED;
3425                                }
3426                            } catch (Exception e) {
3427                                log("isMobileOk: HttpURLConnection Exception" + e);
3428                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
3429                                if (urlConn != null) {
3430                                    urlConn.disconnect();
3431                                    urlConn = null;
3432                                }
3433                                sleep(NET_ERROR_SLEEP_SEC);
3434                                continue;
3435                            }
3436                        }
3437                        log("isMobileOk: X loops|timed out result=" + result);
3438                        return result;
3439                    } catch (Exception e) {
3440                        log("isMobileOk: Exception e=" + e);
3441                        continue;
3442                    }
3443                }
3444                log("isMobileOk: timed out");
3445            } finally {
3446                log("isMobileOk: F stop hipri");
3447                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3448//                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3449//                        Phone.FEATURE_ENABLE_HIPRI);
3450
3451                // Wait for hipri to disconnect.
3452                long endTime = SystemClock.elapsedRealtime() + 5000;
3453
3454                while(SystemClock.elapsedRealtime() < endTime) {
3455                    NetworkInfo.State state = mCs
3456                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3457                    if (state != NetworkInfo.State.DISCONNECTED) {
3458                        if (VDBG) {
3459                            log("isMobileOk: connected ni=" +
3460                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3461                        }
3462                        sleep(POLLING_SLEEP_SEC);
3463                        continue;
3464                    }
3465                }
3466
3467                log("isMobileOk: X result=" + result);
3468            }
3469            return result;
3470        }
3471
3472        @Override
3473        protected Integer doInBackground(Params... params) {
3474            return isMobileOk(params[0]);
3475        }
3476
3477        @Override
3478        protected void onPostExecute(Integer result) {
3479            log("onPostExecute: result=" + result);
3480            if ((mParams != null) && (mParams.mCb != null)) {
3481                mParams.mCb.onComplete(result);
3482            }
3483        }
3484
3485        private String inetAddressesToString(InetAddress[] addresses) {
3486            StringBuffer sb = new StringBuffer();
3487            boolean firstTime = true;
3488            for(InetAddress addr : addresses) {
3489                if (firstTime) {
3490                    firstTime = false;
3491                } else {
3492                    sb.append(",");
3493                }
3494                sb.append(addr);
3495            }
3496            return sb.toString();
3497        }
3498
3499        private void printNetworkInfo() {
3500            boolean hasIccCard = mTm.hasIccCard();
3501            int simState = mTm.getSimState();
3502            log("hasIccCard=" + hasIccCard
3503                    + " simState=" + simState);
3504            NetworkInfo[] ni = mCs.getAllNetworkInfo();
3505            if (ni != null) {
3506                log("ni.length=" + ni.length);
3507                for (NetworkInfo netInfo: ni) {
3508                    log("netInfo=" + netInfo.toString());
3509                }
3510            } else {
3511                log("no network info ni=null");
3512            }
3513        }
3514
3515        /**
3516         * Sleep for a few seconds then return.
3517         * @param seconds
3518         */
3519        private static void sleep(int seconds) {
3520            long stopTime = System.nanoTime() + (seconds * 1000000000);
3521            long sleepTime;
3522            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
3523                try {
3524                    Thread.sleep(sleepTime / 1000000);
3525                } catch (InterruptedException ignored) {
3526                }
3527            }
3528        }
3529
3530        private static void log(String s) {
3531            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3532        }
3533    }
3534
3535    // TODO: Move to ConnectivityManager and make public?
3536    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
3537            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
3538
3539    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
3540        @Override
3541        public void onReceive(Context context, Intent intent) {
3542            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
3543                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
3544            }
3545        }
3546    };
3547
3548    private void handleMobileProvisioningAction(String url) {
3549        // Mark notification as not visible
3550        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
3551
3552        // Check airplane mode
3553        boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(),
3554                Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
3555        // If provisioning network and not in airplane mode handle as a special case,
3556        // otherwise launch browser with the intent directly.
3557        if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) {
3558            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
3559            mIsProvisioningNetwork.set(false);
3560//            mIsStartingProvisioning.set(true);
3561//            MobileDataStateTracker mdst = (MobileDataStateTracker)
3562//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3563            // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here
3564//            mdst.setRadio(true);
3565//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
3566//            mdst.enableMobileProvisioning(url);
3567        } else {
3568            if (DBG) log("handleMobileProvisioningAction: not prov network");
3569            mIsProvisioningNetwork.set(false);
3570            // Check for  apps that can handle provisioning first
3571            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
3572            List<String> carrierPackages =
3573                    mTelephonyManager.getCarrierPackageNamesForIntent(provisioningIntent);
3574            if (carrierPackages != null && !carrierPackages.isEmpty()) {
3575                if (carrierPackages.size() != 1) {
3576                    if (DBG) log("Multiple matching carrier apps found, launching the first.");
3577                }
3578                provisioningIntent.setPackage(carrierPackages.get(0));
3579                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3580                        Intent.FLAG_ACTIVITY_NEW_TASK);
3581                mContext.startActivity(provisioningIntent);
3582            } else {
3583                // If no apps exist, use standard URL ACTION_VIEW method
3584                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
3585                        Intent.CATEGORY_APP_BROWSER);
3586                newIntent.setData(Uri.parse(url));
3587                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3588                        Intent.FLAG_ACTIVITY_NEW_TASK);
3589                try {
3590                    mContext.startActivity(newIntent);
3591                } catch (ActivityNotFoundException e) {
3592                    loge("handleMobileProvisioningAction: startActivity failed" + e);
3593                }
3594            }
3595        }
3596    }
3597
3598    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3599    private volatile boolean mIsNotificationVisible = false;
3600
3601    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
3602            String url) {
3603        if (DBG) {
3604            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3605                + " extraInfo=" + extraInfo + " url=" + url);
3606        }
3607        Intent intent = null;
3608        PendingIntent pendingIntent = null;
3609        if (visible) {
3610            switch (networkType) {
3611                case ConnectivityManager.TYPE_WIFI:
3612                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3613                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3614                            Intent.FLAG_ACTIVITY_NEW_TASK);
3615                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3616                    break;
3617                case ConnectivityManager.TYPE_MOBILE:
3618                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3619                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
3620                    intent.putExtra("EXTRA_URL", url);
3621                    intent.setFlags(0);
3622                    pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3623                    break;
3624                default:
3625                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3626                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3627                            Intent.FLAG_ACTIVITY_NEW_TASK);
3628                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3629                    break;
3630            }
3631        }
3632        // Concatenate the range of types onto the range of NetIDs.
3633        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3634        setProvNotificationVisibleIntent(visible, id, networkType, extraInfo, pendingIntent);
3635    }
3636
3637    /**
3638     * Show or hide network provisioning notificaitons.
3639     *
3640     * @param id an identifier that uniquely identifies this notification.  This must match
3641     *         between show and hide calls.  We use the NetID value but for legacy callers
3642     *         we concatenate the range of types with the range of NetIDs.
3643     */
3644    private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
3645            String extraInfo, PendingIntent intent) {
3646        if (DBG) {
3647            log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3648                networkType + " extraInfo=" + extraInfo);
3649        }
3650
3651        Resources r = Resources.getSystem();
3652        NotificationManager notificationManager = (NotificationManager) mContext
3653            .getSystemService(Context.NOTIFICATION_SERVICE);
3654
3655        if (visible) {
3656            CharSequence title;
3657            CharSequence details;
3658            int icon;
3659            Notification notification = new Notification();
3660            switch (networkType) {
3661                case ConnectivityManager.TYPE_WIFI:
3662                    title = r.getString(R.string.wifi_available_sign_in, 0);
3663                    details = r.getString(R.string.network_available_sign_in_detailed,
3664                            extraInfo);
3665                    icon = R.drawable.stat_notify_wifi_in_range;
3666                    break;
3667                case ConnectivityManager.TYPE_MOBILE:
3668                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3669                    title = r.getString(R.string.network_available_sign_in, 0);
3670                    // TODO: Change this to pull from NetworkInfo once a printable
3671                    // name has been added to it
3672                    details = mTelephonyManager.getNetworkOperatorName();
3673                    icon = R.drawable.stat_notify_rssi_in_range;
3674                    break;
3675                default:
3676                    title = r.getString(R.string.network_available_sign_in, 0);
3677                    details = r.getString(R.string.network_available_sign_in_detailed,
3678                            extraInfo);
3679                    icon = R.drawable.stat_notify_rssi_in_range;
3680                    break;
3681            }
3682
3683            notification.when = 0;
3684            notification.icon = icon;
3685            notification.flags = Notification.FLAG_AUTO_CANCEL;
3686            notification.tickerText = title;
3687            notification.color = mContext.getResources().getColor(
3688                    com.android.internal.R.color.system_notification_accent_color);
3689            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3690            notification.contentIntent = intent;
3691
3692            try {
3693                notificationManager.notify(NOTIFICATION_ID, id, notification);
3694            } catch (NullPointerException npe) {
3695                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3696                npe.printStackTrace();
3697            }
3698        } else {
3699            try {
3700                notificationManager.cancel(NOTIFICATION_ID, id);
3701            } catch (NullPointerException npe) {
3702                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3703                npe.printStackTrace();
3704            }
3705        }
3706        mIsNotificationVisible = visible;
3707    }
3708
3709    /** Location to an updatable file listing carrier provisioning urls.
3710     *  An example:
3711     *
3712     * <?xml version="1.0" encoding="utf-8"?>
3713     *  <provisioningUrls>
3714     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3715     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3716     *  </provisioningUrls>
3717     */
3718    private static final String PROVISIONING_URL_PATH =
3719            "/data/misc/radio/provisioning_urls.xml";
3720    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3721
3722    /** XML tag for root element. */
3723    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3724    /** XML tag for individual url */
3725    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3726    /** XML tag for redirected url */
3727    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3728    /** XML attribute for mcc */
3729    private static final String ATTR_MCC = "mcc";
3730    /** XML attribute for mnc */
3731    private static final String ATTR_MNC = "mnc";
3732
3733    private static final int REDIRECTED_PROVISIONING = 1;
3734    private static final int PROVISIONING = 2;
3735
3736    private String getProvisioningUrlBaseFromFile(int type) {
3737        FileReader fileReader = null;
3738        XmlPullParser parser = null;
3739        Configuration config = mContext.getResources().getConfiguration();
3740        String tagType;
3741
3742        switch (type) {
3743            case PROVISIONING:
3744                tagType = TAG_PROVISIONING_URL;
3745                break;
3746            case REDIRECTED_PROVISIONING:
3747                tagType = TAG_REDIRECTED_URL;
3748                break;
3749            default:
3750                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3751                        type);
3752        }
3753
3754        try {
3755            fileReader = new FileReader(mProvisioningUrlFile);
3756            parser = Xml.newPullParser();
3757            parser.setInput(fileReader);
3758            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3759
3760            while (true) {
3761                XmlUtils.nextElement(parser);
3762
3763                String element = parser.getName();
3764                if (element == null) break;
3765
3766                if (element.equals(tagType)) {
3767                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3768                    try {
3769                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3770                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3771                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3772                                parser.next();
3773                                if (parser.getEventType() == XmlPullParser.TEXT) {
3774                                    return parser.getText();
3775                                }
3776                            }
3777                        }
3778                    } catch (NumberFormatException e) {
3779                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3780                    }
3781                }
3782            }
3783            return null;
3784        } catch (FileNotFoundException e) {
3785            loge("Carrier Provisioning Urls file not found");
3786        } catch (XmlPullParserException e) {
3787            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3788        } catch (IOException e) {
3789            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3790        } finally {
3791            if (fileReader != null) {
3792                try {
3793                    fileReader.close();
3794                } catch (IOException e) {}
3795            }
3796        }
3797        return null;
3798    }
3799
3800    @Override
3801    public String getMobileRedirectedProvisioningUrl() {
3802        enforceConnectivityInternalPermission();
3803        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3804        if (TextUtils.isEmpty(url)) {
3805            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3806        }
3807        return url;
3808    }
3809
3810    @Override
3811    public String getMobileProvisioningUrl() {
3812        enforceConnectivityInternalPermission();
3813        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3814        if (TextUtils.isEmpty(url)) {
3815            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3816            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3817        } else {
3818            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3819        }
3820        // populate the iccid, imei and phone number in the provisioning url.
3821        if (!TextUtils.isEmpty(url)) {
3822            String phoneNumber = mTelephonyManager.getLine1Number();
3823            if (TextUtils.isEmpty(phoneNumber)) {
3824                phoneNumber = "0000000000";
3825            }
3826            url = String.format(url,
3827                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3828                    mTelephonyManager.getDeviceId() /* IMEI */,
3829                    phoneNumber /* Phone numer */);
3830        }
3831
3832        return url;
3833    }
3834
3835    @Override
3836    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3837            String extraInfo, String url) {
3838        enforceConnectivityInternalPermission();
3839        setProvNotificationVisible(visible, networkType, extraInfo, url);
3840    }
3841
3842    @Override
3843    public void setAirplaneMode(boolean enable) {
3844        enforceConnectivityInternalPermission();
3845        final long ident = Binder.clearCallingIdentity();
3846        try {
3847            final ContentResolver cr = mContext.getContentResolver();
3848            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3849            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3850            intent.putExtra("state", enable);
3851            mContext.sendBroadcast(intent);
3852        } finally {
3853            Binder.restoreCallingIdentity(ident);
3854        }
3855    }
3856
3857    private void onUserStart(int userId) {
3858        synchronized(mVpns) {
3859            Vpn userVpn = mVpns.get(userId);
3860            if (userVpn != null) {
3861                loge("Starting user already has a VPN");
3862                return;
3863            }
3864            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
3865            mVpns.put(userId, userVpn);
3866        }
3867    }
3868
3869    private void onUserStop(int userId) {
3870        synchronized(mVpns) {
3871            Vpn userVpn = mVpns.get(userId);
3872            if (userVpn == null) {
3873                loge("Stopping user has no VPN");
3874                return;
3875            }
3876            mVpns.delete(userId);
3877        }
3878    }
3879
3880    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3881        @Override
3882        public void onReceive(Context context, Intent intent) {
3883            final String action = intent.getAction();
3884            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3885            if (userId == UserHandle.USER_NULL) return;
3886
3887            if (Intent.ACTION_USER_STARTING.equals(action)) {
3888                onUserStart(userId);
3889            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3890                onUserStop(userId);
3891            }
3892        }
3893    };
3894
3895    @Override
3896    public LinkQualityInfo getLinkQualityInfo(int networkType) {
3897        enforceAccessPermission();
3898        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3899            return mNetTrackers[networkType].getLinkQualityInfo();
3900        } else {
3901            return null;
3902        }
3903    }
3904
3905    @Override
3906    public LinkQualityInfo getActiveLinkQualityInfo() {
3907        enforceAccessPermission();
3908        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
3909                mNetTrackers[mActiveDefaultNetwork] != null) {
3910            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
3911        } else {
3912            return null;
3913        }
3914    }
3915
3916    @Override
3917    public LinkQualityInfo[] getAllLinkQualityInfo() {
3918        enforceAccessPermission();
3919        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
3920        for (NetworkStateTracker tracker : mNetTrackers) {
3921            if (tracker != null) {
3922                LinkQualityInfo li = tracker.getLinkQualityInfo();
3923                if (li != null) {
3924                    result.add(li);
3925                }
3926            }
3927        }
3928
3929        return result.toArray(new LinkQualityInfo[result.size()]);
3930    }
3931
3932    /* Infrastructure for network sampling */
3933
3934    private void handleNetworkSamplingTimeout() {
3935
3936        if (SAMPLE_DBG) log("Sampling interval elapsed, updating statistics ..");
3937
3938        // initialize list of interfaces ..
3939        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
3940                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
3941        for (NetworkStateTracker tracker : mNetTrackers) {
3942            if (tracker != null) {
3943                String ifaceName = tracker.getNetworkInterfaceName();
3944                if (ifaceName != null) {
3945                    mapIfaceToSample.put(ifaceName, null);
3946                }
3947            }
3948        }
3949
3950        // Read samples for all interfaces
3951        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
3952
3953        // process samples for all networks
3954        for (NetworkStateTracker tracker : mNetTrackers) {
3955            if (tracker != null) {
3956                String ifaceName = tracker.getNetworkInterfaceName();
3957                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
3958                if (ss != null) {
3959                    // end the previous sampling cycle
3960                    tracker.stopSampling(ss);
3961                    // start a new sampling cycle ..
3962                    tracker.startSampling(ss);
3963                }
3964            }
3965        }
3966
3967        if (SAMPLE_DBG) log("Done.");
3968
3969        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
3970                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
3971                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
3972
3973        if (SAMPLE_DBG) {
3974            log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
3975        }
3976
3977        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
3978    }
3979
3980    /**
3981     * Sets a network sampling alarm.
3982     */
3983    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
3984        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
3985        int alarmType;
3986        if (Resources.getSystem().getBoolean(
3987                R.bool.config_networkSamplingWakesDevice)) {
3988            alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
3989        } else {
3990            alarmType = AlarmManager.ELAPSED_REALTIME;
3991        }
3992        mAlarmManager.set(alarmType, wakeupTime, intent);
3993    }
3994
3995    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3996            new HashMap<Messenger, NetworkFactoryInfo>();
3997    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3998            new HashMap<NetworkRequest, NetworkRequestInfo>();
3999
4000    private static class NetworkFactoryInfo {
4001        public final String name;
4002        public final Messenger messenger;
4003        public final AsyncChannel asyncChannel;
4004
4005        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4006            this.name = name;
4007            this.messenger = messenger;
4008            this.asyncChannel = asyncChannel;
4009        }
4010    }
4011
4012    /**
4013     * Tracks info about the requester.
4014     * Also used to notice when the calling process dies so we can self-expire
4015     */
4016    private class NetworkRequestInfo implements IBinder.DeathRecipient {
4017        static final boolean REQUEST = true;
4018        static final boolean LISTEN = false;
4019
4020        final NetworkRequest request;
4021        IBinder mBinder;
4022        final int mPid;
4023        final int mUid;
4024        final Messenger messenger;
4025        final boolean isRequest;
4026
4027        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
4028            super();
4029            messenger = m;
4030            request = r;
4031            mBinder = binder;
4032            mPid = getCallingPid();
4033            mUid = getCallingUid();
4034            this.isRequest = isRequest;
4035
4036            try {
4037                mBinder.linkToDeath(this, 0);
4038            } catch (RemoteException e) {
4039                binderDied();
4040            }
4041        }
4042
4043        void unlinkDeathRecipient() {
4044            mBinder.unlinkToDeath(this, 0);
4045        }
4046
4047        public void binderDied() {
4048            log("ConnectivityService NetworkRequestInfo binderDied(" +
4049                    request + ", " + mBinder + ")");
4050            releaseNetworkRequest(request);
4051        }
4052
4053        public String toString() {
4054            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
4055                    mPid + " for " + request;
4056        }
4057    }
4058
4059    @Override
4060    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
4061            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
4062        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
4063                == false) {
4064            enforceConnectivityInternalPermission();
4065        } else {
4066            enforceChangePermission();
4067        }
4068
4069        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4070
4071        // if UID is restricted, don't allow them to bring up metered APNs
4072        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
4073                == false) {
4074            final int uidRules;
4075            synchronized(mRulesLock) {
4076                uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
4077            }
4078            if ((uidRules & RULE_REJECT_METERED) != 0) {
4079                // we could silently fail or we can filter the available nets to only give
4080                // them those they have access to.  Chose the more useful
4081                networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
4082            }
4083        }
4084
4085        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
4086            throw new IllegalArgumentException("Bad timeout specified");
4087        }
4088        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4089                nextNetworkRequestId());
4090        if (DBG) log("requestNetwork for " + networkRequest);
4091        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4092                NetworkRequestInfo.REQUEST);
4093
4094        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
4095        if (timeoutMs > 0) {
4096            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
4097                    nri), timeoutMs);
4098        }
4099        return networkRequest;
4100    }
4101
4102    @Override
4103    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4104            PendingIntent operation) {
4105        // TODO
4106        return null;
4107    }
4108
4109    @Override
4110    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4111            Messenger messenger, IBinder binder) {
4112        enforceAccessPermission();
4113
4114        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
4115                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4116        if (DBG) log("listenForNetwork for " + networkRequest);
4117        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4118                NetworkRequestInfo.LISTEN);
4119
4120        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4121        return networkRequest;
4122    }
4123
4124    @Override
4125    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4126            PendingIntent operation) {
4127    }
4128
4129    @Override
4130    public void releaseNetworkRequest(NetworkRequest networkRequest) {
4131        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4132                0, networkRequest));
4133    }
4134
4135    @Override
4136    public void registerNetworkFactory(Messenger messenger, String name) {
4137        enforceConnectivityInternalPermission();
4138        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4139        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
4140    }
4141
4142    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
4143        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
4144        mNetworkFactoryInfos.put(nfi.messenger, nfi);
4145        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4146    }
4147
4148    @Override
4149    public void unregisterNetworkFactory(Messenger messenger) {
4150        enforceConnectivityInternalPermission();
4151        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4152    }
4153
4154    private void handleUnregisterNetworkFactory(Messenger messenger) {
4155        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4156        if (nfi == null) {
4157            loge("Failed to find Messenger in unregisterNetworkFactory");
4158            return;
4159        }
4160        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
4161    }
4162
4163    /**
4164     * NetworkAgentInfo supporting a request by requestId.
4165     * These have already been vetted (their Capabilities satisfy the request)
4166     * and the are the highest scored network available.
4167     * the are keyed off the Requests requestId.
4168     */
4169    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4170            new SparseArray<NetworkAgentInfo>();
4171
4172    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4173            new SparseArray<NetworkAgentInfo>();
4174
4175    // NetworkAgentInfo keyed off its connecting messenger
4176    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
4177    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4178            new HashMap<Messenger, NetworkAgentInfo>();
4179
4180    private final NetworkRequest mDefaultRequest;
4181
4182    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
4183        return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai;
4184    }
4185
4186    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
4187            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
4188            int currentScore, NetworkMisc networkMisc) {
4189        enforceConnectivityInternalPermission();
4190
4191        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
4192            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
4193            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
4194            networkMisc);
4195        synchronized (this) {
4196            nai.networkMonitor.systemReady = mSystemReady;
4197        }
4198        if (DBG) log("registerNetworkAgent " + nai);
4199        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
4200    }
4201
4202    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4203        if (VDBG) log("Got NetworkAgent Messenger");
4204        mNetworkAgentInfos.put(na.messenger, na);
4205        assignNextNetId(na);
4206        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4207        NetworkInfo networkInfo = na.networkInfo;
4208        na.networkInfo = null;
4209        updateNetworkInfo(na, networkInfo);
4210    }
4211
4212    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4213        LinkProperties newLp = networkAgent.linkProperties;
4214        int netId = networkAgent.network.netId;
4215
4216        updateInterfaces(newLp, oldLp, netId);
4217        updateMtu(newLp, oldLp);
4218        updateTcpBufferSizes(networkAgent);
4219        // TODO - figure out what to do for clat
4220//        for (LinkProperties lp : newLp.getStackedLinks()) {
4221//            updateMtu(lp, null);
4222//        }
4223        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
4224        updateDnses(newLp, oldLp, netId, flushDns);
4225        updateClat(newLp, oldLp, networkAgent);
4226        if (isDefaultNetwork(networkAgent)) handleApplyDefaultProxy(newLp.getHttpProxy());
4227    }
4228
4229    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
4230        // Update 464xlat state.
4231        if (mClat.requiresClat(na)) {
4232
4233            // If the connection was previously using clat, but is not using it now, stop the clat
4234            // daemon. Normally, this happens automatically when the connection disconnects, but if
4235            // the disconnect is not reported, or if the connection's LinkProperties changed for
4236            // some other reason (e.g., handoff changes the IP addresses on the link), it would
4237            // still be running. If it's not running, then stopping it is a no-op.
4238            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
4239                mClat.stopClat();
4240            }
4241            // If the link requires clat to be running, then start the daemon now.
4242            if (na.networkInfo.isConnected()) {
4243                mClat.startClat(na);
4244            } else {
4245                mClat.stopClat();
4246            }
4247        }
4248    }
4249
4250    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4251        CompareResult<String> interfaceDiff = new CompareResult<String>();
4252        if (oldLp != null) {
4253            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4254        } else if (newLp != null) {
4255            interfaceDiff.added = newLp.getAllInterfaceNames();
4256        }
4257        for (String iface : interfaceDiff.added) {
4258            try {
4259                if (DBG) log("Adding iface " + iface + " to network " + netId);
4260                mNetd.addInterfaceToNetwork(iface, netId);
4261            } catch (Exception e) {
4262                loge("Exception adding interface: " + e);
4263            }
4264        }
4265        for (String iface : interfaceDiff.removed) {
4266            try {
4267                if (DBG) log("Removing iface " + iface + " from network " + netId);
4268                mNetd.removeInterfaceFromNetwork(iface, netId);
4269            } catch (Exception e) {
4270                loge("Exception removing interface: " + e);
4271            }
4272        }
4273    }
4274
4275    /**
4276     * Have netd update routes from oldLp to newLp.
4277     * @return true if routes changed between oldLp and newLp
4278     */
4279    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4280        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4281        if (oldLp != null) {
4282            routeDiff = oldLp.compareAllRoutes(newLp);
4283        } else if (newLp != null) {
4284            routeDiff.added = newLp.getAllRoutes();
4285        }
4286
4287        // add routes before removing old in case it helps with continuous connectivity
4288
4289        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4290        for (RouteInfo route : routeDiff.added) {
4291            if (route.hasGateway()) continue;
4292            if (DBG) log("Adding Route [" + route + "] to network " + netId);
4293            try {
4294                mNetd.addRoute(netId, route);
4295            } catch (Exception e) {
4296                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4297                    loge("Exception in addRoute for non-gateway: " + e);
4298                }
4299            }
4300        }
4301        for (RouteInfo route : routeDiff.added) {
4302            if (route.hasGateway() == false) continue;
4303            if (DBG) log("Adding Route [" + route + "] to network " + netId);
4304            try {
4305                mNetd.addRoute(netId, route);
4306            } catch (Exception e) {
4307                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4308                    loge("Exception in addRoute for gateway: " + e);
4309                }
4310            }
4311        }
4312
4313        for (RouteInfo route : routeDiff.removed) {
4314            if (DBG) log("Removing Route [" + route + "] from network " + netId);
4315            try {
4316                mNetd.removeRoute(netId, route);
4317            } catch (Exception e) {
4318                loge("Exception in removeRoute: " + e);
4319            }
4320        }
4321        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4322    }
4323    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, boolean flush) {
4324        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
4325            Collection<InetAddress> dnses = newLp.getDnsServers();
4326            if (dnses.size() == 0 && mDefaultDns != null) {
4327                dnses = new ArrayList();
4328                dnses.add(mDefaultDns);
4329                if (DBG) {
4330                    loge("no dns provided for netId " + netId + ", so using defaults");
4331                }
4332            }
4333            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
4334            try {
4335                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4336                    newLp.getDomains());
4337            } catch (Exception e) {
4338                loge("Exception in setDnsServersForNetwork: " + e);
4339            }
4340            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4341            if (defaultNai != null && defaultNai.network.netId == netId) {
4342                setDefaultDnsSystemProperties(dnses);
4343            }
4344            flushVmDnsCache();
4345        } else if (flush) {
4346            try {
4347                mNetd.flushNetworkDnsCache(netId);
4348            } catch (Exception e) {
4349                loge("Exception in flushNetworkDnsCache: " + e);
4350            }
4351            flushVmDnsCache();
4352        }
4353    }
4354
4355    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4356        int last = 0;
4357        for (InetAddress dns : dnses) {
4358            ++last;
4359            String key = "net.dns" + last;
4360            String value = dns.getHostAddress();
4361            SystemProperties.set(key, value);
4362        }
4363        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4364            String key = "net.dns" + i;
4365            SystemProperties.set(key, "");
4366        }
4367        mNumDnsEntries = last;
4368    }
4369
4370
4371    private void updateCapabilities(NetworkAgentInfo networkAgent,
4372            NetworkCapabilities networkCapabilities) {
4373        // TODO - what else here?  Verify still satisfies everybody?
4374        // Check if satisfies somebody new?  call callbacks?
4375        synchronized (networkAgent) {
4376            networkAgent.networkCapabilities = networkCapabilities;
4377        }
4378    }
4379
4380    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4381        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4382        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4383            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4384                    networkRequest);
4385        }
4386    }
4387
4388    private void callCallbackForRequest(NetworkRequestInfo nri,
4389            NetworkAgentInfo networkAgent, int notificationType) {
4390        if (nri.messenger == null) return;  // Default request has no msgr
4391        Object o;
4392        int a1 = 0;
4393        int a2 = 0;
4394        switch (notificationType) {
4395            case ConnectivityManager.CALLBACK_LOSING:
4396                a1 = 30 * 1000; // TODO - read this from NetworkMonitor
4397                // fall through
4398            case ConnectivityManager.CALLBACK_PRECHECK:
4399            case ConnectivityManager.CALLBACK_AVAILABLE:
4400            case ConnectivityManager.CALLBACK_LOST:
4401            case ConnectivityManager.CALLBACK_CAP_CHANGED:
4402            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4403                o = new NetworkRequest(nri.request);
4404                a2 = networkAgent.network.netId;
4405                break;
4406            }
4407            case ConnectivityManager.CALLBACK_UNAVAIL:
4408            case ConnectivityManager.CALLBACK_RELEASED: {
4409                o = new NetworkRequest(nri.request);
4410                break;
4411            }
4412            default: {
4413                loge("Unknown notificationType " + notificationType);
4414                return;
4415            }
4416        }
4417        Message msg = Message.obtain();
4418        msg.arg1 = a1;
4419        msg.arg2 = a2;
4420        msg.obj = o;
4421        msg.what = notificationType;
4422        try {
4423            if (VDBG) {
4424                log("sending notification " + notifyTypeToName(notificationType) +
4425                        " for " + nri.request);
4426            }
4427            nri.messenger.send(msg);
4428        } catch (RemoteException e) {
4429            // may occur naturally in the race of binder death.
4430            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4431        }
4432    }
4433
4434    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4435        if (oldNetwork == null) {
4436            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4437            return;
4438        }
4439        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4440        if (DBG) {
4441            if (oldNetwork.networkRequests.size() != 0) {
4442                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
4443            }
4444        }
4445        oldNetwork.asyncChannel.disconnect();
4446    }
4447
4448    private void makeDefault(NetworkAgentInfo newNetwork) {
4449        if (DBG) log("Switching to new default network: " + newNetwork);
4450        mActiveDefaultNetwork = newNetwork.networkInfo.getType();
4451        setupDataActivityTracking(newNetwork);
4452        try {
4453            mNetd.setDefaultNetId(newNetwork.network.netId);
4454        } catch (Exception e) {
4455            loge("Exception setting default network :" + e);
4456        }
4457        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4458        updateTcpBufferSizes(newNetwork);
4459    }
4460
4461    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
4462        if (newNetwork == null) {
4463            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
4464            return;
4465        }
4466        boolean keep = newNetwork.isVPN();
4467        boolean isNewDefault = false;
4468        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
4469        // check if any NetworkRequest wants this NetworkAgent
4470        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4471        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
4472        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4473            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4474            if (newNetwork == currentNetwork) {
4475                if (DBG) log("Network " + newNetwork.name() + " was already satisfying" +
4476                              " request " + nri.request.requestId + ". No change.");
4477                keep = true;
4478                continue;
4479            }
4480
4481            // check if it satisfies the NetworkCapabilities
4482            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4483            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
4484                    newNetwork.networkCapabilities)) {
4485                if (!nri.isRequest) {
4486                    newNetwork.addRequest(nri.request);
4487                    continue;
4488                }
4489                // next check if it's better than any current network we're using for
4490                // this request
4491                if (VDBG) {
4492                    log("currentScore = " +
4493                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
4494                            ", newScore = " + newNetwork.currentScore);
4495                }
4496                if (currentNetwork == null ||
4497                        currentNetwork.currentScore < newNetwork.currentScore) {
4498                    if (currentNetwork != null) {
4499                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4500                        currentNetwork.networkRequests.remove(nri.request.requestId);
4501                        currentNetwork.networkLingered.add(nri.request);
4502                        affectedNetworks.add(currentNetwork);
4503                    } else {
4504                        if (DBG) log("   accepting network in place of null");
4505                    }
4506                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4507                    newNetwork.addRequest(nri.request);
4508                    if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
4509                        mLegacyTypeTracker.add(nri.request.legacyType, newNetwork);
4510                    }
4511                    keep = true;
4512                    // TODO - this could get expensive if we have alot of requests for this
4513                    // network.  Think about if there is a way to reduce this.  Push
4514                    // netid->request mapping to each factory?
4515                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
4516                    if (mDefaultRequest.requestId == nri.request.requestId) {
4517                        isNewDefault = true;
4518                        updateActiveDefaultNetwork(newNetwork);
4519                        if (newNetwork.linkProperties != null) {
4520                            updateTcpBufferSizes(newNetwork);
4521                            setDefaultDnsSystemProperties(
4522                                    newNetwork.linkProperties.getDnsServers());
4523                        } else {
4524                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
4525                        }
4526                        // Maintain the illusion: since the legacy API only
4527                        // understands one network at a time, we must pretend
4528                        // that the current default network disconnected before
4529                        // the new one connected.
4530                        if (currentNetwork != null) {
4531                            mLegacyTypeTracker.remove(currentNetwork.networkInfo.getType(),
4532                                                      currentNetwork);
4533                        }
4534                        mDefaultInetConditionPublished = 100;
4535                        mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4536                    }
4537                }
4538            }
4539        }
4540        for (NetworkAgentInfo nai : affectedNetworks) {
4541            boolean teardown = !nai.isVPN();
4542            for (int i = 0; i < nai.networkRequests.size() && teardown; i++) {
4543                NetworkRequest nr = nai.networkRequests.valueAt(i);
4544                try {
4545                if (mNetworkRequests.get(nr).isRequest) {
4546                    teardown = false;
4547                }
4548                } catch (Exception e) {
4549                    loge("Request " + nr + " not found in mNetworkRequests.");
4550                    loge("  it came from request list  of " + nai.name());
4551                }
4552            }
4553            if (teardown) {
4554                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4555                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4556            } else {
4557                // not going to linger, so kill the list of linger networks..  only
4558                // notify them of linger if it happens as the result of gaining another,
4559                // but if they transition and old network stays up, don't tell them of linger
4560                // or very delayed loss
4561                nai.networkLingered.clear();
4562                if (VDBG) log("Lingered for " + nai.name() + " cleared");
4563            }
4564        }
4565        if (keep) {
4566            if (isNewDefault) {
4567                makeDefault(newNetwork);
4568                synchronized (ConnectivityService.this) {
4569                    // have a new default network, release the transition wakelock in
4570                    // a second if it's held.  The second pause is to allow apps
4571                    // to reconnect over the new network
4572                    if (mNetTransitionWakeLock.isHeld()) {
4573                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4574                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4575                                mNetTransitionWakeLockSerialNumber, 0),
4576                                1000);
4577                    }
4578                }
4579            }
4580
4581            // Notify battery stats service about this network, both the normal
4582            // interface and any stacked links.
4583            try {
4584                final IBatteryStats bs = BatteryStatsService.getService();
4585                final int type = newNetwork.networkInfo.getType();
4586
4587                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4588                bs.noteNetworkInterfaceType(baseIface, type);
4589                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4590                    final String stackedIface = stacked.getInterfaceName();
4591                    bs.noteNetworkInterfaceType(stackedIface, type);
4592                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4593                }
4594            } catch (RemoteException ignored) {
4595            }
4596
4597            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4598        } else {
4599            if (DBG && newNetwork.networkRequests.size() != 0) {
4600                loge("tearing down network with live requests:");
4601                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
4602                    loge("  " + newNetwork.networkRequests.valueAt(i));
4603                }
4604            }
4605            if (DBG) log("Validated network turns out to be unwanted.  Tear it down.");
4606            newNetwork.asyncChannel.disconnect();
4607        }
4608    }
4609
4610
4611    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4612        NetworkInfo.State state = newInfo.getState();
4613        NetworkInfo oldInfo = null;
4614        synchronized (networkAgent) {
4615            oldInfo = networkAgent.networkInfo;
4616            networkAgent.networkInfo = newInfo;
4617        }
4618        if (networkAgent.isVPN() && mLockdownTracker != null) {
4619            mLockdownTracker.onVpnStateChanged(newInfo);
4620        }
4621
4622        if (oldInfo != null && oldInfo.getState() == state) {
4623            if (VDBG) log("ignoring duplicate network state non-change");
4624            return;
4625        }
4626        if (DBG) {
4627            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4628                    (oldInfo == null ? "null" : oldInfo.getState()) +
4629                    " to " + state);
4630        }
4631
4632        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4633            try {
4634                // This should never fail.  Specifying an already in use NetID will cause failure.
4635                if (networkAgent.isVPN()) {
4636                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4637                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4638                            (networkAgent.networkMisc == null ||
4639                                !networkAgent.networkMisc.allowBypass));
4640                } else {
4641                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4642                }
4643            } catch (Exception e) {
4644                loge("Error creating network " + networkAgent.network.netId + ": "
4645                        + e.getMessage());
4646                return;
4647            }
4648            networkAgent.created = true;
4649            updateLinkProperties(networkAgent, null);
4650            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4651            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4652            if (networkAgent.isVPN()) {
4653                // Temporarily disable the default proxy (not global).
4654                synchronized (mProxyLock) {
4655                    if (!mDefaultProxyDisabled) {
4656                        mDefaultProxyDisabled = true;
4657                        if (mGlobalProxy == null && mDefaultProxy != null) {
4658                            sendProxyBroadcast(null);
4659                        }
4660                    }
4661                }
4662                // TODO: support proxy per network.
4663            }
4664            // Make default network if we have no default.  Any network is better than no network.
4665            if (mNetworkForRequestId.get(mDefaultRequest.requestId) == null &&
4666                    networkAgent.isVPN() == false &&
4667                    mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
4668                    networkAgent.networkCapabilities)) {
4669                makeDefault(networkAgent);
4670            }
4671        } else if (state == NetworkInfo.State.DISCONNECTED ||
4672                state == NetworkInfo.State.SUSPENDED) {
4673            networkAgent.asyncChannel.disconnect();
4674            if (networkAgent.isVPN()) {
4675                synchronized (mProxyLock) {
4676                    if (mDefaultProxyDisabled) {
4677                        mDefaultProxyDisabled = false;
4678                        if (mGlobalProxy == null && mDefaultProxy != null) {
4679                            sendProxyBroadcast(mDefaultProxy);
4680                        }
4681                    }
4682                }
4683            }
4684        }
4685    }
4686
4687    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4688        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4689
4690        nai.currentScore = score;
4691
4692        // TODO - This will not do the right thing if this network is lowering
4693        // its score and has requests that can be served by other
4694        // currently-active networks, or if the network is increasing its
4695        // score and other networks have requests that can be better served
4696        // by this network.
4697        //
4698        // Really we want to see if any of our requests migrate to other
4699        // active/lingered networks and if any other requests migrate to us (depending
4700        // on increasing/decreasing currentScore.  That's a bit of work and probably our
4701        // score checking/network allocation code needs to be modularized so we can understand
4702        // (see handleConnectionValided for an example).
4703        //
4704        // As a first order approx, lets just advertise the new score to factories.  If
4705        // somebody can beat it they will nominate a network and our normal net replacement
4706        // code will fire.
4707        for (int i = 0; i < nai.networkRequests.size(); i++) {
4708            NetworkRequest nr = nai.networkRequests.valueAt(i);
4709            // Don't send listening requests to factories. b/17393458
4710            if (mNetworkRequests.get(nr).isRequest == false) continue;
4711            sendUpdatedScoreToFactories(nr, score);
4712        }
4713    }
4714
4715    // notify only this one new request of the current state
4716    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4717        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4718        // TODO - read state from monitor to decide what to send.
4719//        if (nai.networkMonitor.isLingering()) {
4720//            notifyType = NetworkCallbacks.LOSING;
4721//        } else if (nai.networkMonitor.isEvaluating()) {
4722//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4723//        }
4724        callCallbackForRequest(nri, nai, notifyType);
4725    }
4726
4727    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4728        // The NetworkInfo we actually send out has no bearing on the real
4729        // state of affairs. For example, if the default connection is mobile,
4730        // and a request for HIPRI has just gone away, we need to pretend that
4731        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4732        // the state to DISCONNECTED, even though the network is of type MOBILE
4733        // and is still connected.
4734        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4735        info.setType(type);
4736        if (connected) {
4737            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4738            sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
4739        } else {
4740            info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
4741            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4742            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4743            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4744            if (info.isFailover()) {
4745                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4746                nai.networkInfo.setFailover(false);
4747            }
4748            if (info.getReason() != null) {
4749                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4750            }
4751            if (info.getExtraInfo() != null) {
4752                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4753            }
4754            NetworkAgentInfo newDefaultAgent = null;
4755            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4756                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4757                if (newDefaultAgent != null) {
4758                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4759                            newDefaultAgent.networkInfo);
4760                } else {
4761                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4762                }
4763            }
4764            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4765                    mDefaultInetConditionPublished);
4766            final Intent immediateIntent = new Intent(intent);
4767            immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4768            sendStickyBroadcast(immediateIntent);
4769            sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
4770            if (newDefaultAgent != null) {
4771                sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
4772                getConnectivityChangeDelay());
4773            }
4774        }
4775    }
4776
4777    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4778        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4779        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4780            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4781            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4782            if (VDBG) log(" sending notification for " + nr);
4783            callCallbackForRequest(nri, networkAgent, notifyType);
4784        }
4785    }
4786
4787    private String notifyTypeToName(int notifyType) {
4788        switch (notifyType) {
4789            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4790            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4791            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4792            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4793            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4794            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4795            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4796            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4797        }
4798        return "UNKNOWN";
4799    }
4800
4801    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
4802        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4803        if (nai != null) {
4804            synchronized (nai) {
4805                return new LinkProperties(nai.linkProperties);
4806            }
4807        }
4808        return new LinkProperties();
4809    }
4810
4811    private NetworkInfo getNetworkInfoForType(int networkType) {
4812        if (!mLegacyTypeTracker.isTypeSupported(networkType))
4813            return null;
4814
4815        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4816        if (nai != null) {
4817            NetworkInfo result = new NetworkInfo(nai.networkInfo);
4818            result.setType(networkType);
4819            return result;
4820        } else {
4821            NetworkInfo result = new NetworkInfo(
4822                    networkType, 0, ConnectivityManager.getNetworkTypeName(networkType), "");
4823            result.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
4824            return result;
4825        }
4826    }
4827
4828    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
4829        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4830        if (nai != null) {
4831            synchronized (nai) {
4832                return new NetworkCapabilities(nai.networkCapabilities);
4833            }
4834        }
4835        return new NetworkCapabilities();
4836    }
4837
4838    @Override
4839    public boolean addVpnAddress(String address, int prefixLength) {
4840        throwIfLockdownEnabled();
4841        int user = UserHandle.getUserId(Binder.getCallingUid());
4842        synchronized (mVpns) {
4843            return mVpns.get(user).addAddress(address, prefixLength);
4844        }
4845    }
4846
4847    @Override
4848    public boolean removeVpnAddress(String address, int prefixLength) {
4849        throwIfLockdownEnabled();
4850        int user = UserHandle.getUserId(Binder.getCallingUid());
4851        synchronized (mVpns) {
4852            return mVpns.get(user).removeAddress(address, prefixLength);
4853        }
4854    }
4855}
4856