Home | History | Annotate | Download | only in server
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.server;
     18 
     19 import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
     20 import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
     21 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
     22 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
     23 import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
     24 import static android.net.ConnectivityManager.TYPE_DUMMY;
     25 import static android.net.ConnectivityManager.TYPE_MOBILE;
     26 import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
     27 import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
     28 import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
     29 import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
     30 import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
     31 import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
     32 import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
     33 import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
     34 import static android.net.ConnectivityManager.TYPE_NONE;
     35 import static android.net.ConnectivityManager.TYPE_WIFI;
     36 import static android.net.ConnectivityManager.TYPE_WIMAX;
     37 import static android.net.ConnectivityManager.TYPE_PROXY;
     38 import static android.net.ConnectivityManager.getNetworkTypeName;
     39 import static android.net.ConnectivityManager.isNetworkTypeValid;
     40 import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
     41 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
     42 
     43 import android.app.AlarmManager;
     44 import android.app.Notification;
     45 import android.app.NotificationManager;
     46 import android.app.PendingIntent;
     47 import android.content.ActivityNotFoundException;
     48 import android.content.BroadcastReceiver;
     49 import android.content.ContentResolver;
     50 import android.content.Context;
     51 import android.content.ContextWrapper;
     52 import android.content.Intent;
     53 import android.content.IntentFilter;
     54 import android.content.pm.PackageManager;
     55 import android.content.res.Configuration;
     56 import android.content.res.Resources;
     57 import android.database.ContentObserver;
     58 import android.net.ConnectivityManager;
     59 import android.net.IConnectivityManager;
     60 import android.net.INetworkManagementEventObserver;
     61 import android.net.INetworkPolicyListener;
     62 import android.net.INetworkPolicyManager;
     63 import android.net.INetworkStatsService;
     64 import android.net.LinkAddress;
     65 import android.net.LinkProperties;
     66 import android.net.LinkProperties.CompareResult;
     67 import android.net.LinkQualityInfo;
     68 import android.net.MobileDataStateTracker;
     69 import android.net.Network;
     70 import android.net.NetworkAgent;
     71 import android.net.NetworkCapabilities;
     72 import android.net.NetworkConfig;
     73 import android.net.NetworkInfo;
     74 import android.net.NetworkInfo.DetailedState;
     75 import android.net.NetworkFactory;
     76 import android.net.NetworkMisc;
     77 import android.net.NetworkQuotaInfo;
     78 import android.net.NetworkRequest;
     79 import android.net.NetworkState;
     80 import android.net.NetworkStateTracker;
     81 import android.net.NetworkUtils;
     82 import android.net.Proxy;
     83 import android.net.ProxyDataTracker;
     84 import android.net.ProxyInfo;
     85 import android.net.RouteInfo;
     86 import android.net.SamplingDataTracker;
     87 import android.net.UidRange;
     88 import android.net.Uri;
     89 import android.net.wimax.WimaxManagerConstants;
     90 import android.os.AsyncTask;
     91 import android.os.Binder;
     92 import android.os.Build;
     93 import android.os.Bundle;
     94 import android.os.FileUtils;
     95 import android.os.Handler;
     96 import android.os.HandlerThread;
     97 import android.os.IBinder;
     98 import android.os.INetworkManagementService;
     99 import android.os.Looper;
    100 import android.os.Message;
    101 import android.os.Messenger;
    102 import android.os.ParcelFileDescriptor;
    103 import android.os.PowerManager;
    104 import android.os.Process;
    105 import android.os.RemoteException;
    106 import android.os.ServiceManager;
    107 import android.os.SystemClock;
    108 import android.os.SystemProperties;
    109 import android.os.UserHandle;
    110 import android.os.UserManager;
    111 import android.provider.Settings;
    112 import android.security.Credentials;
    113 import android.security.KeyStore;
    114 import android.telephony.TelephonyManager;
    115 import android.text.TextUtils;
    116 import android.util.Slog;
    117 import android.util.SparseArray;
    118 import android.util.SparseIntArray;
    119 import android.util.Xml;
    120 
    121 import com.android.internal.R;
    122 import com.android.internal.annotations.GuardedBy;
    123 import com.android.internal.app.IBatteryStats;
    124 import com.android.internal.net.LegacyVpnInfo;
    125 import com.android.internal.net.NetworkStatsFactory;
    126 import com.android.internal.net.VpnConfig;
    127 import com.android.internal.net.VpnProfile;
    128 import com.android.internal.telephony.DctConstants;
    129 import com.android.internal.telephony.Phone;
    130 import com.android.internal.telephony.PhoneConstants;
    131 import com.android.internal.telephony.TelephonyIntents;
    132 import com.android.internal.util.AsyncChannel;
    133 import com.android.internal.util.IndentingPrintWriter;
    134 import com.android.internal.util.XmlUtils;
    135 import com.android.server.am.BatteryStatsService;
    136 import com.android.server.connectivity.DataConnectionStats;
    137 import com.android.server.connectivity.Nat464Xlat;
    138 import com.android.server.connectivity.NetworkAgentInfo;
    139 import com.android.server.connectivity.NetworkMonitor;
    140 import com.android.server.connectivity.PacManager;
    141 import com.android.server.connectivity.PermissionMonitor;
    142 import com.android.server.connectivity.Tethering;
    143 import com.android.server.connectivity.Vpn;
    144 import com.android.server.net.BaseNetworkObserver;
    145 import com.android.server.net.LockdownVpnTracker;
    146 import com.google.android.collect.Lists;
    147 import com.google.android.collect.Sets;
    148 
    149 import dalvik.system.DexClassLoader;
    150 
    151 import org.xmlpull.v1.XmlPullParser;
    152 import org.xmlpull.v1.XmlPullParserException;
    153 
    154 import java.io.File;
    155 import java.io.FileDescriptor;
    156 import java.io.FileNotFoundException;
    157 import java.io.FileReader;
    158 import java.io.IOException;
    159 import java.io.PrintWriter;
    160 import java.lang.reflect.Constructor;
    161 import java.net.HttpURLConnection;
    162 import java.net.Inet4Address;
    163 import java.net.Inet6Address;
    164 import java.net.InetAddress;
    165 import java.net.URL;
    166 import java.net.UnknownHostException;
    167 import java.util.ArrayList;
    168 import java.util.Arrays;
    169 import java.util.Collection;
    170 import java.util.GregorianCalendar;
    171 import java.util.HashMap;
    172 import java.util.HashSet;
    173 import java.util.List;
    174 import java.util.Map;
    175 import java.util.Objects;
    176 import java.util.Random;
    177 import java.util.concurrent.atomic.AtomicBoolean;
    178 import java.util.concurrent.atomic.AtomicInteger;
    179 
    180 import javax.net.ssl.HostnameVerifier;
    181 import javax.net.ssl.HttpsURLConnection;
    182 import javax.net.ssl.SSLSession;
    183 
    184 /**
    185  * @hide
    186  */
    187 public class ConnectivityService extends IConnectivityManager.Stub {
    188     private static final String TAG = "ConnectivityService";
    189 
    190     private static final boolean DBG = true;
    191     private static final boolean VDBG = false;
    192 
    193     // network sampling debugging
    194     private static final boolean SAMPLE_DBG = false;
    195 
    196     private static final boolean LOGD_RULES = false;
    197 
    198     // TODO: create better separation between radio types and network types
    199 
    200     // how long to wait before switching back to a radio's default network
    201     private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
    202     // system property that can override the above value
    203     private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
    204             "android.telephony.apn-restore";
    205 
    206     // Default value if FAIL_FAST_TIME_MS is not set
    207     private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
    208     // system property that can override DEFAULT_FAIL_FAST_TIME_MS
    209     private static final String FAIL_FAST_TIME_MS =
    210             "persist.radio.fail_fast_time_ms";
    211 
    212     private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
    213             "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
    214 
    215     private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
    216 
    217     private PendingIntent mSampleIntervalElapsedIntent;
    218 
    219     // Set network sampling interval at 12 minutes, this way, even if the timers get
    220     // aggregated, it will fire at around 15 minutes, which should allow us to
    221     // aggregate this timer with other timers (specially the socket keep alive timers)
    222     private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60);
    223 
    224     // start network sampling a minute after booting ...
    225     private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60);
    226 
    227     AlarmManager mAlarmManager;
    228 
    229     private Tethering mTethering;
    230 
    231     private final PermissionMonitor mPermissionMonitor;
    232 
    233     private KeyStore mKeyStore;
    234 
    235     @GuardedBy("mVpns")
    236     private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
    237 
    238     private boolean mLockdownEnabled;
    239     private LockdownVpnTracker mLockdownTracker;
    240 
    241     private Nat464Xlat mClat;
    242 
    243     /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
    244     private Object mRulesLock = new Object();
    245     /** Currently active network rules by UID. */
    246     private SparseIntArray mUidRules = new SparseIntArray();
    247     /** Set of ifaces that are costly. */
    248     private HashSet<String> mMeteredIfaces = Sets.newHashSet();
    249 
    250     /**
    251      * Sometimes we want to refer to the individual network state
    252      * trackers separately, and sometimes we just want to treat them
    253      * abstractly.
    254      */
    255     private NetworkStateTracker mNetTrackers[];
    256 
    257     private Context mContext;
    258     private int mNetworkPreference;
    259     private int mActiveDefaultNetwork = TYPE_NONE;
    260     // 0 is full bad, 100 is full good
    261     private int mDefaultInetConditionPublished = 0;
    262 
    263     private Object mDnsLock = new Object();
    264     private int mNumDnsEntries;
    265 
    266     private boolean mTestMode;
    267     private static ConnectivityService sServiceInstance;
    268 
    269     private INetworkManagementService mNetd;
    270     private INetworkPolicyManager mPolicyManager;
    271 
    272     private String mCurrentTcpBufferSizes;
    273 
    274     private static final int ENABLED  = 1;
    275     private static final int DISABLED = 0;
    276 
    277     /**
    278      * used internally to change our mobile data enabled flag
    279      */
    280     private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
    281 
    282     /**
    283      * used internally to clear a wakelock when transitioning
    284      * from one net to another.  Clear happens when we get a new
    285      * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
    286      * after a timeout if no network is found (typically 1 min).
    287      */
    288     private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
    289 
    290     /**
    291      * used internally to reload global proxy settings
    292      */
    293     private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
    294 
    295     /**
    296      * used internally to set external dependency met/unmet
    297      * arg1 = ENABLED (met) or DISABLED (unmet)
    298      * arg2 = NetworkType
    299      */
    300     private static final int EVENT_SET_DEPENDENCY_MET = 10;
    301 
    302     /**
    303      * used internally to send a sticky broadcast delayed.
    304      */
    305     private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
    306 
    307     /**
    308      * Used internally to
    309      * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
    310      */
    311     private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
    312 
    313     /**
    314      * Used internally to disable fail fast of mobile data
    315      */
    316     private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
    317 
    318     /**
    319      * used internally to indicate that data sampling interval is up
    320      */
    321     private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
    322 
    323     /**
    324      * PAC manager has received new port.
    325      */
    326     private static final int EVENT_PROXY_HAS_CHANGED = 16;
    327 
    328     /**
    329      * used internally when registering NetworkFactories
    330      * obj = NetworkFactoryInfo
    331      */
    332     private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
    333 
    334     /**
    335      * used internally when registering NetworkAgents
    336      * obj = Messenger
    337      */
    338     private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
    339 
    340     /**
    341      * used to add a network request
    342      * includes a NetworkRequestInfo
    343      */
    344     private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
    345 
    346     /**
    347      * indicates a timeout period is over - check if we had a network yet or not
    348      * and if not, call the timeout calback (but leave the request live until they
    349      * cancel it.
    350      * includes a NetworkRequestInfo
    351      */
    352     private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
    353 
    354     /**
    355      * used to add a network listener - no request
    356      * includes a NetworkRequestInfo
    357      */
    358     private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
    359 
    360     /**
    361      * used to remove a network request, either a listener or a real request
    362      * arg1 = UID of caller
    363      * obj  = NetworkRequest
    364      */
    365     private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
    366 
    367     /**
    368      * used internally when registering NetworkFactories
    369      * obj = Messenger
    370      */
    371     private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
    372 
    373     /**
    374      * used internally to expire a wakelock when transitioning
    375      * from one net to another.  Expire happens when we fail to find
    376      * a new network (typically after 1 minute) -
    377      * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
    378      * a replacement network.
    379      */
    380     private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
    381 
    382     /**
    383      * Used internally to indicate the system is ready.
    384      */
    385     private static final int EVENT_SYSTEM_READY = 25;
    386 
    387 
    388     /** Handler used for internal events. */
    389     final private InternalHandler mHandler;
    390     /** Handler used for incoming {@link NetworkStateTracker} events. */
    391     final private NetworkStateTrackerHandler mTrackerHandler;
    392 
    393     private boolean mSystemReady;
    394     private Intent mInitialBroadcast;
    395 
    396     private PowerManager.WakeLock mNetTransitionWakeLock;
    397     private String mNetTransitionWakeLockCausedBy = "";
    398     private int mNetTransitionWakeLockSerialNumber;
    399     private int mNetTransitionWakeLockTimeout;
    400 
    401     private InetAddress mDefaultDns;
    402 
    403     // used in DBG mode to track inet condition reports
    404     private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
    405     private ArrayList mInetLog;
    406 
    407     // track the current default http proxy - tell the world if we get a new one (real change)
    408     private volatile ProxyInfo mDefaultProxy = null;
    409     private Object mProxyLock = new Object();
    410     private boolean mDefaultProxyDisabled = false;
    411 
    412     // track the global proxy.
    413     private ProxyInfo mGlobalProxy = null;
    414 
    415     private PacManager mPacManager = null;
    416 
    417     private SettingsObserver mSettingsObserver;
    418 
    419     private UserManager mUserManager;
    420 
    421     NetworkConfig[] mNetConfigs;
    422     int mNetworksDefined;
    423 
    424     // the set of network types that can only be enabled by system/sig apps
    425     List mProtectedNetworks;
    426 
    427     private DataConnectionStats mDataConnectionStats;
    428 
    429     private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
    430 
    431     TelephonyManager mTelephonyManager;
    432 
    433     // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
    434     private final static int MIN_NET_ID = 100; // some reserved marks
    435     private final static int MAX_NET_ID = 65535;
    436     private int mNextNetId = MIN_NET_ID;
    437 
    438     // sequence number of NetworkRequests
    439     private int mNextNetworkRequestId = 1;
    440 
    441     /**
    442      * Implements support for the legacy "one network per network type" model.
    443      *
    444      * We used to have a static array of NetworkStateTrackers, one for each
    445      * network type, but that doesn't work any more now that we can have,
    446      * for example, more that one wifi network. This class stores all the
    447      * NetworkAgentInfo objects that support a given type, but the legacy
    448      * API will only see the first one.
    449      *
    450      * It serves two main purposes:
    451      *
    452      * 1. Provide information about "the network for a given type" (since this
    453      *    API only supports one).
    454      * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
    455      *    the first network for a given type changes, or if the default network
    456      *    changes.
    457      */
    458     private class LegacyTypeTracker {
    459 
    460         private static final boolean DBG = true;
    461         private static final boolean VDBG = false;
    462         private static final String TAG = "CSLegacyTypeTracker";
    463 
    464         /**
    465          * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
    466          * Each list holds references to all NetworkAgentInfos that are used to
    467          * satisfy requests for that network type.
    468          *
    469          * This array is built out at startup such that an unsupported network
    470          * doesn't get an ArrayList instance, making this a tristate:
    471          * unsupported, supported but not active and active.
    472          *
    473          * The actual lists are populated when we scan the network types that
    474          * are supported on this device.
    475          */
    476         private ArrayList<NetworkAgentInfo> mTypeLists[];
    477 
    478         public LegacyTypeTracker() {
    479             mTypeLists = (ArrayList<NetworkAgentInfo>[])
    480                     new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
    481         }
    482 
    483         public void addSupportedType(int type) {
    484             if (mTypeLists[type] != null) {
    485                 throw new IllegalStateException(
    486                         "legacy list for type " + type + "already initialized");
    487             }
    488             mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
    489         }
    490 
    491         public boolean isTypeSupported(int type) {
    492             return isNetworkTypeValid(type) && mTypeLists[type] != null;
    493         }
    494 
    495         public NetworkAgentInfo getNetworkForType(int type) {
    496             if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
    497                 return mTypeLists[type].get(0);
    498             } else {
    499                 return null;
    500             }
    501         }
    502 
    503         private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
    504             if (DBG) {
    505                 log("Sending " + (connected ? "connected" : "disconnected") +
    506                         " broadcast for type " + type + " " + nai.name() +
    507                         " isDefaultNetwork=" + isDefaultNetwork(nai));
    508             }
    509         }
    510 
    511         /** Adds the given network to the specified legacy type list. */
    512         public void add(int type, NetworkAgentInfo nai) {
    513             if (!isTypeSupported(type)) {
    514                 return;  // Invalid network type.
    515             }
    516             if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
    517 
    518             ArrayList<NetworkAgentInfo> list = mTypeLists[type];
    519             if (list.contains(nai)) {
    520                 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
    521                 return;
    522             }
    523 
    524             list.add(nai);
    525 
    526             // Send a broadcast if this is the first network of its type or if it's the default.
    527             if (list.size() == 1 || isDefaultNetwork(nai)) {
    528                 maybeLogBroadcast(nai, true, type);
    529                 sendLegacyNetworkBroadcast(nai, true, type);
    530             }
    531         }
    532 
    533         /** Removes the given network from the specified legacy type list. */
    534         public void remove(int type, NetworkAgentInfo nai) {
    535             ArrayList<NetworkAgentInfo> list = mTypeLists[type];
    536             if (list == null || list.isEmpty()) {
    537                 return;
    538             }
    539 
    540             boolean wasFirstNetwork = list.get(0).equals(nai);
    541 
    542             if (!list.remove(nai)) {
    543                 return;
    544             }
    545 
    546             if (wasFirstNetwork || isDefaultNetwork(nai)) {
    547                 maybeLogBroadcast(nai, false, type);
    548                 sendLegacyNetworkBroadcast(nai, false, type);
    549             }
    550 
    551             if (!list.isEmpty() && wasFirstNetwork) {
    552                 if (DBG) log("Other network available for type " + type +
    553                               ", sending connected broadcast");
    554                 maybeLogBroadcast(list.get(0), false, type);
    555                 sendLegacyNetworkBroadcast(list.get(0), false, type);
    556             }
    557         }
    558 
    559         /** Removes the given network from all legacy type lists. */
    560         public void remove(NetworkAgentInfo nai) {
    561             if (VDBG) log("Removing agent " + nai);
    562             for (int type = 0; type < mTypeLists.length; type++) {
    563                 remove(type, nai);
    564             }
    565         }
    566 
    567         private String naiToString(NetworkAgentInfo nai) {
    568             String name = (nai != null) ? nai.name() : "null";
    569             String state = (nai.networkInfo != null) ?
    570                     nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
    571                     "???/???";
    572             return name + " " + state;
    573         }
    574 
    575         public void dump(IndentingPrintWriter pw) {
    576             for (int type = 0; type < mTypeLists.length; type++) {
    577                 if (mTypeLists[type] == null) continue;
    578                 pw.print(type + " ");
    579                 pw.increaseIndent();
    580                 if (mTypeLists[type].size() == 0) pw.println("none");
    581                 for (NetworkAgentInfo nai : mTypeLists[type]) {
    582                     pw.println(naiToString(nai));
    583                 }
    584                 pw.decreaseIndent();
    585             }
    586         }
    587 
    588         // This class needs its own log method because it has a different TAG.
    589         private void log(String s) {
    590             Slog.d(TAG, s);
    591         }
    592 
    593     }
    594     private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
    595 
    596     public ConnectivityService(Context context, INetworkManagementService netManager,
    597             INetworkStatsService statsService, INetworkPolicyManager policyManager) {
    598         if (DBG) log("ConnectivityService starting up");
    599 
    600         NetworkCapabilities netCap = new NetworkCapabilities();
    601         netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    602         netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
    603         mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
    604         NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
    605                 NetworkRequestInfo.REQUEST);
    606         mNetworkRequests.put(mDefaultRequest, nri);
    607 
    608         HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
    609         handlerThread.start();
    610         mHandler = new InternalHandler(handlerThread.getLooper());
    611         mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
    612 
    613         // setup our unique device name
    614         if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
    615             String id = Settings.Secure.getString(context.getContentResolver(),
    616                     Settings.Secure.ANDROID_ID);
    617             if (id != null && id.length() > 0) {
    618                 String name = new String("android-").concat(id);
    619                 SystemProperties.set("net.hostname", name);
    620             }
    621         }
    622 
    623         // read our default dns server ip
    624         String dns = Settings.Global.getString(context.getContentResolver(),
    625                 Settings.Global.DEFAULT_DNS_SERVER);
    626         if (dns == null || dns.length() == 0) {
    627             dns = context.getResources().getString(
    628                     com.android.internal.R.string.config_default_dns_server);
    629         }
    630         try {
    631             mDefaultDns = NetworkUtils.numericToInetAddress(dns);
    632         } catch (IllegalArgumentException e) {
    633             loge("Error setting defaultDns using " + dns);
    634         }
    635 
    636         mContext = checkNotNull(context, "missing Context");
    637         mNetd = checkNotNull(netManager, "missing INetworkManagementService");
    638         mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
    639         mKeyStore = KeyStore.getInstance();
    640         mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    641 
    642         try {
    643             mPolicyManager.registerListener(mPolicyListener);
    644         } catch (RemoteException e) {
    645             // ouch, no rules updates means some processes may never get network
    646             loge("unable to register INetworkPolicyListener" + e.toString());
    647         }
    648 
    649         final PowerManager powerManager = (PowerManager) context.getSystemService(
    650                 Context.POWER_SERVICE);
    651         mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    652         mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
    653                 com.android.internal.R.integer.config_networkTransitionTimeout);
    654 
    655         mNetTrackers = new NetworkStateTracker[
    656                 ConnectivityManager.MAX_NETWORK_TYPE+1];
    657 
    658         mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
    659 
    660         // TODO: What is the "correct" way to do determine if this is a wifi only device?
    661         boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
    662         log("wifiOnly=" + wifiOnly);
    663         String[] naStrings = context.getResources().getStringArray(
    664                 com.android.internal.R.array.networkAttributes);
    665         for (String naString : naStrings) {
    666             try {
    667                 NetworkConfig n = new NetworkConfig(naString);
    668                 if (VDBG) log("naString=" + naString + " config=" + n);
    669                 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
    670                     loge("Error in networkAttributes - ignoring attempt to define type " +
    671                             n.type);
    672                     continue;
    673                 }
    674                 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
    675                     log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
    676                             n.type);
    677                     continue;
    678                 }
    679                 if (mNetConfigs[n.type] != null) {
    680                     loge("Error in networkAttributes - ignoring attempt to redefine type " +
    681                             n.type);
    682                     continue;
    683                 }
    684                 mLegacyTypeTracker.addSupportedType(n.type);
    685 
    686                 mNetConfigs[n.type] = n;
    687                 mNetworksDefined++;
    688             } catch(Exception e) {
    689                 // ignore it - leave the entry null
    690             }
    691         }
    692         if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
    693 
    694         mProtectedNetworks = new ArrayList<Integer>();
    695         int[] protectedNetworks = context.getResources().getIntArray(
    696                 com.android.internal.R.array.config_protectedNetworks);
    697         for (int p : protectedNetworks) {
    698             if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
    699                 mProtectedNetworks.add(p);
    700             } else {
    701                 if (DBG) loge("Ignoring protectedNetwork " + p);
    702             }
    703         }
    704 
    705         mTestMode = SystemProperties.get("cm.test.mode").equals("true")
    706                 && SystemProperties.get("ro.build.type").equals("eng");
    707 
    708         mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
    709 
    710         mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
    711 
    712         //set up the listener for user state for creating user VPNs
    713         IntentFilter intentFilter = new IntentFilter();
    714         intentFilter.addAction(Intent.ACTION_USER_STARTING);
    715         intentFilter.addAction(Intent.ACTION_USER_STOPPING);
    716         mContext.registerReceiverAsUser(
    717                 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
    718         mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
    719 
    720         try {
    721             mNetd.registerObserver(mTethering);
    722             mNetd.registerObserver(mDataActivityObserver);
    723             mNetd.registerObserver(mClat);
    724         } catch (RemoteException e) {
    725             loge("Error registering observer :" + e);
    726         }
    727 
    728         if (DBG) {
    729             mInetLog = new ArrayList();
    730         }
    731 
    732         mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
    733         mSettingsObserver.observe(mContext);
    734 
    735         mDataConnectionStats = new DataConnectionStats(mContext);
    736         mDataConnectionStats.startMonitoring();
    737 
    738         mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
    739 
    740         IntentFilter filter = new IntentFilter();
    741         filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
    742         mContext.registerReceiver(
    743                 new BroadcastReceiver() {
    744                     @Override
    745                     public void onReceive(Context context, Intent intent) {
    746                         String action = intent.getAction();
    747                         if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
    748                             mHandler.sendMessage(mHandler.obtainMessage
    749                                     (EVENT_SAMPLE_INTERVAL_ELAPSED));
    750                         }
    751                     }
    752                 },
    753                 new IntentFilter(filter));
    754 
    755         mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
    756 
    757         mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
    758     }
    759 
    760     private synchronized int nextNetworkRequestId() {
    761         return mNextNetworkRequestId++;
    762     }
    763 
    764     private void assignNextNetId(NetworkAgentInfo nai) {
    765         synchronized (mNetworkForNetId) {
    766             for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
    767                 int netId = mNextNetId;
    768                 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
    769                 // Make sure NetID unused.  http://b/16815182
    770                 if (mNetworkForNetId.get(netId) == null) {
    771                     nai.network = new Network(netId);
    772                     mNetworkForNetId.put(netId, nai);
    773                     return;
    774                 }
    775             }
    776         }
    777         throw new IllegalStateException("No free netIds");
    778     }
    779 
    780     private int getConnectivityChangeDelay() {
    781         final ContentResolver cr = mContext.getContentResolver();
    782 
    783         /** Check system properties for the default value then use secure settings value, if any. */
    784         int defaultDelay = SystemProperties.getInt(
    785                 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
    786                 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
    787         return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
    788                 defaultDelay);
    789     }
    790 
    791     private boolean teardown(NetworkStateTracker netTracker) {
    792         if (netTracker.teardown()) {
    793             netTracker.setTeardownRequested(true);
    794             return true;
    795         } else {
    796             return false;
    797         }
    798     }
    799 
    800     /**
    801      * Check if UID should be blocked from using the network represented by the given networkType.
    802      * @deprecated Uses mLegacyTypeTracker; cannot deal with multiple Networks of the same type.
    803      */
    804     private boolean isNetworkBlocked(int networkType, int uid) {
    805         return isNetworkWithLinkPropertiesBlocked(getLinkPropertiesForType(networkType), uid);
    806     }
    807 
    808     /**
    809      * Check if UID should be blocked from using the network represented by the given
    810      * NetworkAgentInfo.
    811      */
    812     private boolean isNetworkBlocked(NetworkAgentInfo nai, int uid) {
    813         return isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid);
    814     }
    815 
    816     /**
    817      * Check if UID should be blocked from using the network with the given LinkProperties.
    818      */
    819     private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
    820         final boolean networkCostly;
    821         final int uidRules;
    822 
    823         final String iface = (lp == null ? "" : lp.getInterfaceName());
    824         synchronized (mRulesLock) {
    825             networkCostly = mMeteredIfaces.contains(iface);
    826             uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
    827         }
    828 
    829         if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
    830             return true;
    831         }
    832 
    833         // no restrictive rules; network is visible
    834         return false;
    835     }
    836 
    837     /**
    838      * Return a filtered {@link NetworkInfo}, potentially marked
    839      * {@link DetailedState#BLOCKED} based on
    840      * {@link #isNetworkBlocked}.
    841      * @deprecated Uses mLegacyTypeTracker; cannot deal with multiple Networks of the same type.
    842      */
    843     private NetworkInfo getFilteredNetworkInfo(int networkType, int uid) {
    844         NetworkInfo info = getNetworkInfoForType(networkType);
    845         return getFilteredNetworkInfo(info, networkType, uid);
    846     }
    847 
    848     /*
    849      * @deprecated Uses mLegacyTypeTracker; cannot deal with multiple Networks of the same type.
    850      */
    851     private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, int networkType, int uid) {
    852         if (isNetworkBlocked(networkType, uid)) {
    853             // network is blocked; clone and override state
    854             info = new NetworkInfo(info);
    855             info.setDetailedState(DetailedState.BLOCKED, null, null);
    856             if (VDBG) log("returning Blocked NetworkInfo");
    857         }
    858         if (mLockdownTracker != null) {
    859             info = mLockdownTracker.augmentNetworkInfo(info);
    860             if (VDBG) log("returning Locked NetworkInfo");
    861         }
    862         return info;
    863     }
    864 
    865     private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid) {
    866         NetworkInfo info = nai.networkInfo;
    867         if (isNetworkBlocked(nai, uid)) {
    868             // network is blocked; clone and override state
    869             info = new NetworkInfo(info);
    870             info.setDetailedState(DetailedState.BLOCKED, null, null);
    871             if (DBG) log("returning Blocked NetworkInfo");
    872         }
    873         if (mLockdownTracker != null) {
    874             info = mLockdownTracker.augmentNetworkInfo(info);
    875             if (DBG) log("returning Locked NetworkInfo");
    876         }
    877         return info;
    878     }
    879 
    880     /**
    881      * Return NetworkInfo for the active (i.e., connected) network interface.
    882      * It is assumed that at most one network is active at a time. If more
    883      * than one is active, it is indeterminate which will be returned.
    884      * @return the info for the active network, or {@code null} if none is
    885      * active
    886      */
    887     @Override
    888     public NetworkInfo getActiveNetworkInfo() {
    889         enforceAccessPermission();
    890         final int uid = Binder.getCallingUid();
    891         return getNetworkInfo(mActiveDefaultNetwork, uid);
    892     }
    893 
    894     /**
    895      * Find the first Provisioning network.
    896      *
    897      * @return NetworkInfo or null if none.
    898      */
    899     private NetworkInfo getProvisioningNetworkInfo() {
    900         enforceAccessPermission();
    901 
    902         // Find the first Provisioning Network
    903         NetworkInfo provNi = null;
    904         for (NetworkInfo ni : getAllNetworkInfo()) {
    905             if (ni.isConnectedToProvisioningNetwork()) {
    906                 provNi = ni;
    907                 break;
    908             }
    909         }
    910         if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
    911         return provNi;
    912     }
    913 
    914     /**
    915      * Find the first Provisioning network or the ActiveDefaultNetwork
    916      * if there is no Provisioning network
    917      *
    918      * @return NetworkInfo or null if none.
    919      */
    920     @Override
    921     public NetworkInfo getProvisioningOrActiveNetworkInfo() {
    922         enforceAccessPermission();
    923 
    924         NetworkInfo provNi = getProvisioningNetworkInfo();
    925         if (provNi == null) {
    926             final int uid = Binder.getCallingUid();
    927             provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
    928         }
    929         if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
    930         return provNi;
    931     }
    932 
    933     public NetworkInfo getActiveNetworkInfoUnfiltered() {
    934         enforceAccessPermission();
    935         if (isNetworkTypeValid(mActiveDefaultNetwork)) {
    936             return getNetworkInfoForType(mActiveDefaultNetwork);
    937         }
    938         return null;
    939     }
    940 
    941     @Override
    942     public NetworkInfo getActiveNetworkInfoForUid(int uid) {
    943         enforceConnectivityInternalPermission();
    944         return getNetworkInfo(mActiveDefaultNetwork, uid);
    945     }
    946 
    947     @Override
    948     public NetworkInfo getNetworkInfo(int networkType) {
    949         enforceAccessPermission();
    950         final int uid = Binder.getCallingUid();
    951         return getNetworkInfo(networkType, uid);
    952     }
    953 
    954     private NetworkInfo getNetworkInfo(int networkType, int uid) {
    955         NetworkInfo info = null;
    956         if (isNetworkTypeValid(networkType)) {
    957             if (getNetworkInfoForType(networkType) != null) {
    958                 info = getFilteredNetworkInfo(networkType, uid);
    959             }
    960         }
    961         return info;
    962     }
    963 
    964     @Override
    965     public NetworkInfo getNetworkInfoForNetwork(Network network) {
    966         enforceAccessPermission();
    967         if (network == null) return null;
    968 
    969         final int uid = Binder.getCallingUid();
    970         NetworkAgentInfo nai = null;
    971         synchronized (mNetworkForNetId) {
    972             nai = mNetworkForNetId.get(network.netId);
    973         }
    974         if (nai == null) return null;
    975         synchronized (nai) {
    976             if (nai.networkInfo == null) return null;
    977 
    978             return getFilteredNetworkInfo(nai, uid);
    979         }
    980     }
    981 
    982     @Override
    983     public NetworkInfo[] getAllNetworkInfo() {
    984         enforceAccessPermission();
    985         final int uid = Binder.getCallingUid();
    986         final ArrayList<NetworkInfo> result = Lists.newArrayList();
    987         for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
    988                 networkType++) {
    989             if (getNetworkInfoForType(networkType) != null) {
    990                 result.add(getFilteredNetworkInfo(networkType, uid));
    991             }
    992         }
    993         return result.toArray(new NetworkInfo[result.size()]);
    994     }
    995 
    996     @Override
    997     public Network getNetworkForType(int networkType) {
    998         enforceAccessPermission();
    999         final int uid = Binder.getCallingUid();
   1000         if (isNetworkBlocked(networkType, uid)) {
   1001             return null;
   1002         }
   1003         NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
   1004         return (nai == null) ? null : nai.network;
   1005     }
   1006 
   1007     @Override
   1008     public Network[] getAllNetworks() {
   1009         enforceAccessPermission();
   1010         final ArrayList<Network> result = new ArrayList();
   1011         synchronized (mNetworkForNetId) {
   1012             for (int i = 0; i < mNetworkForNetId.size(); i++) {
   1013                 result.add(new Network(mNetworkForNetId.valueAt(i).network));
   1014             }
   1015         }
   1016         return result.toArray(new Network[result.size()]);
   1017     }
   1018 
   1019     @Override
   1020     public boolean isNetworkSupported(int networkType) {
   1021         enforceAccessPermission();
   1022         return (isNetworkTypeValid(networkType) && (getNetworkInfoForType(networkType) != null));
   1023     }
   1024 
   1025     /**
   1026      * Return LinkProperties for the active (i.e., connected) default
   1027      * network interface.  It is assumed that at most one default network
   1028      * is active at a time. If more than one is active, it is indeterminate
   1029      * which will be returned.
   1030      * @return the ip properties for the active network, or {@code null} if
   1031      * none is active
   1032      */
   1033     @Override
   1034     public LinkProperties getActiveLinkProperties() {
   1035         return getLinkPropertiesForType(mActiveDefaultNetwork);
   1036     }
   1037 
   1038     @Override
   1039     public LinkProperties getLinkPropertiesForType(int networkType) {
   1040         enforceAccessPermission();
   1041         if (isNetworkTypeValid(networkType)) {
   1042             return getLinkPropertiesForTypeInternal(networkType);
   1043         }
   1044         return null;
   1045     }
   1046 
   1047     // TODO - this should be ALL networks
   1048     @Override
   1049     public LinkProperties getLinkProperties(Network network) {
   1050         enforceAccessPermission();
   1051         NetworkAgentInfo nai = null;
   1052         synchronized (mNetworkForNetId) {
   1053             nai = mNetworkForNetId.get(network.netId);
   1054         }
   1055 
   1056         if (nai != null) {
   1057             synchronized (nai) {
   1058                 return new LinkProperties(nai.linkProperties);
   1059             }
   1060         }
   1061         return null;
   1062     }
   1063 
   1064     @Override
   1065     public NetworkCapabilities getNetworkCapabilities(Network network) {
   1066         enforceAccessPermission();
   1067         NetworkAgentInfo nai = null;
   1068         synchronized (mNetworkForNetId) {
   1069             nai = mNetworkForNetId.get(network.netId);
   1070         }
   1071         if (nai != null) {
   1072             synchronized (nai) {
   1073                 return new NetworkCapabilities(nai.networkCapabilities);
   1074             }
   1075         }
   1076         return null;
   1077     }
   1078 
   1079     @Override
   1080     public NetworkState[] getAllNetworkState() {
   1081         enforceAccessPermission();
   1082         final int uid = Binder.getCallingUid();
   1083         final ArrayList<NetworkState> result = Lists.newArrayList();
   1084         for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
   1085                 networkType++) {
   1086             if (getNetworkInfoForType(networkType) != null) {
   1087                 final NetworkInfo info = getFilteredNetworkInfo(networkType, uid);
   1088                 final LinkProperties lp = getLinkPropertiesForTypeInternal(networkType);
   1089                 final NetworkCapabilities netcap = getNetworkCapabilitiesForType(networkType);
   1090                 result.add(new NetworkState(info, lp, netcap));
   1091             }
   1092         }
   1093         return result.toArray(new NetworkState[result.size()]);
   1094     }
   1095 
   1096     private NetworkState getNetworkStateUnchecked(int networkType) {
   1097         if (isNetworkTypeValid(networkType)) {
   1098             NetworkInfo info = getNetworkInfoForType(networkType);
   1099             if (info != null) {
   1100                 return new NetworkState(info,
   1101                         getLinkPropertiesForTypeInternal(networkType),
   1102                         getNetworkCapabilitiesForType(networkType));
   1103             }
   1104         }
   1105         return null;
   1106     }
   1107 
   1108     @Override
   1109     public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
   1110         enforceAccessPermission();
   1111 
   1112         final long token = Binder.clearCallingIdentity();
   1113         try {
   1114             final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
   1115             if (state != null) {
   1116                 try {
   1117                     return mPolicyManager.getNetworkQuotaInfo(state);
   1118                 } catch (RemoteException e) {
   1119                 }
   1120             }
   1121             return null;
   1122         } finally {
   1123             Binder.restoreCallingIdentity(token);
   1124         }
   1125     }
   1126 
   1127     @Override
   1128     public boolean isActiveNetworkMetered() {
   1129         enforceAccessPermission();
   1130         final long token = Binder.clearCallingIdentity();
   1131         try {
   1132             return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
   1133         } finally {
   1134             Binder.restoreCallingIdentity(token);
   1135         }
   1136     }
   1137 
   1138     private boolean isNetworkMeteredUnchecked(int networkType) {
   1139         final NetworkState state = getNetworkStateUnchecked(networkType);
   1140         if (state != null) {
   1141             try {
   1142                 return mPolicyManager.isNetworkMetered(state);
   1143             } catch (RemoteException e) {
   1144             }
   1145         }
   1146         return false;
   1147     }
   1148 
   1149     private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
   1150         @Override
   1151         public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
   1152             int deviceType = Integer.parseInt(label);
   1153             sendDataActivityBroadcast(deviceType, active, tsNanos);
   1154         }
   1155     };
   1156 
   1157     /**
   1158      * Ensure that a network route exists to deliver traffic to the specified
   1159      * host via the specified network interface.
   1160      * @param networkType the type of the network over which traffic to the
   1161      * specified host is to be routed
   1162      * @param hostAddress the IP address of the host to which the route is
   1163      * desired
   1164      * @return {@code true} on success, {@code false} on failure
   1165      */
   1166     public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
   1167         enforceChangePermission();
   1168         if (mProtectedNetworks.contains(networkType)) {
   1169             enforceConnectivityInternalPermission();
   1170         }
   1171 
   1172         InetAddress addr;
   1173         try {
   1174             addr = InetAddress.getByAddress(hostAddress);
   1175         } catch (UnknownHostException e) {
   1176             if (DBG) log("requestRouteToHostAddress got " + e.toString());
   1177             return false;
   1178         }
   1179 
   1180         if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
   1181             if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
   1182             return false;
   1183         }
   1184 
   1185         NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
   1186         if (nai == null) {
   1187             if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
   1188                 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
   1189             } else {
   1190                 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
   1191             }
   1192             return false;
   1193         }
   1194 
   1195         DetailedState netState;
   1196         synchronized (nai) {
   1197             netState = nai.networkInfo.getDetailedState();
   1198         }
   1199 
   1200         if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
   1201             if (VDBG) {
   1202                 log("requestRouteToHostAddress on down network "
   1203                         + "(" + networkType + ") - dropped"
   1204                         + " netState=" + netState);
   1205             }
   1206             return false;
   1207         }
   1208 
   1209         final int uid = Binder.getCallingUid();
   1210         final long token = Binder.clearCallingIdentity();
   1211         try {
   1212             LinkProperties lp;
   1213             int netId;
   1214             synchronized (nai) {
   1215                 lp = nai.linkProperties;
   1216                 netId = nai.network.netId;
   1217             }
   1218             boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
   1219             if (DBG) log("requestRouteToHostAddress ok=" + ok);
   1220             return ok;
   1221         } finally {
   1222             Binder.restoreCallingIdentity(token);
   1223         }
   1224     }
   1225 
   1226     private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
   1227         RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
   1228         if (bestRoute == null) {
   1229             bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
   1230         } else {
   1231             String iface = bestRoute.getInterface();
   1232             if (bestRoute.getGateway().equals(addr)) {
   1233                 // if there is no better route, add the implied hostroute for our gateway
   1234                 bestRoute = RouteInfo.makeHostRoute(addr, iface);
   1235             } else {
   1236                 // if we will connect to this through another route, add a direct route
   1237                 // to it's gateway
   1238                 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
   1239             }
   1240         }
   1241         if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
   1242         try {
   1243             mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
   1244         } catch (Exception e) {
   1245             // never crash - catch them all
   1246             if (DBG) loge("Exception trying to add a route: " + e);
   1247             return false;
   1248         }
   1249         return true;
   1250     }
   1251 
   1252     public void setDataDependency(int networkType, boolean met) {
   1253         enforceConnectivityInternalPermission();
   1254 
   1255         mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
   1256                 (met ? ENABLED : DISABLED), networkType));
   1257     }
   1258 
   1259     private void handleSetDependencyMet(int networkType, boolean met) {
   1260         if (mNetTrackers[networkType] != null) {
   1261             if (DBG) {
   1262                 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
   1263             }
   1264             mNetTrackers[networkType].setDependencyMet(met);
   1265         }
   1266     }
   1267 
   1268     private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
   1269         @Override
   1270         public void onUidRulesChanged(int uid, int uidRules) {
   1271             // caller is NPMS, since we only register with them
   1272             if (LOGD_RULES) {
   1273                 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
   1274             }
   1275 
   1276             synchronized (mRulesLock) {
   1277                 // skip update when we've already applied rules
   1278                 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
   1279                 if (oldRules == uidRules) return;
   1280 
   1281                 mUidRules.put(uid, uidRules);
   1282             }
   1283 
   1284             // TODO: notify UID when it has requested targeted updates
   1285         }
   1286 
   1287         @Override
   1288         public void onMeteredIfacesChanged(String[] meteredIfaces) {
   1289             // caller is NPMS, since we only register with them
   1290             if (LOGD_RULES) {
   1291                 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
   1292             }
   1293 
   1294             synchronized (mRulesLock) {
   1295                 mMeteredIfaces.clear();
   1296                 for (String iface : meteredIfaces) {
   1297                     mMeteredIfaces.add(iface);
   1298                 }
   1299             }
   1300         }
   1301 
   1302         @Override
   1303         public void onRestrictBackgroundChanged(boolean restrictBackground) {
   1304             // caller is NPMS, since we only register with them
   1305             if (LOGD_RULES) {
   1306                 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
   1307             }
   1308 
   1309             // kick off connectivity change broadcast for active network, since
   1310             // global background policy change is radical.
   1311             final int networkType = mActiveDefaultNetwork;
   1312             if (isNetworkTypeValid(networkType)) {
   1313                 final NetworkStateTracker tracker = mNetTrackers[networkType];
   1314                 if (tracker != null) {
   1315                     final NetworkInfo info = tracker.getNetworkInfo();
   1316                     if (info != null && info.isConnected()) {
   1317                         sendConnectedBroadcast(info);
   1318                     }
   1319                 }
   1320             }
   1321         }
   1322     };
   1323 
   1324     @Override
   1325     public void setPolicyDataEnable(int networkType, boolean enabled) {
   1326         // only someone like NPMS should only be calling us
   1327         mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
   1328 
   1329         mHandler.sendMessage(mHandler.obtainMessage(
   1330                 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
   1331     }
   1332 
   1333     private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
   1334    // TODO - handle this passing to factories
   1335 //        if (isNetworkTypeValid(networkType)) {
   1336 //            final NetworkStateTracker tracker = mNetTrackers[networkType];
   1337 //            if (tracker != null) {
   1338 //                tracker.setPolicyDataEnable(enabled);
   1339 //            }
   1340 //        }
   1341     }
   1342 
   1343     private void enforceInternetPermission() {
   1344         mContext.enforceCallingOrSelfPermission(
   1345                 android.Manifest.permission.INTERNET,
   1346                 "ConnectivityService");
   1347     }
   1348 
   1349     private void enforceAccessPermission() {
   1350         mContext.enforceCallingOrSelfPermission(
   1351                 android.Manifest.permission.ACCESS_NETWORK_STATE,
   1352                 "ConnectivityService");
   1353     }
   1354 
   1355     private void enforceChangePermission() {
   1356         mContext.enforceCallingOrSelfPermission(
   1357                 android.Manifest.permission.CHANGE_NETWORK_STATE,
   1358                 "ConnectivityService");
   1359     }
   1360 
   1361     private void enforceTetherAccessPermission() {
   1362         mContext.enforceCallingOrSelfPermission(
   1363                 android.Manifest.permission.ACCESS_NETWORK_STATE,
   1364                 "ConnectivityService");
   1365     }
   1366 
   1367     private void enforceConnectivityInternalPermission() {
   1368         mContext.enforceCallingOrSelfPermission(
   1369                 android.Manifest.permission.CONNECTIVITY_INTERNAL,
   1370                 "ConnectivityService");
   1371     }
   1372 
   1373     public void sendConnectedBroadcast(NetworkInfo info) {
   1374         enforceConnectivityInternalPermission();
   1375         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
   1376         sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
   1377     }
   1378 
   1379     private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
   1380         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
   1381         sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
   1382     }
   1383 
   1384     private void sendInetConditionBroadcast(NetworkInfo info) {
   1385         sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
   1386     }
   1387 
   1388     private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
   1389         if (mLockdownTracker != null) {
   1390             info = mLockdownTracker.augmentNetworkInfo(info);
   1391         }
   1392 
   1393         Intent intent = new Intent(bcastType);
   1394         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
   1395         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
   1396         if (info.isFailover()) {
   1397             intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
   1398             info.setFailover(false);
   1399         }
   1400         if (info.getReason() != null) {
   1401             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
   1402         }
   1403         if (info.getExtraInfo() != null) {
   1404             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
   1405                     info.getExtraInfo());
   1406         }
   1407         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
   1408         return intent;
   1409     }
   1410 
   1411     private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
   1412         sendStickyBroadcast(makeGeneralIntent(info, bcastType));
   1413     }
   1414 
   1415     private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
   1416         sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
   1417     }
   1418 
   1419     private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
   1420         Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
   1421         intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
   1422         intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
   1423         intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
   1424         final long ident = Binder.clearCallingIdentity();
   1425         try {
   1426             mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
   1427                     RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
   1428         } finally {
   1429             Binder.restoreCallingIdentity(ident);
   1430         }
   1431     }
   1432 
   1433     private void sendStickyBroadcast(Intent intent) {
   1434         synchronized(this) {
   1435             if (!mSystemReady) {
   1436                 mInitialBroadcast = new Intent(intent);
   1437             }
   1438             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
   1439             if (DBG) {
   1440                 log("sendStickyBroadcast: action=" + intent.getAction());
   1441             }
   1442 
   1443             final long ident = Binder.clearCallingIdentity();
   1444             try {
   1445                 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   1446             } finally {
   1447                 Binder.restoreCallingIdentity(ident);
   1448             }
   1449         }
   1450     }
   1451 
   1452     private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
   1453         if (delayMs <= 0) {
   1454             sendStickyBroadcast(intent);
   1455         } else {
   1456             if (VDBG) {
   1457                 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
   1458                         + intent.getAction());
   1459             }
   1460             mHandler.sendMessageDelayed(mHandler.obtainMessage(
   1461                     EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
   1462         }
   1463     }
   1464 
   1465     void systemReady() {
   1466         // start network sampling ..
   1467         Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
   1468         intent.setPackage(mContext.getPackageName());
   1469 
   1470         mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
   1471                 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
   1472         setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
   1473 
   1474         loadGlobalProxy();
   1475 
   1476         synchronized(this) {
   1477             mSystemReady = true;
   1478             if (mInitialBroadcast != null) {
   1479                 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
   1480                 mInitialBroadcast = null;
   1481             }
   1482         }
   1483         // load the global proxy at startup
   1484         mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
   1485 
   1486         // Try bringing up tracker, but if KeyStore isn't ready yet, wait
   1487         // for user to unlock device.
   1488         if (!updateLockdownVpn()) {
   1489             final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
   1490             mContext.registerReceiver(mUserPresentReceiver, filter);
   1491         }
   1492 
   1493         mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
   1494 
   1495         mPermissionMonitor.startMonitoring();
   1496     }
   1497 
   1498     private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
   1499         @Override
   1500         public void onReceive(Context context, Intent intent) {
   1501             // Try creating lockdown tracker, since user present usually means
   1502             // unlocked keystore.
   1503             if (updateLockdownVpn()) {
   1504                 mContext.unregisterReceiver(this);
   1505             }
   1506         }
   1507     };
   1508 
   1509     /** @hide */
   1510     @Override
   1511     public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
   1512         enforceConnectivityInternalPermission();
   1513         if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
   1514 //        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
   1515     }
   1516 
   1517     /**
   1518      * Setup data activity tracking for the given network.
   1519      *
   1520      * Every {@code setupDataActivityTracking} should be paired with a
   1521      * {@link #removeDataActivityTracking} for cleanup.
   1522      */
   1523     private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
   1524         final String iface = networkAgent.linkProperties.getInterfaceName();
   1525 
   1526         final int timeout;
   1527         int type = ConnectivityManager.TYPE_NONE;
   1528 
   1529         if (networkAgent.networkCapabilities.hasTransport(
   1530                 NetworkCapabilities.TRANSPORT_CELLULAR)) {
   1531             timeout = Settings.Global.getInt(mContext.getContentResolver(),
   1532                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
   1533                                              5);
   1534             type = ConnectivityManager.TYPE_MOBILE;
   1535         } else if (networkAgent.networkCapabilities.hasTransport(
   1536                 NetworkCapabilities.TRANSPORT_WIFI)) {
   1537             timeout = Settings.Global.getInt(mContext.getContentResolver(),
   1538                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
   1539                                              0);
   1540             type = ConnectivityManager.TYPE_WIFI;
   1541         } else {
   1542             // do not track any other networks
   1543             timeout = 0;
   1544         }
   1545 
   1546         if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
   1547             try {
   1548                 mNetd.addIdleTimer(iface, timeout, type);
   1549             } catch (Exception e) {
   1550                 // You shall not crash!
   1551                 loge("Exception in setupDataActivityTracking " + e);
   1552             }
   1553         }
   1554     }
   1555 
   1556     /**
   1557      * Remove data activity tracking when network disconnects.
   1558      */
   1559     private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
   1560         final String iface = networkAgent.linkProperties.getInterfaceName();
   1561         final NetworkCapabilities caps = networkAgent.networkCapabilities;
   1562 
   1563         if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
   1564                               caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
   1565             try {
   1566                 // the call fails silently if no idletimer setup for this interface
   1567                 mNetd.removeIdleTimer(iface);
   1568             } catch (Exception e) {
   1569                 loge("Exception in removeDataActivityTracking " + e);
   1570             }
   1571         }
   1572     }
   1573 
   1574     /**
   1575      * Reads the network specific MTU size from reources.
   1576      * and set it on it's iface.
   1577      */
   1578     private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
   1579         final String iface = newLp.getInterfaceName();
   1580         final int mtu = newLp.getMtu();
   1581         if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
   1582             if (VDBG) log("identical MTU - not setting");
   1583             return;
   1584         }
   1585 
   1586         if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
   1587             loge("Unexpected mtu value: " + mtu + ", " + iface);
   1588             return;
   1589         }
   1590 
   1591         // Cannot set MTU without interface name
   1592         if (TextUtils.isEmpty(iface)) {
   1593             loge("Setting MTU size with null iface.");
   1594             return;
   1595         }
   1596 
   1597         try {
   1598             if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
   1599             mNetd.setMtu(iface, mtu);
   1600         } catch (Exception e) {
   1601             Slog.e(TAG, "exception in setMtu()" + e);
   1602         }
   1603     }
   1604 
   1605     private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
   1606 
   1607     private void updateTcpBufferSizes(NetworkAgentInfo nai) {
   1608         if (isDefaultNetwork(nai) == false) {
   1609             return;
   1610         }
   1611 
   1612         String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
   1613         String[] values = null;
   1614         if (tcpBufferSizes != null) {
   1615             values = tcpBufferSizes.split(",");
   1616         }
   1617 
   1618         if (values == null || values.length != 6) {
   1619             if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
   1620             tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
   1621             values = tcpBufferSizes.split(",");
   1622         }
   1623 
   1624         if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
   1625 
   1626         try {
   1627             if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
   1628 
   1629             final String prefix = "/sys/kernel/ipv4/tcp_";
   1630             FileUtils.stringToFile(prefix + "rmem_min", values[0]);
   1631             FileUtils.stringToFile(prefix + "rmem_def", values[1]);
   1632             FileUtils.stringToFile(prefix + "rmem_max", values[2]);
   1633             FileUtils.stringToFile(prefix + "wmem_min", values[3]);
   1634             FileUtils.stringToFile(prefix + "wmem_def", values[4]);
   1635             FileUtils.stringToFile(prefix + "wmem_max", values[5]);
   1636             mCurrentTcpBufferSizes = tcpBufferSizes;
   1637         } catch (IOException e) {
   1638             loge("Can't set TCP buffer sizes:" + e);
   1639         }
   1640 
   1641         final String defaultRwndKey = "net.tcp.default_init_rwnd";
   1642         int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
   1643         Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
   1644             Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
   1645         final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
   1646         if (rwndValue != 0) {
   1647             SystemProperties.set(sysctlKey, rwndValue.toString());
   1648         }
   1649     }
   1650 
   1651     private void flushVmDnsCache() {
   1652         /*
   1653          * Tell the VMs to toss their DNS caches
   1654          */
   1655         Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
   1656         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
   1657         /*
   1658          * Connectivity events can happen before boot has completed ...
   1659          */
   1660         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
   1661         final long ident = Binder.clearCallingIdentity();
   1662         try {
   1663             mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
   1664         } finally {
   1665             Binder.restoreCallingIdentity(ident);
   1666         }
   1667     }
   1668 
   1669     @Override
   1670     public int getRestoreDefaultNetworkDelay(int networkType) {
   1671         String restoreDefaultNetworkDelayStr = SystemProperties.get(
   1672                 NETWORK_RESTORE_DELAY_PROP_NAME);
   1673         if(restoreDefaultNetworkDelayStr != null &&
   1674                 restoreDefaultNetworkDelayStr.length() != 0) {
   1675             try {
   1676                 return Integer.valueOf(restoreDefaultNetworkDelayStr);
   1677             } catch (NumberFormatException e) {
   1678             }
   1679         }
   1680         // if the system property isn't set, use the value for the apn type
   1681         int ret = RESTORE_DEFAULT_NETWORK_DELAY;
   1682 
   1683         if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
   1684                 (mNetConfigs[networkType] != null)) {
   1685             ret = mNetConfigs[networkType].restoreTime;
   1686         }
   1687         return ret;
   1688     }
   1689 
   1690     @Override
   1691     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
   1692         final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
   1693         if (mContext.checkCallingOrSelfPermission(
   1694                 android.Manifest.permission.DUMP)
   1695                 != PackageManager.PERMISSION_GRANTED) {
   1696             pw.println("Permission Denial: can't dump ConnectivityService " +
   1697                     "from from pid=" + Binder.getCallingPid() + ", uid=" +
   1698                     Binder.getCallingUid());
   1699             return;
   1700         }
   1701 
   1702         pw.println("NetworkFactories for:");
   1703         pw.increaseIndent();
   1704         for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
   1705             pw.println(nfi.name);
   1706         }
   1707         pw.decreaseIndent();
   1708         pw.println();
   1709 
   1710         NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
   1711         pw.print("Active default network: ");
   1712         if (defaultNai == null) {
   1713             pw.println("none");
   1714         } else {
   1715             pw.println(defaultNai.network.netId);
   1716         }
   1717         pw.println();
   1718 
   1719         pw.println("Current Networks:");
   1720         pw.increaseIndent();
   1721         for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
   1722             pw.println(nai.toString());
   1723             pw.increaseIndent();
   1724             pw.println("Requests:");
   1725             pw.increaseIndent();
   1726             for (int i = 0; i < nai.networkRequests.size(); i++) {
   1727                 pw.println(nai.networkRequests.valueAt(i).toString());
   1728             }
   1729             pw.decreaseIndent();
   1730             pw.println("Lingered:");
   1731             pw.increaseIndent();
   1732             for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
   1733             pw.decreaseIndent();
   1734             pw.decreaseIndent();
   1735         }
   1736         pw.decreaseIndent();
   1737         pw.println();
   1738 
   1739         pw.println("Network Requests:");
   1740         pw.increaseIndent();
   1741         for (NetworkRequestInfo nri : mNetworkRequests.values()) {
   1742             pw.println(nri.toString());
   1743         }
   1744         pw.println();
   1745         pw.decreaseIndent();
   1746 
   1747         pw.print("mActiveDefaultNetwork: " + mActiveDefaultNetwork);
   1748         if (mActiveDefaultNetwork != TYPE_NONE) {
   1749             NetworkInfo activeNetworkInfo = getActiveNetworkInfo();
   1750             if (activeNetworkInfo != null) {
   1751                 pw.print(" " + activeNetworkInfo.getState() +
   1752                          "/" + activeNetworkInfo.getDetailedState());
   1753             }
   1754         }
   1755         pw.println();
   1756 
   1757         pw.println("mLegacyTypeTracker:");
   1758         pw.increaseIndent();
   1759         mLegacyTypeTracker.dump(pw);
   1760         pw.decreaseIndent();
   1761         pw.println();
   1762 
   1763         synchronized (this) {
   1764             pw.println("NetworkTransitionWakeLock is currently " +
   1765                     (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
   1766             pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
   1767         }
   1768         pw.println();
   1769 
   1770         mTethering.dump(fd, pw, args);
   1771 
   1772         if (mInetLog != null) {
   1773             pw.println();
   1774             pw.println("Inet condition reports:");
   1775             pw.increaseIndent();
   1776             for(int i = 0; i < mInetLog.size(); i++) {
   1777                 pw.println(mInetLog.get(i));
   1778             }
   1779             pw.decreaseIndent();
   1780         }
   1781     }
   1782 
   1783     private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
   1784         if (nai.network == null) return false;
   1785         final NetworkAgentInfo officialNai;
   1786         synchronized (mNetworkForNetId) {
   1787             officialNai = mNetworkForNetId.get(nai.network.netId);
   1788         }
   1789         if (officialNai != null && officialNai.equals(nai)) return true;
   1790         if (officialNai != null || VDBG) {
   1791             loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
   1792                 " - " + nai);
   1793         }
   1794         return false;
   1795     }
   1796 
   1797     private boolean isRequest(NetworkRequest request) {
   1798         return mNetworkRequests.get(request).isRequest;
   1799     }
   1800 
   1801     // must be stateless - things change under us.
   1802     private class NetworkStateTrackerHandler extends Handler {
   1803         public NetworkStateTrackerHandler(Looper looper) {
   1804             super(looper);
   1805         }
   1806 
   1807         @Override
   1808         public void handleMessage(Message msg) {
   1809             NetworkInfo info;
   1810             switch (msg.what) {
   1811                 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
   1812                     handleAsyncChannelHalfConnect(msg);
   1813                     break;
   1814                 }
   1815                 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
   1816                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1817                     if (nai != null) nai.asyncChannel.disconnect();
   1818                     break;
   1819                 }
   1820                 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
   1821                     handleAsyncChannelDisconnected(msg);
   1822                     break;
   1823                 }
   1824                 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
   1825                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1826                     if (nai == null) {
   1827                         loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
   1828                     } else {
   1829                         updateCapabilities(nai, (NetworkCapabilities)msg.obj);
   1830                     }
   1831                     break;
   1832                 }
   1833                 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
   1834                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1835                     if (nai == null) {
   1836                         loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
   1837                     } else {
   1838                         if (VDBG) {
   1839                             log("Update of LinkProperties for " + nai.name() +
   1840                                     "; created=" + nai.created);
   1841                         }
   1842                         LinkProperties oldLp = nai.linkProperties;
   1843                         synchronized (nai) {
   1844                             nai.linkProperties = (LinkProperties)msg.obj;
   1845                         }
   1846                         if (nai.created) updateLinkProperties(nai, oldLp);
   1847                     }
   1848                     break;
   1849                 }
   1850                 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
   1851                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1852                     if (nai == null) {
   1853                         loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
   1854                         break;
   1855                     }
   1856                     info = (NetworkInfo) msg.obj;
   1857                     updateNetworkInfo(nai, info);
   1858                     break;
   1859                 }
   1860                 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
   1861                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1862                     if (nai == null) {
   1863                         loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
   1864                         break;
   1865                     }
   1866                     Integer score = (Integer) msg.obj;
   1867                     if (score != null) updateNetworkScore(nai, score.intValue());
   1868                     break;
   1869                 }
   1870                 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
   1871                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1872                     if (nai == null) {
   1873                         loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
   1874                         break;
   1875                     }
   1876                     try {
   1877                         mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
   1878                     } catch (Exception e) {
   1879                         // Never crash!
   1880                         loge("Exception in addVpnUidRanges: " + e);
   1881                     }
   1882                     break;
   1883                 }
   1884                 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
   1885                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1886                     if (nai == null) {
   1887                         loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
   1888                         break;
   1889                     }
   1890                     try {
   1891                         mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
   1892                     } catch (Exception e) {
   1893                         // Never crash!
   1894                         loge("Exception in removeVpnUidRanges: " + e);
   1895                     }
   1896                     break;
   1897                 }
   1898                 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
   1899                     NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   1900                     if (nai == null) {
   1901                         loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
   1902                         break;
   1903                     }
   1904                     if (nai.created && !nai.networkMisc.explicitlySelected) {
   1905                         loge("ERROR: created network explicitly selected.");
   1906                     }
   1907                     nai.networkMisc.explicitlySelected = true;
   1908                     break;
   1909                 }
   1910                 case NetworkMonitor.EVENT_NETWORK_TESTED: {
   1911                     NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
   1912                     if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
   1913                         boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
   1914                         if (valid) {
   1915                             if (DBG) log("Validated " + nai.name());
   1916                             final boolean previouslyValidated = nai.validated;
   1917                             final int previousScore = nai.getCurrentScore();
   1918                             nai.validated = true;
   1919                             rematchNetworkAndRequests(nai, !previouslyValidated);
   1920                             // If score has changed, rebroadcast to NetworkFactories. b/17726566
   1921                             if (nai.getCurrentScore() != previousScore) {
   1922                                 sendUpdatedScoreToFactories(nai);
   1923                             }
   1924                         }
   1925                         updateInetCondition(nai, valid);
   1926                         // Let the NetworkAgent know the state of its network
   1927                         nai.asyncChannel.sendMessage(
   1928                                 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
   1929                                 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
   1930                                 0, null);
   1931                     }
   1932                     break;
   1933                 }
   1934                 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
   1935                     NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
   1936                     if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
   1937                         handleLingerComplete(nai);
   1938                     }
   1939                     break;
   1940                 }
   1941                 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
   1942                     if (msg.arg1 == 0) {
   1943                         setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
   1944                     } else {
   1945                         NetworkAgentInfo nai = null;
   1946                         synchronized (mNetworkForNetId) {
   1947                             nai = mNetworkForNetId.get(msg.arg2);
   1948                         }
   1949                         if (nai == null) {
   1950                             loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
   1951                             break;
   1952                         }
   1953                         setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
   1954                                 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
   1955                     }
   1956                     break;
   1957                 }
   1958                 case NetworkStateTracker.EVENT_STATE_CHANGED: {
   1959                     info = (NetworkInfo) msg.obj;
   1960                     NetworkInfo.State state = info.getState();
   1961 
   1962                     if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
   1963                             (state == NetworkInfo.State.DISCONNECTED) ||
   1964                             (state == NetworkInfo.State.SUSPENDED)) {
   1965                         log("ConnectivityChange for " +
   1966                             info.getTypeName() + ": " +
   1967                             state + "/" + info.getDetailedState());
   1968                     }
   1969 
   1970                     EventLogTags.writeConnectivityStateChanged(
   1971                             info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
   1972 
   1973                     if (info.isConnectedToProvisioningNetwork()) {
   1974                         /**
   1975                          * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
   1976                          * for now its an in between network, its a network that
   1977                          * is actually a default network but we don't want it to be
   1978                          * announced as such to keep background applications from
   1979                          * trying to use it. It turns out that some still try so we
   1980                          * take the additional step of clearing any default routes
   1981                          * to the link that may have incorrectly setup by the lower
   1982                          * levels.
   1983                          */
   1984                         LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
   1985                         if (DBG) {
   1986                             log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
   1987                         }
   1988 
   1989                         // Clear any default routes setup by the radio so
   1990                         // any activity by applications trying to use this
   1991                         // connection will fail until the provisioning network
   1992                         // is enabled.
   1993                         /*
   1994                         for (RouteInfo r : lp.getRoutes()) {
   1995                             removeRoute(lp, r, TO_DEFAULT_TABLE,
   1996                                         mNetTrackers[info.getType()].getNetwork().netId);
   1997                         }
   1998                         */
   1999                     } else if (state == NetworkInfo.State.DISCONNECTED) {
   2000                     } else if (state == NetworkInfo.State.SUSPENDED) {
   2001                     } else if (state == NetworkInfo.State.CONNECTED) {
   2002                     //    handleConnect(info);
   2003                     }
   2004                     notifyLockdownVpn(null);
   2005                     break;
   2006                 }
   2007                 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
   2008                     info = (NetworkInfo) msg.obj;
   2009                     // TODO: Temporary allowing network configuration
   2010                     //       change not resetting sockets.
   2011                     //       @see bug/4455071
   2012                     /*
   2013                     handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
   2014                             false);
   2015                     */
   2016                     break;
   2017                 }
   2018             }
   2019         }
   2020     }
   2021 
   2022     private void handleAsyncChannelHalfConnect(Message msg) {
   2023         AsyncChannel ac = (AsyncChannel) msg.obj;
   2024         if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
   2025             if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
   2026                 if (VDBG) log("NetworkFactory connected");
   2027                 // A network factory has connected.  Send it all current NetworkRequests.
   2028                 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
   2029                     if (nri.isRequest == false) continue;
   2030                     NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
   2031                     ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
   2032                             (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
   2033                 }
   2034             } else {
   2035                 loge("Error connecting NetworkFactory");
   2036                 mNetworkFactoryInfos.remove(msg.obj);
   2037             }
   2038         } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
   2039             if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
   2040                 if (VDBG) log("NetworkAgent connected");
   2041                 // A network agent has requested a connection.  Establish the connection.
   2042                 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
   2043                         sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
   2044             } else {
   2045                 loge("Error connecting NetworkAgent");
   2046                 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
   2047                 if (nai != null) {
   2048                     synchronized (mNetworkForNetId) {
   2049                         mNetworkForNetId.remove(nai.network.netId);
   2050                     }
   2051                     // Just in case.
   2052                     mLegacyTypeTracker.remove(nai);
   2053                 }
   2054             }
   2055         }
   2056     }
   2057     private void handleAsyncChannelDisconnected(Message msg) {
   2058         NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
   2059         if (nai != null) {
   2060             if (DBG) {
   2061                 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
   2062             }
   2063             // A network agent has disconnected.
   2064             if (nai.created) {
   2065                 // Tell netd to clean up the configuration for this network
   2066                 // (routing rules, DNS, etc).
   2067                 try {
   2068                     mNetd.removeNetwork(nai.network.netId);
   2069                 } catch (Exception e) {
   2070                     loge("Exception removing network: " + e);
   2071                 }
   2072             }
   2073             // TODO - if we move the logic to the network agent (have them disconnect
   2074             // because they lost all their requests or because their score isn't good)
   2075             // then they would disconnect organically, report their new state and then
   2076             // disconnect the channel.
   2077             if (nai.networkInfo.isConnected()) {
   2078                 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
   2079                         null, null);
   2080             }
   2081             if (isDefaultNetwork(nai)) {
   2082                 mDefaultInetConditionPublished = 0;
   2083             }
   2084             notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
   2085             nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
   2086             mNetworkAgentInfos.remove(msg.replyTo);
   2087             updateClat(null, nai.linkProperties, nai);
   2088             mLegacyTypeTracker.remove(nai);
   2089             synchronized (mNetworkForNetId) {
   2090                 mNetworkForNetId.remove(nai.network.netId);
   2091             }
   2092             // Since we've lost the network, go through all the requests that
   2093             // it was satisfying and see if any other factory can satisfy them.
   2094             // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
   2095             final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
   2096             for (int i = 0; i < nai.networkRequests.size(); i++) {
   2097                 NetworkRequest request = nai.networkRequests.valueAt(i);
   2098                 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
   2099                 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
   2100                     if (DBG) {
   2101                         log("Checking for replacement network to handle request " + request );
   2102                     }
   2103                     mNetworkForRequestId.remove(request.requestId);
   2104                     sendUpdatedScoreToFactories(request, 0);
   2105                     NetworkAgentInfo alternative = null;
   2106                     for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
   2107                         NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
   2108                         if (existing.networkInfo.isConnected() &&
   2109                                 request.networkCapabilities.satisfiedByNetworkCapabilities(
   2110                                 existing.networkCapabilities) &&
   2111                                 (alternative == null ||
   2112                                  alternative.getCurrentScore() < existing.getCurrentScore())) {
   2113                             alternative = existing;
   2114                         }
   2115                     }
   2116                     if (alternative != null) {
   2117                         if (DBG) log(" found replacement in " + alternative.name());
   2118                         if (!toActivate.contains(alternative)) {
   2119                             toActivate.add(alternative);
   2120                         }
   2121                     }
   2122                 }
   2123             }
   2124             if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
   2125                 removeDataActivityTracking(nai);
   2126                 mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
   2127                 notifyLockdownVpn(nai);
   2128                 requestNetworkTransitionWakelock(nai.name());
   2129             }
   2130             for (NetworkAgentInfo networkToActivate : toActivate) {
   2131                 networkToActivate.networkLingered.clear();
   2132                 networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
   2133                 rematchNetworkAndRequests(networkToActivate, false);
   2134             }
   2135         }
   2136     }
   2137 
   2138     private void handleRegisterNetworkRequest(Message msg) {
   2139         final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
   2140         final NetworkCapabilities newCap = nri.request.networkCapabilities;
   2141         int score = 0;
   2142 
   2143         // Check for the best currently alive network that satisfies this request
   2144         NetworkAgentInfo bestNetwork = null;
   2145         for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
   2146             if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
   2147             if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
   2148                 if (DBG) log("apparently satisfied.  currentScore=" + network.getCurrentScore());
   2149                 if ((bestNetwork == null) ||
   2150                         bestNetwork.getCurrentScore() < network.getCurrentScore()) {
   2151                     if (!nri.isRequest) {
   2152                         // Not setting bestNetwork here as a listening NetworkRequest may be
   2153                         // satisfied by multiple Networks.  Instead the request is added to
   2154                         // each satisfying Network and notified about each.
   2155                         network.addRequest(nri.request);
   2156                         notifyNetworkCallback(network, nri);
   2157                     } else {
   2158                         bestNetwork = network;
   2159                     }
   2160                 }
   2161             }
   2162         }
   2163         if (bestNetwork != null) {
   2164             if (DBG) log("using " + bestNetwork.name());
   2165             if (bestNetwork.networkInfo.isConnected()) {
   2166                 // Cancel any lingering so the linger timeout doesn't teardown this network
   2167                 // even though we have a request for it.
   2168                 bestNetwork.networkLingered.clear();
   2169                 bestNetwork.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
   2170             }
   2171             // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
   2172             bestNetwork.addRequest(nri.request);
   2173             mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
   2174             notifyNetworkCallback(bestNetwork, nri);
   2175             score = bestNetwork.getCurrentScore();
   2176             if (nri.request.legacyType != TYPE_NONE) {
   2177                 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
   2178             }
   2179         }
   2180         mNetworkRequests.put(nri.request, nri);
   2181         if (nri.isRequest) {
   2182             if (DBG) log("sending new NetworkRequest to factories");
   2183             for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
   2184                 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
   2185                         0, nri.request);
   2186             }
   2187         }
   2188     }
   2189 
   2190     private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
   2191         NetworkRequestInfo nri = mNetworkRequests.get(request);
   2192         if (nri != null) {
   2193             if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
   2194                 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
   2195                 return;
   2196             }
   2197             if (DBG) log("releasing NetworkRequest " + request);
   2198             nri.unlinkDeathRecipient();
   2199             mNetworkRequests.remove(request);
   2200             if (nri.isRequest) {
   2201                 // Find all networks that are satisfying this request and remove the request
   2202                 // from their request lists.
   2203                 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
   2204                     if (nai.networkRequests.get(nri.request.requestId) != null) {
   2205                         nai.networkRequests.remove(nri.request.requestId);
   2206                         if (DBG) {
   2207                             log(" Removing from current network " + nai.name() +
   2208                                     ", leaving " + nai.networkRequests.size() +
   2209                                     " requests.");
   2210                         }
   2211                         // check if has any requests remaining and if not,
   2212                         // disconnect (unless it's a VPN).
   2213                         boolean keep = nai.isVPN();
   2214                         for (int i = 0; i < nai.networkRequests.size() && !keep; i++) {
   2215                             NetworkRequest r = nai.networkRequests.valueAt(i);
   2216                             if (isRequest(r)) keep = true;
   2217                         }
   2218                         if (!keep) {
   2219                             if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
   2220                             nai.asyncChannel.disconnect();
   2221                         }
   2222                     }
   2223                 }
   2224 
   2225                 // Maintain the illusion.  When this request arrived, we might have preteneded
   2226                 // that a network connected to serve it, even though the network was already
   2227                 // connected.  Now that this request has gone away, we might have to pretend
   2228                 // that the network disconnected.  LegacyTypeTracker will generate that
   2229                 // phatom disconnect for this type.
   2230                 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
   2231                 if (nai != null) {
   2232                     mNetworkForRequestId.remove(nri.request.requestId);
   2233                     if (nri.request.legacyType != TYPE_NONE) {
   2234                         mLegacyTypeTracker.remove(nri.request.legacyType, nai);
   2235                     }
   2236                 }
   2237 
   2238                 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
   2239                     nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
   2240                             nri.request);
   2241                 }
   2242             } else {
   2243                 // listens don't have a singular affectedNetwork.  Check all networks to see
   2244                 // if this listen request applies and remove it.
   2245                 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
   2246                     nai.networkRequests.remove(nri.request.requestId);
   2247                 }
   2248             }
   2249             callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
   2250         }
   2251     }
   2252 
   2253     private class InternalHandler extends Handler {
   2254         public InternalHandler(Looper looper) {
   2255             super(looper);
   2256         }
   2257 
   2258         @Override
   2259         public void handleMessage(Message msg) {
   2260             NetworkInfo info;
   2261             switch (msg.what) {
   2262                 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
   2263                 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
   2264                     String causedBy = null;
   2265                     synchronized (ConnectivityService.this) {
   2266                         if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
   2267                                 mNetTransitionWakeLock.isHeld()) {
   2268                             mNetTransitionWakeLock.release();
   2269                             causedBy = mNetTransitionWakeLockCausedBy;
   2270                         } else {
   2271                             break;
   2272                         }
   2273                     }
   2274                     if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
   2275                         log("Failed to find a new network - expiring NetTransition Wakelock");
   2276                     } else {
   2277                         log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
   2278                                 " cleared because we found a replacement network");
   2279                     }
   2280                     break;
   2281                 }
   2282                 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
   2283                     handleDeprecatedGlobalHttpProxy();
   2284                     break;
   2285                 }
   2286                 case EVENT_SET_DEPENDENCY_MET: {
   2287                     boolean met = (msg.arg1 == ENABLED);
   2288                     handleSetDependencyMet(msg.arg2, met);
   2289                     break;
   2290                 }
   2291                 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
   2292                     Intent intent = (Intent)msg.obj;
   2293                     sendStickyBroadcast(intent);
   2294                     break;
   2295                 }
   2296                 case EVENT_SET_POLICY_DATA_ENABLE: {
   2297                     final int networkType = msg.arg1;
   2298                     final boolean enabled = msg.arg2 == ENABLED;
   2299                     handleSetPolicyDataEnable(networkType, enabled);
   2300                     break;
   2301                 }
   2302                 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
   2303                     int tag = mEnableFailFastMobileDataTag.get();
   2304                     if (msg.arg1 == tag) {
   2305                         MobileDataStateTracker mobileDst =
   2306                             (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
   2307                         if (mobileDst != null) {
   2308                             mobileDst.setEnableFailFastMobileData(msg.arg2);
   2309                         }
   2310                     } else {
   2311                         log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
   2312                                 + " != tag:" + tag);
   2313                     }
   2314                     break;
   2315                 }
   2316                 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
   2317                     handleNetworkSamplingTimeout();
   2318                     break;
   2319                 }
   2320                 case EVENT_PROXY_HAS_CHANGED: {
   2321                     handleApplyDefaultProxy((ProxyInfo)msg.obj);
   2322                     break;
   2323                 }
   2324                 case EVENT_REGISTER_NETWORK_FACTORY: {
   2325                     handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
   2326                     break;
   2327                 }
   2328                 case EVENT_UNREGISTER_NETWORK_FACTORY: {
   2329                     handleUnregisterNetworkFactory((Messenger)msg.obj);
   2330                     break;
   2331                 }
   2332                 case EVENT_REGISTER_NETWORK_AGENT: {
   2333                     handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
   2334                     break;
   2335                 }
   2336                 case EVENT_REGISTER_NETWORK_REQUEST:
   2337                 case EVENT_REGISTER_NETWORK_LISTENER: {
   2338                     handleRegisterNetworkRequest(msg);
   2339                     break;
   2340                 }
   2341                 case EVENT_RELEASE_NETWORK_REQUEST: {
   2342                     handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
   2343                     break;
   2344                 }
   2345                 case EVENT_SYSTEM_READY: {
   2346                     for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
   2347                         nai.networkMonitor.systemReady = true;
   2348                     }
   2349                     break;
   2350                 }
   2351             }
   2352         }
   2353     }
   2354 
   2355     // javadoc from interface
   2356     public int tether(String iface) {
   2357         ConnectivityManager.enforceTetherChangePermission(mContext);
   2358         if (isTetheringSupported()) {
   2359             return mTethering.tether(iface);
   2360         } else {
   2361             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
   2362         }
   2363     }
   2364 
   2365     // javadoc from interface
   2366     public int untether(String iface) {
   2367         ConnectivityManager.enforceTetherChangePermission(mContext);
   2368 
   2369         if (isTetheringSupported()) {
   2370             return mTethering.untether(iface);
   2371         } else {
   2372             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
   2373         }
   2374     }
   2375 
   2376     // javadoc from interface
   2377     public int getLastTetherError(String iface) {
   2378         enforceTetherAccessPermission();
   2379 
   2380         if (isTetheringSupported()) {
   2381             return mTethering.getLastTetherError(iface);
   2382         } else {
   2383             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
   2384         }
   2385     }
   2386 
   2387     // TODO - proper iface API for selection by property, inspection, etc
   2388     public String[] getTetherableUsbRegexs() {
   2389         enforceTetherAccessPermission();
   2390         if (isTetheringSupported()) {
   2391             return mTethering.getTetherableUsbRegexs();
   2392         } else {
   2393             return new String[0];
   2394         }
   2395     }
   2396 
   2397     public String[] getTetherableWifiRegexs() {
   2398         enforceTetherAccessPermission();
   2399         if (isTetheringSupported()) {
   2400             return mTethering.getTetherableWifiRegexs();
   2401         } else {
   2402             return new String[0];
   2403         }
   2404     }
   2405 
   2406     public String[] getTetherableBluetoothRegexs() {
   2407         enforceTetherAccessPermission();
   2408         if (isTetheringSupported()) {
   2409             return mTethering.getTetherableBluetoothRegexs();
   2410         } else {
   2411             return new String[0];
   2412         }
   2413     }
   2414 
   2415     public int setUsbTethering(boolean enable) {
   2416         ConnectivityManager.enforceTetherChangePermission(mContext);
   2417         if (isTetheringSupported()) {
   2418             return mTethering.setUsbTethering(enable);
   2419         } else {
   2420             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
   2421         }
   2422     }
   2423 
   2424     // TODO - move iface listing, queries, etc to new module
   2425     // javadoc from interface
   2426     public String[] getTetherableIfaces() {
   2427         enforceTetherAccessPermission();
   2428         return mTethering.getTetherableIfaces();
   2429     }
   2430 
   2431     public String[] getTetheredIfaces() {
   2432         enforceTetherAccessPermission();
   2433         return mTethering.getTetheredIfaces();
   2434     }
   2435 
   2436     public String[] getTetheringErroredIfaces() {
   2437         enforceTetherAccessPermission();
   2438         return mTethering.getErroredIfaces();
   2439     }
   2440 
   2441     public String[] getTetheredDhcpRanges() {
   2442         enforceConnectivityInternalPermission();
   2443         return mTethering.getTetheredDhcpRanges();
   2444     }
   2445 
   2446     // if ro.tether.denied = true we default to no tethering
   2447     // gservices could set the secure setting to 1 though to enable it on a build where it
   2448     // had previously been turned off.
   2449     public boolean isTetheringSupported() {
   2450         enforceTetherAccessPermission();
   2451         int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
   2452         boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
   2453                 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
   2454                 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
   2455         return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
   2456                 mTethering.getTetherableWifiRegexs().length != 0 ||
   2457                 mTethering.getTetherableBluetoothRegexs().length != 0) &&
   2458                 mTethering.getUpstreamIfaceTypes().length != 0);
   2459     }
   2460 
   2461     // Called when we lose the default network and have no replacement yet.
   2462     // This will automatically be cleared after X seconds or a new default network
   2463     // becomes CONNECTED, whichever happens first.  The timer is started by the
   2464     // first caller and not restarted by subsequent callers.
   2465     private void requestNetworkTransitionWakelock(String forWhom) {
   2466         int serialNum = 0;
   2467         synchronized (this) {
   2468             if (mNetTransitionWakeLock.isHeld()) return;
   2469             serialNum = ++mNetTransitionWakeLockSerialNumber;
   2470             mNetTransitionWakeLock.acquire();
   2471             mNetTransitionWakeLockCausedBy = forWhom;
   2472         }
   2473         mHandler.sendMessageDelayed(mHandler.obtainMessage(
   2474                 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
   2475                 mNetTransitionWakeLockTimeout);
   2476         return;
   2477     }
   2478 
   2479     // 100 percent is full good, 0 is full bad.
   2480     public void reportInetCondition(int networkType, int percentage) {
   2481         if (percentage > 50) return;  // don't handle good network reports
   2482         NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
   2483         if (nai != null) reportBadNetwork(nai.network);
   2484     }
   2485 
   2486     public void reportBadNetwork(Network network) {
   2487         enforceAccessPermission();
   2488         enforceInternetPermission();
   2489 
   2490         if (network == null) return;
   2491 
   2492         final int uid = Binder.getCallingUid();
   2493         NetworkAgentInfo nai = null;
   2494         synchronized (mNetworkForNetId) {
   2495             nai = mNetworkForNetId.get(network.netId);
   2496         }
   2497         if (nai == null) return;
   2498         if (DBG) log("reportBadNetwork(" + nai.name() + ") by " + uid);
   2499         synchronized (nai) {
   2500             // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
   2501             // which isn't meant to work on uncreated networks.
   2502             if (!nai.created) return;
   2503 
   2504             if (isNetworkBlocked(nai, uid)) return;
   2505 
   2506             nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
   2507         }
   2508     }
   2509 
   2510     public ProxyInfo getProxy() {
   2511         // this information is already available as a world read/writable jvm property
   2512         // so this API change wouldn't have a benifit.  It also breaks the passing
   2513         // of proxy info to all the JVMs.
   2514         // enforceAccessPermission();
   2515         synchronized (mProxyLock) {
   2516             ProxyInfo ret = mGlobalProxy;
   2517             if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
   2518             return ret;
   2519         }
   2520     }
   2521 
   2522     public void setGlobalProxy(ProxyInfo proxyProperties) {
   2523         enforceConnectivityInternalPermission();
   2524 
   2525         synchronized (mProxyLock) {
   2526             if (proxyProperties == mGlobalProxy) return;
   2527             if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
   2528             if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
   2529 
   2530             String host = "";
   2531             int port = 0;
   2532             String exclList = "";
   2533             String pacFileUrl = "";
   2534             if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
   2535                     (proxyProperties.getPacFileUrl() != null))) {
   2536                 if (!proxyProperties.isValid()) {
   2537                     if (DBG)
   2538                         log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
   2539                     return;
   2540                 }
   2541                 mGlobalProxy = new ProxyInfo(proxyProperties);
   2542                 host = mGlobalProxy.getHost();
   2543                 port = mGlobalProxy.getPort();
   2544                 exclList = mGlobalProxy.getExclusionListAsString();
   2545                 if (proxyProperties.getPacFileUrl() != null) {
   2546                     pacFileUrl = proxyProperties.getPacFileUrl().toString();
   2547                 }
   2548             } else {
   2549                 mGlobalProxy = null;
   2550             }
   2551             ContentResolver res = mContext.getContentResolver();
   2552             final long token = Binder.clearCallingIdentity();
   2553             try {
   2554                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
   2555                 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
   2556                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
   2557                         exclList);
   2558                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
   2559             } finally {
   2560                 Binder.restoreCallingIdentity(token);
   2561             }
   2562 
   2563             if (mGlobalProxy == null) {
   2564                 proxyProperties = mDefaultProxy;
   2565             }
   2566             sendProxyBroadcast(proxyProperties);
   2567         }
   2568     }
   2569 
   2570     private void loadGlobalProxy() {
   2571         ContentResolver res = mContext.getContentResolver();
   2572         String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
   2573         int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
   2574         String exclList = Settings.Global.getString(res,
   2575                 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
   2576         String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
   2577         if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
   2578             ProxyInfo proxyProperties;
   2579             if (!TextUtils.isEmpty(pacFileUrl)) {
   2580                 proxyProperties = new ProxyInfo(pacFileUrl);
   2581             } else {
   2582                 proxyProperties = new ProxyInfo(host, port, exclList);
   2583             }
   2584             if (!proxyProperties.isValid()) {
   2585                 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
   2586                 return;
   2587             }
   2588 
   2589             synchronized (mProxyLock) {
   2590                 mGlobalProxy = proxyProperties;
   2591             }
   2592         }
   2593     }
   2594 
   2595     public ProxyInfo getGlobalProxy() {
   2596         // this information is already available as a world read/writable jvm property
   2597         // so this API change wouldn't have a benifit.  It also breaks the passing
   2598         // of proxy info to all the JVMs.
   2599         // enforceAccessPermission();
   2600         synchronized (mProxyLock) {
   2601             return mGlobalProxy;
   2602         }
   2603     }
   2604 
   2605     private void handleApplyDefaultProxy(ProxyInfo proxy) {
   2606         if (proxy != null && TextUtils.isEmpty(proxy.getHost())
   2607                 && (proxy.getPacFileUrl() == null)) {
   2608             proxy = null;
   2609         }
   2610         synchronized (mProxyLock) {
   2611             if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
   2612             if (mDefaultProxy == proxy) return; // catches repeated nulls
   2613             if (proxy != null &&  !proxy.isValid()) {
   2614                 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
   2615                 return;
   2616             }
   2617 
   2618             // This call could be coming from the PacManager, containing the port of the local
   2619             // proxy.  If this new proxy matches the global proxy then copy this proxy to the
   2620             // global (to get the correct local port), and send a broadcast.
   2621             // TODO: Switch PacManager to have its own message to send back rather than
   2622             // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
   2623             if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
   2624                     && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
   2625                 mGlobalProxy = proxy;
   2626                 sendProxyBroadcast(mGlobalProxy);
   2627                 return;
   2628             }
   2629             mDefaultProxy = proxy;
   2630 
   2631             if (mGlobalProxy != null) return;
   2632             if (!mDefaultProxyDisabled) {
   2633                 sendProxyBroadcast(proxy);
   2634             }
   2635         }
   2636     }
   2637 
   2638     private void handleDeprecatedGlobalHttpProxy() {
   2639         String proxy = Settings.Global.getString(mContext.getContentResolver(),
   2640                 Settings.Global.HTTP_PROXY);
   2641         if (!TextUtils.isEmpty(proxy)) {
   2642             String data[] = proxy.split(":");
   2643             if (data.length == 0) {
   2644                 return;
   2645             }
   2646 
   2647             String proxyHost =  data[0];
   2648             int proxyPort = 8080;
   2649             if (data.length > 1) {
   2650                 try {
   2651                     proxyPort = Integer.parseInt(data[1]);
   2652                 } catch (NumberFormatException e) {
   2653                     return;
   2654                 }
   2655             }
   2656             ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
   2657             setGlobalProxy(p);
   2658         }
   2659     }
   2660 
   2661     private void sendProxyBroadcast(ProxyInfo proxy) {
   2662         if (proxy == null) proxy = new ProxyInfo("", 0, "");
   2663         if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
   2664         if (DBG) log("sending Proxy Broadcast for " + proxy);
   2665         Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
   2666         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
   2667             Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
   2668         intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
   2669         final long ident = Binder.clearCallingIdentity();
   2670         try {
   2671             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   2672         } finally {
   2673             Binder.restoreCallingIdentity(ident);
   2674         }
   2675     }
   2676 
   2677     private static class SettingsObserver extends ContentObserver {
   2678         private int mWhat;
   2679         private Handler mHandler;
   2680         SettingsObserver(Handler handler, int what) {
   2681             super(handler);
   2682             mHandler = handler;
   2683             mWhat = what;
   2684         }
   2685 
   2686         void observe(Context context) {
   2687             ContentResolver resolver = context.getContentResolver();
   2688             resolver.registerContentObserver(Settings.Global.getUriFor(
   2689                     Settings.Global.HTTP_PROXY), false, this);
   2690         }
   2691 
   2692         @Override
   2693         public void onChange(boolean selfChange) {
   2694             mHandler.obtainMessage(mWhat).sendToTarget();
   2695         }
   2696     }
   2697 
   2698     private static void log(String s) {
   2699         Slog.d(TAG, s);
   2700     }
   2701 
   2702     private static void loge(String s) {
   2703         Slog.e(TAG, s);
   2704     }
   2705 
   2706     int convertFeatureToNetworkType(int networkType, String feature) {
   2707         int usedNetworkType = networkType;
   2708 
   2709         if(networkType == ConnectivityManager.TYPE_MOBILE) {
   2710             if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
   2711                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
   2712             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
   2713                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
   2714             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
   2715                     TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
   2716                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
   2717             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
   2718                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
   2719             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
   2720                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
   2721             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
   2722                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
   2723             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
   2724                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
   2725             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) {
   2726                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY;
   2727             } else {
   2728                 Slog.e(TAG, "Can't match any mobile netTracker!");
   2729             }
   2730         } else if (networkType == ConnectivityManager.TYPE_WIFI) {
   2731             if (TextUtils.equals(feature, "p2p")) {
   2732                 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
   2733             } else {
   2734                 Slog.e(TAG, "Can't match any wifi netTracker!");
   2735             }
   2736         } else {
   2737             Slog.e(TAG, "Unexpected network type");
   2738         }
   2739         return usedNetworkType;
   2740     }
   2741 
   2742     private static <T> T checkNotNull(T value, String message) {
   2743         if (value == null) {
   2744             throw new NullPointerException(message);
   2745         }
   2746         return value;
   2747     }
   2748 
   2749     /**
   2750      * Prepare for a VPN application. This method is used by VpnDialogs
   2751      * and not available in ConnectivityManager. Permissions are checked
   2752      * in Vpn class.
   2753      * @hide
   2754      */
   2755     @Override
   2756     public boolean prepareVpn(String oldPackage, String newPackage) {
   2757         throwIfLockdownEnabled();
   2758         int user = UserHandle.getUserId(Binder.getCallingUid());
   2759         synchronized(mVpns) {
   2760             return mVpns.get(user).prepare(oldPackage, newPackage);
   2761         }
   2762     }
   2763 
   2764     /**
   2765      * Set whether the current VPN package has the ability to launch VPNs without
   2766      * user intervention. This method is used by system UIs and not available
   2767      * in ConnectivityManager. Permissions are checked in Vpn class.
   2768      * @hide
   2769      */
   2770     @Override
   2771     public void setVpnPackageAuthorization(boolean authorized) {
   2772         int user = UserHandle.getUserId(Binder.getCallingUid());
   2773         synchronized(mVpns) {
   2774             mVpns.get(user).setPackageAuthorization(authorized);
   2775         }
   2776     }
   2777 
   2778     /**
   2779      * Configure a TUN interface and return its file descriptor. Parameters
   2780      * are encoded and opaque to this class. This method is used by VpnBuilder
   2781      * and not available in ConnectivityManager. Permissions are checked in
   2782      * Vpn class.
   2783      * @hide
   2784      */
   2785     @Override
   2786     public ParcelFileDescriptor establishVpn(VpnConfig config) {
   2787         throwIfLockdownEnabled();
   2788         int user = UserHandle.getUserId(Binder.getCallingUid());
   2789         synchronized(mVpns) {
   2790             return mVpns.get(user).establish(config);
   2791         }
   2792     }
   2793 
   2794     /**
   2795      * Start legacy VPN, controlling native daemons as needed. Creates a
   2796      * secondary thread to perform connection work, returning quickly.
   2797      */
   2798     @Override
   2799     public void startLegacyVpn(VpnProfile profile) {
   2800         throwIfLockdownEnabled();
   2801         final LinkProperties egress = getActiveLinkProperties();
   2802         if (egress == null) {
   2803             throw new IllegalStateException("Missing active network connection");
   2804         }
   2805         int user = UserHandle.getUserId(Binder.getCallingUid());
   2806         synchronized(mVpns) {
   2807             mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
   2808         }
   2809     }
   2810 
   2811     /**
   2812      * Return the information of the ongoing legacy VPN. This method is used
   2813      * by VpnSettings and not available in ConnectivityManager. Permissions
   2814      * are checked in Vpn class.
   2815      * @hide
   2816      */
   2817     @Override
   2818     public LegacyVpnInfo getLegacyVpnInfo() {
   2819         throwIfLockdownEnabled();
   2820         int user = UserHandle.getUserId(Binder.getCallingUid());
   2821         synchronized(mVpns) {
   2822             return mVpns.get(user).getLegacyVpnInfo();
   2823         }
   2824     }
   2825 
   2826     /**
   2827      * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
   2828      * not available in ConnectivityManager.
   2829      * Permissions are checked in Vpn class.
   2830      * @hide
   2831      */
   2832     @Override
   2833     public VpnConfig getVpnConfig() {
   2834         int user = UserHandle.getUserId(Binder.getCallingUid());
   2835         synchronized(mVpns) {
   2836             return mVpns.get(user).getVpnConfig();
   2837         }
   2838     }
   2839 
   2840     @Override
   2841     public boolean updateLockdownVpn() {
   2842         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   2843             Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
   2844             return false;
   2845         }
   2846 
   2847         // Tear down existing lockdown if profile was removed
   2848         mLockdownEnabled = LockdownVpnTracker.isEnabled();
   2849         if (mLockdownEnabled) {
   2850             if (!mKeyStore.isUnlocked()) {
   2851                 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
   2852                 return false;
   2853             }
   2854 
   2855             final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
   2856             final VpnProfile profile = VpnProfile.decode(
   2857                     profileName, mKeyStore.get(Credentials.VPN + profileName));
   2858             int user = UserHandle.getUserId(Binder.getCallingUid());
   2859             synchronized(mVpns) {
   2860                 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
   2861                             profile));
   2862             }
   2863         } else {
   2864             setLockdownTracker(null);
   2865         }
   2866 
   2867         return true;
   2868     }
   2869 
   2870     /**
   2871      * Internally set new {@link LockdownVpnTracker}, shutting down any existing
   2872      * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
   2873      */
   2874     private void setLockdownTracker(LockdownVpnTracker tracker) {
   2875         // Shutdown any existing tracker
   2876         final LockdownVpnTracker existing = mLockdownTracker;
   2877         mLockdownTracker = null;
   2878         if (existing != null) {
   2879             existing.shutdown();
   2880         }
   2881 
   2882         try {
   2883             if (tracker != null) {
   2884                 mNetd.setFirewallEnabled(true);
   2885                 mNetd.setFirewallInterfaceRule("lo", true);
   2886                 mLockdownTracker = tracker;
   2887                 mLockdownTracker.init();
   2888             } else {
   2889                 mNetd.setFirewallEnabled(false);
   2890             }
   2891         } catch (RemoteException e) {
   2892             // ignored; NMS lives inside system_server
   2893         }
   2894     }
   2895 
   2896     private void throwIfLockdownEnabled() {
   2897         if (mLockdownEnabled) {
   2898             throw new IllegalStateException("Unavailable in lockdown mode");
   2899         }
   2900     }
   2901 
   2902     public void supplyMessenger(int networkType, Messenger messenger) {
   2903         enforceConnectivityInternalPermission();
   2904 
   2905         if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
   2906             mNetTrackers[networkType].supplyMessenger(messenger);
   2907         }
   2908     }
   2909 
   2910     public int findConnectionTypeForIface(String iface) {
   2911         enforceConnectivityInternalPermission();
   2912 
   2913         if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
   2914 
   2915         synchronized(mNetworkForNetId) {
   2916             for (int i = 0; i < mNetworkForNetId.size(); i++) {
   2917                 NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
   2918                 LinkProperties lp = nai.linkProperties;
   2919                 if (lp != null && iface.equals(lp.getInterfaceName()) && nai.networkInfo != null) {
   2920                     return nai.networkInfo.getType();
   2921                 }
   2922             }
   2923         }
   2924         return ConnectivityManager.TYPE_NONE;
   2925     }
   2926 
   2927     /**
   2928      * Have mobile data fail fast if enabled.
   2929      *
   2930      * @param enabled DctConstants.ENABLED/DISABLED
   2931      */
   2932     private void setEnableFailFastMobileData(int enabled) {
   2933         int tag;
   2934 
   2935         if (enabled == DctConstants.ENABLED) {
   2936             tag = mEnableFailFastMobileDataTag.incrementAndGet();
   2937         } else {
   2938             tag = mEnableFailFastMobileDataTag.get();
   2939         }
   2940         mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
   2941                          enabled));
   2942     }
   2943 
   2944     @Override
   2945     public int checkMobileProvisioning(int suggestedTimeOutMs) {
   2946         // TODO: Remove?  Any reason to trigger a provisioning check?
   2947         return -1;
   2948     }
   2949 
   2950     private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
   2951     private volatile boolean mIsNotificationVisible = false;
   2952 
   2953     private void setProvNotificationVisible(boolean visible, int networkType, String action) {
   2954         if (DBG) {
   2955             log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
   2956                 + " action=" + action);
   2957         }
   2958         Intent intent = new Intent(action);
   2959         PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
   2960         // Concatenate the range of types onto the range of NetIDs.
   2961         int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
   2962         setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
   2963     }
   2964 
   2965     /**
   2966      * Show or hide network provisioning notificaitons.
   2967      *
   2968      * @param id an identifier that uniquely identifies this notification.  This must match
   2969      *         between show and hide calls.  We use the NetID value but for legacy callers
   2970      *         we concatenate the range of types with the range of NetIDs.
   2971      */
   2972     private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
   2973             String extraInfo, PendingIntent intent) {
   2974         if (DBG) {
   2975             log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
   2976                 networkType + " extraInfo=" + extraInfo);
   2977         }
   2978 
   2979         Resources r = Resources.getSystem();
   2980         NotificationManager notificationManager = (NotificationManager) mContext
   2981             .getSystemService(Context.NOTIFICATION_SERVICE);
   2982 
   2983         if (visible) {
   2984             CharSequence title;
   2985             CharSequence details;
   2986             int icon;
   2987             Notification notification = new Notification();
   2988             switch (networkType) {
   2989                 case ConnectivityManager.TYPE_WIFI:
   2990                     title = r.getString(R.string.wifi_available_sign_in, 0);
   2991                     details = r.getString(R.string.network_available_sign_in_detailed,
   2992                             extraInfo);
   2993                     icon = R.drawable.stat_notify_wifi_in_range;
   2994                     break;
   2995                 case ConnectivityManager.TYPE_MOBILE:
   2996                 case ConnectivityManager.TYPE_MOBILE_HIPRI:
   2997                     title = r.getString(R.string.network_available_sign_in, 0);
   2998                     // TODO: Change this to pull from NetworkInfo once a printable
   2999                     // name has been added to it
   3000                     details = mTelephonyManager.getNetworkOperatorName();
   3001                     icon = R.drawable.stat_notify_rssi_in_range;
   3002                     break;
   3003                 default:
   3004                     title = r.getString(R.string.network_available_sign_in, 0);
   3005                     details = r.getString(R.string.network_available_sign_in_detailed,
   3006                             extraInfo);
   3007                     icon = R.drawable.stat_notify_rssi_in_range;
   3008                     break;
   3009             }
   3010 
   3011             notification.when = 0;
   3012             notification.icon = icon;
   3013             notification.flags = Notification.FLAG_AUTO_CANCEL;
   3014             notification.tickerText = title;
   3015             notification.color = mContext.getResources().getColor(
   3016                     com.android.internal.R.color.system_notification_accent_color);
   3017             notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
   3018             notification.contentIntent = intent;
   3019 
   3020             try {
   3021                 notificationManager.notify(NOTIFICATION_ID, id, notification);
   3022             } catch (NullPointerException npe) {
   3023                 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
   3024                 npe.printStackTrace();
   3025             }
   3026         } else {
   3027             try {
   3028                 notificationManager.cancel(NOTIFICATION_ID, id);
   3029             } catch (NullPointerException npe) {
   3030                 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
   3031                 npe.printStackTrace();
   3032             }
   3033         }
   3034         mIsNotificationVisible = visible;
   3035     }
   3036 
   3037     /** Location to an updatable file listing carrier provisioning urls.
   3038      *  An example:
   3039      *
   3040      * <?xml version="1.0" encoding="utf-8"?>
   3041      *  <provisioningUrls>
   3042      *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
   3043      *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
   3044      *  </provisioningUrls>
   3045      */
   3046     private static final String PROVISIONING_URL_PATH =
   3047             "/data/misc/radio/provisioning_urls.xml";
   3048     private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
   3049 
   3050     /** XML tag for root element. */
   3051     private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
   3052     /** XML tag for individual url */
   3053     private static final String TAG_PROVISIONING_URL = "provisioningUrl";
   3054     /** XML tag for redirected url */
   3055     private static final String TAG_REDIRECTED_URL = "redirectedUrl";
   3056     /** XML attribute for mcc */
   3057     private static final String ATTR_MCC = "mcc";
   3058     /** XML attribute for mnc */
   3059     private static final String ATTR_MNC = "mnc";
   3060 
   3061     private static final int REDIRECTED_PROVISIONING = 1;
   3062     private static final int PROVISIONING = 2;
   3063 
   3064     private String getProvisioningUrlBaseFromFile(int type) {
   3065         FileReader fileReader = null;
   3066         XmlPullParser parser = null;
   3067         Configuration config = mContext.getResources().getConfiguration();
   3068         String tagType;
   3069 
   3070         switch (type) {
   3071             case PROVISIONING:
   3072                 tagType = TAG_PROVISIONING_URL;
   3073                 break;
   3074             case REDIRECTED_PROVISIONING:
   3075                 tagType = TAG_REDIRECTED_URL;
   3076                 break;
   3077             default:
   3078                 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
   3079                         type);
   3080         }
   3081 
   3082         try {
   3083             fileReader = new FileReader(mProvisioningUrlFile);
   3084             parser = Xml.newPullParser();
   3085             parser.setInput(fileReader);
   3086             XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
   3087 
   3088             while (true) {
   3089                 XmlUtils.nextElement(parser);
   3090 
   3091                 String element = parser.getName();
   3092                 if (element == null) break;
   3093 
   3094                 if (element.equals(tagType)) {
   3095                     String mcc = parser.getAttributeValue(null, ATTR_MCC);
   3096                     try {
   3097                         if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
   3098                             String mnc = parser.getAttributeValue(null, ATTR_MNC);
   3099                             if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
   3100                                 parser.next();
   3101                                 if (parser.getEventType() == XmlPullParser.TEXT) {
   3102                                     return parser.getText();
   3103                                 }
   3104                             }
   3105                         }
   3106                     } catch (NumberFormatException e) {
   3107                         loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
   3108                     }
   3109                 }
   3110             }
   3111             return null;
   3112         } catch (FileNotFoundException e) {
   3113             loge("Carrier Provisioning Urls file not found");
   3114         } catch (XmlPullParserException e) {
   3115             loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
   3116         } catch (IOException e) {
   3117             loge("I/O exception reading Carrier Provisioning Urls file: " + e);
   3118         } finally {
   3119             if (fileReader != null) {
   3120                 try {
   3121                     fileReader.close();
   3122                 } catch (IOException e) {}
   3123             }
   3124         }
   3125         return null;
   3126     }
   3127 
   3128     @Override
   3129     public String getMobileRedirectedProvisioningUrl() {
   3130         enforceConnectivityInternalPermission();
   3131         String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
   3132         if (TextUtils.isEmpty(url)) {
   3133             url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
   3134         }
   3135         return url;
   3136     }
   3137 
   3138     @Override
   3139     public String getMobileProvisioningUrl() {
   3140         enforceConnectivityInternalPermission();
   3141         String url = getProvisioningUrlBaseFromFile(PROVISIONING);
   3142         if (TextUtils.isEmpty(url)) {
   3143             url = mContext.getResources().getString(R.string.mobile_provisioning_url);
   3144             log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
   3145         } else {
   3146             log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
   3147         }
   3148         // populate the iccid, imei and phone number in the provisioning url.
   3149         if (!TextUtils.isEmpty(url)) {
   3150             String phoneNumber = mTelephonyManager.getLine1Number();
   3151             if (TextUtils.isEmpty(phoneNumber)) {
   3152                 phoneNumber = "0000000000";
   3153             }
   3154             url = String.format(url,
   3155                     mTelephonyManager.getSimSerialNumber() /* ICCID */,
   3156                     mTelephonyManager.getDeviceId() /* IMEI */,
   3157                     phoneNumber /* Phone numer */);
   3158         }
   3159 
   3160         return url;
   3161     }
   3162 
   3163     @Override
   3164     public void setProvisioningNotificationVisible(boolean visible, int networkType,
   3165             String action) {
   3166         enforceConnectivityInternalPermission();
   3167         final long ident = Binder.clearCallingIdentity();
   3168         try {
   3169             setProvNotificationVisible(visible, networkType, action);
   3170         } finally {
   3171             Binder.restoreCallingIdentity(ident);
   3172         }
   3173     }
   3174 
   3175     @Override
   3176     public void setAirplaneMode(boolean enable) {
   3177         enforceConnectivityInternalPermission();
   3178         final long ident = Binder.clearCallingIdentity();
   3179         try {
   3180             final ContentResolver cr = mContext.getContentResolver();
   3181             Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
   3182             Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
   3183             intent.putExtra("state", enable);
   3184             mContext.sendBroadcast(intent);
   3185         } finally {
   3186             Binder.restoreCallingIdentity(ident);
   3187         }
   3188     }
   3189 
   3190     private void onUserStart(int userId) {
   3191         synchronized(mVpns) {
   3192             Vpn userVpn = mVpns.get(userId);
   3193             if (userVpn != null) {
   3194                 loge("Starting user already has a VPN");
   3195                 return;
   3196             }
   3197             userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
   3198             mVpns.put(userId, userVpn);
   3199         }
   3200     }
   3201 
   3202     private void onUserStop(int userId) {
   3203         synchronized(mVpns) {
   3204             Vpn userVpn = mVpns.get(userId);
   3205             if (userVpn == null) {
   3206                 loge("Stopping user has no VPN");
   3207                 return;
   3208             }
   3209             mVpns.delete(userId);
   3210         }
   3211     }
   3212 
   3213     private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
   3214         @Override
   3215         public void onReceive(Context context, Intent intent) {
   3216             final String action = intent.getAction();
   3217             final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
   3218             if (userId == UserHandle.USER_NULL) return;
   3219 
   3220             if (Intent.ACTION_USER_STARTING.equals(action)) {
   3221                 onUserStart(userId);
   3222             } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
   3223                 onUserStop(userId);
   3224             }
   3225         }
   3226     };
   3227 
   3228     @Override
   3229     public LinkQualityInfo getLinkQualityInfo(int networkType) {
   3230         enforceAccessPermission();
   3231         if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
   3232             return mNetTrackers[networkType].getLinkQualityInfo();
   3233         } else {
   3234             return null;
   3235         }
   3236     }
   3237 
   3238     @Override
   3239     public LinkQualityInfo getActiveLinkQualityInfo() {
   3240         enforceAccessPermission();
   3241         if (isNetworkTypeValid(mActiveDefaultNetwork) &&
   3242                 mNetTrackers[mActiveDefaultNetwork] != null) {
   3243             return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
   3244         } else {
   3245             return null;
   3246         }
   3247     }
   3248 
   3249     @Override
   3250     public LinkQualityInfo[] getAllLinkQualityInfo() {
   3251         enforceAccessPermission();
   3252         final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
   3253         for (NetworkStateTracker tracker : mNetTrackers) {
   3254             if (tracker != null) {
   3255                 LinkQualityInfo li = tracker.getLinkQualityInfo();
   3256                 if (li != null) {
   3257                     result.add(li);
   3258                 }
   3259             }
   3260         }
   3261 
   3262         return result.toArray(new LinkQualityInfo[result.size()]);
   3263     }
   3264 
   3265     /* Infrastructure for network sampling */
   3266 
   3267     private void handleNetworkSamplingTimeout() {
   3268 
   3269         if (SAMPLE_DBG) log("Sampling interval elapsed, updating statistics ..");
   3270 
   3271         // initialize list of interfaces ..
   3272         Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
   3273                 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
   3274         for (NetworkStateTracker tracker : mNetTrackers) {
   3275             if (tracker != null) {
   3276                 String ifaceName = tracker.getNetworkInterfaceName();
   3277                 if (ifaceName != null) {
   3278                     mapIfaceToSample.put(ifaceName, null);
   3279                 }
   3280             }
   3281         }
   3282 
   3283         // Read samples for all interfaces
   3284         SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
   3285 
   3286         // process samples for all networks
   3287         for (NetworkStateTracker tracker : mNetTrackers) {
   3288             if (tracker != null) {
   3289                 String ifaceName = tracker.getNetworkInterfaceName();
   3290                 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
   3291                 if (ss != null) {
   3292                     // end the previous sampling cycle
   3293                     tracker.stopSampling(ss);
   3294                     // start a new sampling cycle ..
   3295                     tracker.startSampling(ss);
   3296                 }
   3297             }
   3298         }
   3299 
   3300         if (SAMPLE_DBG) log("Done.");
   3301 
   3302         int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
   3303                 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
   3304                 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
   3305 
   3306         if (SAMPLE_DBG) {
   3307             log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
   3308         }
   3309 
   3310         setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
   3311     }
   3312 
   3313     /**
   3314      * Sets a network sampling alarm.
   3315      */
   3316     void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
   3317         long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
   3318         int alarmType;
   3319         if (Resources.getSystem().getBoolean(
   3320                 R.bool.config_networkSamplingWakesDevice)) {
   3321             alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
   3322         } else {
   3323             alarmType = AlarmManager.ELAPSED_REALTIME;
   3324         }
   3325         mAlarmManager.set(alarmType, wakeupTime, intent);
   3326     }
   3327 
   3328     private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
   3329             new HashMap<Messenger, NetworkFactoryInfo>();
   3330     private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
   3331             new HashMap<NetworkRequest, NetworkRequestInfo>();
   3332 
   3333     private static class NetworkFactoryInfo {
   3334         public final String name;
   3335         public final Messenger messenger;
   3336         public final AsyncChannel asyncChannel;
   3337 
   3338         public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
   3339             this.name = name;
   3340             this.messenger = messenger;
   3341             this.asyncChannel = asyncChannel;
   3342         }
   3343     }
   3344 
   3345     /**
   3346      * Tracks info about the requester.
   3347      * Also used to notice when the calling process dies so we can self-expire
   3348      */
   3349     private class NetworkRequestInfo implements IBinder.DeathRecipient {
   3350         static final boolean REQUEST = true;
   3351         static final boolean LISTEN = false;
   3352 
   3353         final NetworkRequest request;
   3354         IBinder mBinder;
   3355         final int mPid;
   3356         final int mUid;
   3357         final Messenger messenger;
   3358         final boolean isRequest;
   3359 
   3360         NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
   3361             super();
   3362             messenger = m;
   3363             request = r;
   3364             mBinder = binder;
   3365             mPid = getCallingPid();
   3366             mUid = getCallingUid();
   3367             this.isRequest = isRequest;
   3368 
   3369             try {
   3370                 mBinder.linkToDeath(this, 0);
   3371             } catch (RemoteException e) {
   3372                 binderDied();
   3373             }
   3374         }
   3375 
   3376         void unlinkDeathRecipient() {
   3377             mBinder.unlinkToDeath(this, 0);
   3378         }
   3379 
   3380         public void binderDied() {
   3381             log("ConnectivityService NetworkRequestInfo binderDied(" +
   3382                     request + ", " + mBinder + ")");
   3383             releaseNetworkRequest(request);
   3384         }
   3385 
   3386         public String toString() {
   3387             return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
   3388                     mPid + " for " + request;
   3389         }
   3390     }
   3391 
   3392     @Override
   3393     public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
   3394             Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
   3395         if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
   3396                 == false) {
   3397             enforceConnectivityInternalPermission();
   3398         } else {
   3399             enforceChangePermission();
   3400         }
   3401 
   3402         networkCapabilities = new NetworkCapabilities(networkCapabilities);
   3403 
   3404         // if UID is restricted, don't allow them to bring up metered APNs
   3405         if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
   3406                 == false) {
   3407             final int uidRules;
   3408             final int uid = Binder.getCallingUid();
   3409             synchronized(mRulesLock) {
   3410                 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
   3411             }
   3412             if ((uidRules & RULE_REJECT_METERED) != 0) {
   3413                 // we could silently fail or we can filter the available nets to only give
   3414                 // them those they have access to.  Chose the more useful
   3415                 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
   3416             }
   3417         }
   3418 
   3419         if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
   3420             throw new IllegalArgumentException("Bad timeout specified");
   3421         }
   3422         NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
   3423                 nextNetworkRequestId());
   3424         if (DBG) log("requestNetwork for " + networkRequest);
   3425         NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
   3426                 NetworkRequestInfo.REQUEST);
   3427 
   3428         mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
   3429         if (timeoutMs > 0) {
   3430             mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
   3431                     nri), timeoutMs);
   3432         }
   3433         return networkRequest;
   3434     }
   3435 
   3436     @Override
   3437     public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
   3438             PendingIntent operation) {
   3439         // TODO
   3440         return null;
   3441     }
   3442 
   3443     @Override
   3444     public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
   3445             Messenger messenger, IBinder binder) {
   3446         enforceAccessPermission();
   3447 
   3448         NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
   3449                 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
   3450         if (DBG) log("listenForNetwork for " + networkRequest);
   3451         NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
   3452                 NetworkRequestInfo.LISTEN);
   3453 
   3454         mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
   3455         return networkRequest;
   3456     }
   3457 
   3458     @Override
   3459     public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
   3460             PendingIntent operation) {
   3461     }
   3462 
   3463     @Override
   3464     public void releaseNetworkRequest(NetworkRequest networkRequest) {
   3465         mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
   3466                 0, networkRequest));
   3467     }
   3468 
   3469     @Override
   3470     public void registerNetworkFactory(Messenger messenger, String name) {
   3471         enforceConnectivityInternalPermission();
   3472         NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
   3473         mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
   3474     }
   3475 
   3476     private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
   3477         if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
   3478         mNetworkFactoryInfos.put(nfi.messenger, nfi);
   3479         nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
   3480     }
   3481 
   3482     @Override
   3483     public void unregisterNetworkFactory(Messenger messenger) {
   3484         enforceConnectivityInternalPermission();
   3485         mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
   3486     }
   3487 
   3488     private void handleUnregisterNetworkFactory(Messenger messenger) {
   3489         NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
   3490         if (nfi == null) {
   3491             loge("Failed to find Messenger in unregisterNetworkFactory");
   3492             return;
   3493         }
   3494         if (DBG) log("unregisterNetworkFactory for " + nfi.name);
   3495     }
   3496 
   3497     /**
   3498      * NetworkAgentInfo supporting a request by requestId.
   3499      * These have already been vetted (their Capabilities satisfy the request)
   3500      * and the are the highest scored network available.
   3501      * the are keyed off the Requests requestId.
   3502      */
   3503     private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
   3504             new SparseArray<NetworkAgentInfo>();
   3505 
   3506     private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
   3507             new SparseArray<NetworkAgentInfo>();
   3508 
   3509     // NetworkAgentInfo keyed off its connecting messenger
   3510     // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
   3511     private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
   3512             new HashMap<Messenger, NetworkAgentInfo>();
   3513 
   3514     private final NetworkRequest mDefaultRequest;
   3515 
   3516     private boolean isDefaultNetwork(NetworkAgentInfo nai) {
   3517         return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai;
   3518     }
   3519 
   3520     public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
   3521             LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
   3522             int currentScore, NetworkMisc networkMisc) {
   3523         enforceConnectivityInternalPermission();
   3524 
   3525         NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
   3526             new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
   3527             new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
   3528             new NetworkMisc(networkMisc));
   3529         synchronized (this) {
   3530             nai.networkMonitor.systemReady = mSystemReady;
   3531         }
   3532         if (DBG) log("registerNetworkAgent " + nai);
   3533         mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
   3534     }
   3535 
   3536     private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
   3537         if (VDBG) log("Got NetworkAgent Messenger");
   3538         mNetworkAgentInfos.put(na.messenger, na);
   3539         assignNextNetId(na);
   3540         na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
   3541         NetworkInfo networkInfo = na.networkInfo;
   3542         na.networkInfo = null;
   3543         updateNetworkInfo(na, networkInfo);
   3544     }
   3545 
   3546     private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
   3547         LinkProperties newLp = networkAgent.linkProperties;
   3548         int netId = networkAgent.network.netId;
   3549 
   3550         // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
   3551         // we do anything else, make sure its LinkProperties are accurate.
   3552         mClat.fixupLinkProperties(networkAgent, oldLp);
   3553 
   3554         updateInterfaces(newLp, oldLp, netId);
   3555         updateMtu(newLp, oldLp);
   3556         // TODO - figure out what to do for clat
   3557 //        for (LinkProperties lp : newLp.getStackedLinks()) {
   3558 //            updateMtu(lp, null);
   3559 //        }
   3560         updateTcpBufferSizes(networkAgent);
   3561         final boolean flushDns = updateRoutes(newLp, oldLp, netId);
   3562         updateDnses(newLp, oldLp, netId, flushDns);
   3563         updateClat(newLp, oldLp, networkAgent);
   3564         if (isDefaultNetwork(networkAgent)) handleApplyDefaultProxy(newLp.getHttpProxy());
   3565         // TODO - move this check to cover the whole function
   3566         if (!Objects.equals(newLp, oldLp)) {
   3567             notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
   3568         }
   3569     }
   3570 
   3571     private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
   3572         final boolean wasRunningClat = mClat.isRunningClat(na);
   3573         final boolean shouldRunClat = Nat464Xlat.requiresClat(na);
   3574 
   3575         if (!wasRunningClat && shouldRunClat) {
   3576             // Start clatd. If it's already been started but is not running yet, this is a no-op.
   3577             mClat.startClat(na);
   3578         } else if (wasRunningClat && !shouldRunClat) {
   3579             mClat.stopClat();
   3580         }
   3581     }
   3582 
   3583     private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
   3584         CompareResult<String> interfaceDiff = new CompareResult<String>();
   3585         if (oldLp != null) {
   3586             interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
   3587         } else if (newLp != null) {
   3588             interfaceDiff.added = newLp.getAllInterfaceNames();
   3589         }
   3590         for (String iface : interfaceDiff.added) {
   3591             try {
   3592                 if (DBG) log("Adding iface " + iface + " to network " + netId);
   3593                 mNetd.addInterfaceToNetwork(iface, netId);
   3594             } catch (Exception e) {
   3595                 loge("Exception adding interface: " + e);
   3596             }
   3597         }
   3598         for (String iface : interfaceDiff.removed) {
   3599             try {
   3600                 if (DBG) log("Removing iface " + iface + " from network " + netId);
   3601                 mNetd.removeInterfaceFromNetwork(iface, netId);
   3602             } catch (Exception e) {
   3603                 loge("Exception removing interface: " + e);
   3604             }
   3605         }
   3606     }
   3607 
   3608     /**
   3609      * Have netd update routes from oldLp to newLp.
   3610      * @return true if routes changed between oldLp and newLp
   3611      */
   3612     private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
   3613         CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
   3614         if (oldLp != null) {
   3615             routeDiff = oldLp.compareAllRoutes(newLp);
   3616         } else if (newLp != null) {
   3617             routeDiff.added = newLp.getAllRoutes();
   3618         }
   3619 
   3620         // add routes before removing old in case it helps with continuous connectivity
   3621 
   3622         // do this twice, adding non-nexthop routes first, then routes they are dependent on
   3623         for (RouteInfo route : routeDiff.added) {
   3624             if (route.hasGateway()) continue;
   3625             if (DBG) log("Adding Route [" + route + "] to network " + netId);
   3626             try {
   3627                 mNetd.addRoute(netId, route);
   3628             } catch (Exception e) {
   3629                 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
   3630                     loge("Exception in addRoute for non-gateway: " + e);
   3631                 }
   3632             }
   3633         }
   3634         for (RouteInfo route : routeDiff.added) {
   3635             if (route.hasGateway() == false) continue;
   3636             if (DBG) log("Adding Route [" + route + "] to network " + netId);
   3637             try {
   3638                 mNetd.addRoute(netId, route);
   3639             } catch (Exception e) {
   3640                 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
   3641                     loge("Exception in addRoute for gateway: " + e);
   3642                 }
   3643             }
   3644         }
   3645 
   3646         for (RouteInfo route : routeDiff.removed) {
   3647             if (DBG) log("Removing Route [" + route + "] from network " + netId);
   3648             try {
   3649                 mNetd.removeRoute(netId, route);
   3650             } catch (Exception e) {
   3651                 loge("Exception in removeRoute: " + e);
   3652             }
   3653         }
   3654         return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
   3655     }
   3656     private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, boolean flush) {
   3657         if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
   3658             Collection<InetAddress> dnses = newLp.getDnsServers();
   3659             if (dnses.size() == 0 && mDefaultDns != null) {
   3660                 dnses = new ArrayList();
   3661                 dnses.add(mDefaultDns);
   3662                 if (DBG) {
   3663                     loge("no dns provided for netId " + netId + ", so using defaults");
   3664                 }
   3665             }
   3666             if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
   3667             try {
   3668                 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
   3669                     newLp.getDomains());
   3670             } catch (Exception e) {
   3671                 loge("Exception in setDnsServersForNetwork: " + e);
   3672             }
   3673             NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
   3674             if (defaultNai != null && defaultNai.network.netId == netId) {
   3675                 setDefaultDnsSystemProperties(dnses);
   3676             }
   3677             flushVmDnsCache();
   3678         } else if (flush) {
   3679             try {
   3680                 mNetd.flushNetworkDnsCache(netId);
   3681             } catch (Exception e) {
   3682                 loge("Exception in flushNetworkDnsCache: " + e);
   3683             }
   3684             flushVmDnsCache();
   3685         }
   3686     }
   3687 
   3688     private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
   3689         int last = 0;
   3690         for (InetAddress dns : dnses) {
   3691             ++last;
   3692             String key = "net.dns" + last;
   3693             String value = dns.getHostAddress();
   3694             SystemProperties.set(key, value);
   3695         }
   3696         for (int i = last + 1; i <= mNumDnsEntries; ++i) {
   3697             String key = "net.dns" + i;
   3698             SystemProperties.set(key, "");
   3699         }
   3700         mNumDnsEntries = last;
   3701     }
   3702 
   3703 
   3704     private void updateCapabilities(NetworkAgentInfo networkAgent,
   3705             NetworkCapabilities networkCapabilities) {
   3706         //  TODO - turn this on in MR1 when we have more dogfooding time.
   3707         // rematchAllNetworksAndRequests();
   3708         if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
   3709             synchronized (networkAgent) {
   3710                 networkAgent.networkCapabilities = networkCapabilities;
   3711             }
   3712             notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
   3713         }
   3714     }
   3715 
   3716     private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
   3717         for (int i = 0; i < nai.networkRequests.size(); i++) {
   3718             NetworkRequest nr = nai.networkRequests.valueAt(i);
   3719             // Don't send listening requests to factories. b/17393458
   3720             if (!isRequest(nr)) continue;
   3721             sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
   3722         }
   3723     }
   3724 
   3725     private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
   3726         if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
   3727         for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
   3728             nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
   3729                     networkRequest);
   3730         }
   3731     }
   3732 
   3733     private void callCallbackForRequest(NetworkRequestInfo nri,
   3734             NetworkAgentInfo networkAgent, int notificationType) {
   3735         if (nri.messenger == null) return;  // Default request has no msgr
   3736         Bundle bundle = new Bundle();
   3737         bundle.putParcelable(NetworkRequest.class.getSimpleName(),
   3738                 new NetworkRequest(nri.request));
   3739         Message msg = Message.obtain();
   3740         if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
   3741                 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
   3742             bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
   3743         }
   3744         switch (notificationType) {
   3745             case ConnectivityManager.CALLBACK_LOSING: {
   3746                 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
   3747                 break;
   3748             }
   3749             case ConnectivityManager.CALLBACK_CAP_CHANGED: {
   3750                 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
   3751                         new NetworkCapabilities(networkAgent.networkCapabilities));
   3752                 break;
   3753             }
   3754             case ConnectivityManager.CALLBACK_IP_CHANGED: {
   3755                 bundle.putParcelable(LinkProperties.class.getSimpleName(),
   3756                         new LinkProperties(networkAgent.linkProperties));
   3757                 break;
   3758             }
   3759         }
   3760         msg.what = notificationType;
   3761         msg.setData(bundle);
   3762         try {
   3763             if (VDBG) {
   3764                 log("sending notification " + notifyTypeToName(notificationType) +
   3765                         " for " + nri.request);
   3766             }
   3767             nri.messenger.send(msg);
   3768         } catch (RemoteException e) {
   3769             // may occur naturally in the race of binder death.
   3770             loge("RemoteException caught trying to send a callback msg for " + nri.request);
   3771         }
   3772     }
   3773 
   3774     private void teardownUnneededNetwork(NetworkAgentInfo nai) {
   3775         for (int i = 0; i < nai.networkRequests.size(); i++) {
   3776             NetworkRequest nr = nai.networkRequests.valueAt(i);
   3777             // Ignore listening requests.
   3778             if (!isRequest(nr)) continue;
   3779             loge("Dead network still had at least " + nr);
   3780             break;
   3781         }
   3782         nai.asyncChannel.disconnect();
   3783     }
   3784 
   3785     private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
   3786         if (oldNetwork == null) {
   3787             loge("Unknown NetworkAgentInfo in handleLingerComplete");
   3788             return;
   3789         }
   3790         if (DBG) log("handleLingerComplete for " + oldNetwork.name());
   3791         teardownUnneededNetwork(oldNetwork);
   3792     }
   3793 
   3794     private void makeDefault(NetworkAgentInfo newNetwork) {
   3795         if (DBG) log("Switching to new default network: " + newNetwork);
   3796         mActiveDefaultNetwork = newNetwork.networkInfo.getType();
   3797         setupDataActivityTracking(newNetwork);
   3798         try {
   3799             mNetd.setDefaultNetId(newNetwork.network.netId);
   3800         } catch (Exception e) {
   3801             loge("Exception setting default network :" + e);
   3802         }
   3803         notifyLockdownVpn(newNetwork);
   3804         handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
   3805         updateTcpBufferSizes(newNetwork);
   3806     }
   3807 
   3808     // Handles a network appearing or improving its score.
   3809     //
   3810     // - Evaluates all current NetworkRequests that can be
   3811     //   satisfied by newNetwork, and reassigns to newNetwork
   3812     //   any such requests for which newNetwork is the best.
   3813     //
   3814     // - Lingers any Networks that as a result are no longer
   3815     //   needed. A network is needed if it is the best network for
   3816     //   one or more NetworkRequests, or if it is a VPN.
   3817     //
   3818     // - Tears down newNetwork if it just became validated
   3819     //   (i.e. nascent==true) but turns out to be unneeded.
   3820     //   Does not tear down newNetwork if it is unvalidated,
   3821     //   because future validation may improve newNetwork's
   3822     //   score enough that it is needed.
   3823     //
   3824     // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
   3825     // it does not remove NetworkRequests that other Networks could better satisfy.
   3826     // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
   3827     // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
   3828     // as it performs better by a factor of the number of Networks.
   3829     //
   3830     // @param nascent indicates if newNetwork just became validated, in which case it should be
   3831     //               torn down if unneeded.  If nascent is false, no action is taken if newNetwork
   3832     //               is found to be unneeded by this call.  Presumably, in this case, either:
   3833     //               - newNetwork is unvalidated (and left alive), or
   3834     //               - the NetworkRequests keeping newNetwork alive have been transitioned to
   3835     //                 another higher scoring network by another call to rematchNetworkAndRequests()
   3836     //                 and this other call also lingered newNetwork.
   3837     private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, boolean nascent) {
   3838         if (!newNetwork.created) loge("ERROR: uncreated network being rematched.");
   3839         if (nascent && !newNetwork.validated) loge("ERROR: nascent network not validated.");
   3840         boolean keep = newNetwork.isVPN();
   3841         boolean isNewDefault = false;
   3842         if (DBG) log("rematching " + newNetwork.name());
   3843         // Find and migrate to this Network any NetworkRequests for
   3844         // which this network is now the best.
   3845         ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
   3846         if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
   3847         for (NetworkRequestInfo nri : mNetworkRequests.values()) {
   3848             NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
   3849             if (newNetwork == currentNetwork) {
   3850                 if (DBG) {
   3851                     log("Network " + newNetwork.name() + " was already satisfying" +
   3852                             " request " + nri.request.requestId + ". No change.");
   3853                 }
   3854                 keep = true;
   3855                 continue;
   3856             }
   3857 
   3858             // check if it satisfies the NetworkCapabilities
   3859             if (VDBG) log("  checking if request is satisfied: " + nri.request);
   3860             if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
   3861                     newNetwork.networkCapabilities)) {
   3862                 if (!nri.isRequest) {
   3863                     // This is not a request, it's a callback listener.
   3864                     // Add it to newNetwork regardless of score.
   3865                     newNetwork.addRequest(nri.request);
   3866                     continue;
   3867                 }
   3868 
   3869                 // next check if it's better than any current network we're using for
   3870                 // this request
   3871                 if (VDBG) {
   3872                     log("currentScore = " +
   3873                             (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
   3874                             ", newScore = " + newNetwork.getCurrentScore());
   3875                 }
   3876                 if (currentNetwork == null ||
   3877                         currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
   3878                     if (currentNetwork != null) {
   3879                         if (DBG) log("   accepting network in place of " + currentNetwork.name());
   3880                         currentNetwork.networkRequests.remove(nri.request.requestId);
   3881                         currentNetwork.networkLingered.add(nri.request);
   3882                         affectedNetworks.add(currentNetwork);
   3883                     } else {
   3884                         if (DBG) log("   accepting network in place of null");
   3885                     }
   3886                     mNetworkForRequestId.put(nri.request.requestId, newNetwork);
   3887                     newNetwork.addRequest(nri.request);
   3888                     if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
   3889                         mLegacyTypeTracker.add(nri.request.legacyType, newNetwork);
   3890                     }
   3891                     keep = true;
   3892                     // Tell NetworkFactories about the new score, so they can stop
   3893                     // trying to connect if they know they cannot match it.
   3894                     // TODO - this could get expensive if we have alot of requests for this
   3895                     // network.  Think about if there is a way to reduce this.  Push
   3896                     // netid->request mapping to each factory?
   3897                     sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
   3898                     if (mDefaultRequest.requestId == nri.request.requestId) {
   3899                         isNewDefault = true;
   3900                         // TODO: Remove following line.  It's redundant with makeDefault call.
   3901                         mActiveDefaultNetwork = newNetwork.networkInfo.getType();
   3902                         if (newNetwork.linkProperties != null) {
   3903                             updateTcpBufferSizes(newNetwork);
   3904                             setDefaultDnsSystemProperties(
   3905                                     newNetwork.linkProperties.getDnsServers());
   3906                         } else {
   3907                             setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
   3908                         }
   3909                         // Maintain the illusion: since the legacy API only
   3910                         // understands one network at a time, we must pretend
   3911                         // that the current default network disconnected before
   3912                         // the new one connected.
   3913                         if (currentNetwork != null) {
   3914                             mLegacyTypeTracker.remove(currentNetwork.networkInfo.getType(),
   3915                                                       currentNetwork);
   3916                         }
   3917                         mDefaultInetConditionPublished = newNetwork.validated ? 100 : 0;
   3918                         mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
   3919                         notifyLockdownVpn(newNetwork);
   3920                     }
   3921                 }
   3922             }
   3923         }
   3924         // Linger any networks that are no longer needed.
   3925         for (NetworkAgentInfo nai : affectedNetworks) {
   3926             boolean teardown = !nai.isVPN() && nai.validated;
   3927             for (int i = 0; i < nai.networkRequests.size() && teardown; i++) {
   3928                 NetworkRequest nr = nai.networkRequests.valueAt(i);
   3929                 try {
   3930                 if (isRequest(nr)) {
   3931                     teardown = false;
   3932                 }
   3933                 } catch (Exception e) {
   3934                     loge("Request " + nr + " not found in mNetworkRequests.");
   3935                     loge("  it came from request list  of " + nai.name());
   3936                 }
   3937             }
   3938             if (teardown) {
   3939                 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
   3940                 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
   3941             } else {
   3942                 // not going to linger, so kill the list of linger networks..  only
   3943                 // notify them of linger if it happens as the result of gaining another,
   3944                 // but if they transition and old network stays up, don't tell them of linger
   3945                 // or very delayed loss
   3946                 nai.networkLingered.clear();
   3947                 if (VDBG) log("Lingered for " + nai.name() + " cleared");
   3948             }
   3949         }
   3950         if (keep) {
   3951             if (isNewDefault) {
   3952                 // Notify system services that this network is up.
   3953                 makeDefault(newNetwork);
   3954                 synchronized (ConnectivityService.this) {
   3955                     // have a new default network, release the transition wakelock in
   3956                     // a second if it's held.  The second pause is to allow apps
   3957                     // to reconnect over the new network
   3958                     if (mNetTransitionWakeLock.isHeld()) {
   3959                         mHandler.sendMessageDelayed(mHandler.obtainMessage(
   3960                                 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
   3961                                 mNetTransitionWakeLockSerialNumber, 0),
   3962                                 1000);
   3963                     }
   3964                 }
   3965             }
   3966 
   3967             // Notify battery stats service about this network, both the normal
   3968             // interface and any stacked links.
   3969             // TODO: Avoid redoing this; this must only be done once when a network comes online.
   3970             try {
   3971                 final IBatteryStats bs = BatteryStatsService.getService();
   3972                 final int type = newNetwork.networkInfo.getType();
   3973 
   3974                 final String baseIface = newNetwork.linkProperties.getInterfaceName();
   3975                 bs.noteNetworkInterfaceType(baseIface, type);
   3976                 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
   3977                     final String stackedIface = stacked.getInterfaceName();
   3978                     bs.noteNetworkInterfaceType(stackedIface, type);
   3979                     NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
   3980                 }
   3981             } catch (RemoteException ignored) {
   3982             }
   3983 
   3984             notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
   3985         } else if (nascent) {
   3986             // Only tear down newly validated networks here.  Leave unvalidated to either become
   3987             // validated (and get evaluated against peers, one losing here) or
   3988             // NetworkMonitor reports a bad network and we tear it down then.
   3989             // Networks that have been up for a while and are validated should be torn down via
   3990             // the lingering process so communication on that network is given time to wrap up.
   3991             // TODO: Could teardown unvalidated networks when their NetworkCapabilities
   3992             // satisfy no NetworkRequests.
   3993             if (DBG) log("Validated network turns out to be unwanted.  Tear it down.");
   3994             teardownUnneededNetwork(newNetwork);
   3995         }
   3996     }
   3997 
   3998     // Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
   3999     // being disconnected.
   4000     // If only one Network's score or capabilities have been modified since the last time
   4001     // this function was called, pass this Network in via the "changed" arugment, otherwise
   4002     // pass null.
   4003     // If only one Network has been changed but its NetworkCapabilities have not changed,
   4004     // pass in the Network's score (from getCurrentScore()) prior to the change via
   4005     // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
   4006     private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
   4007         // TODO: This may get slow.  The "changed" parameter is provided for future optimization
   4008         // to avoid the slowness.  It is not simply enough to process just "changed", for
   4009         // example in the case where "changed"'s score decreases and another network should begin
   4010         // satifying a NetworkRequest that "changed" currently satisfies.
   4011 
   4012         // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
   4013         // can only add more NetworkRequests satisfied by "changed", and this is exactly what
   4014         // rematchNetworkAndRequests() handles.
   4015         if (changed != null && oldScore < changed.getCurrentScore()) {
   4016             rematchNetworkAndRequests(changed, false);
   4017         } else {
   4018             for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
   4019                 rematchNetworkAndRequests(nai, false);
   4020             }
   4021         }
   4022     }
   4023 
   4024     private void updateInetCondition(NetworkAgentInfo nai, boolean valid) {
   4025         // Don't bother updating until we've graduated to validated at least once.
   4026         if (!nai.validated) return;
   4027         // For now only update icons for default connection.
   4028         // TODO: Update WiFi and cellular icons separately. b/17237507
   4029         if (!isDefaultNetwork(nai)) return;
   4030 
   4031         int newInetCondition = valid ? 100 : 0;
   4032         // Don't repeat publish.
   4033         if (newInetCondition == mDefaultInetConditionPublished) return;
   4034 
   4035         mDefaultInetConditionPublished = newInetCondition;
   4036         sendInetConditionBroadcast(nai.networkInfo);
   4037     }
   4038 
   4039     private void notifyLockdownVpn(NetworkAgentInfo nai) {
   4040         if (mLockdownTracker != null) {
   4041             if (nai != null && nai.isVPN()) {
   4042                 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
   4043             } else {
   4044                 mLockdownTracker.onNetworkInfoChanged();
   4045             }
   4046         }
   4047     }
   4048 
   4049     private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
   4050         NetworkInfo.State state = newInfo.getState();
   4051         NetworkInfo oldInfo = null;
   4052         synchronized (networkAgent) {
   4053             oldInfo = networkAgent.networkInfo;
   4054             networkAgent.networkInfo = newInfo;
   4055         }
   4056         notifyLockdownVpn(networkAgent);
   4057 
   4058         if (oldInfo != null && oldInfo.getState() == state) {
   4059             if (VDBG) log("ignoring duplicate network state non-change");
   4060             return;
   4061         }
   4062         if (DBG) {
   4063             log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
   4064                     (oldInfo == null ? "null" : oldInfo.getState()) +
   4065                     " to " + state);
   4066         }
   4067 
   4068         if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
   4069             try {
   4070                 // This should never fail.  Specifying an already in use NetID will cause failure.
   4071                 if (networkAgent.isVPN()) {
   4072                     mNetd.createVirtualNetwork(networkAgent.network.netId,
   4073                             !networkAgent.linkProperties.getDnsServers().isEmpty(),
   4074                             (networkAgent.networkMisc == null ||
   4075                                 !networkAgent.networkMisc.allowBypass));
   4076                 } else {
   4077                     mNetd.createPhysicalNetwork(networkAgent.network.netId);
   4078                 }
   4079             } catch (Exception e) {
   4080                 loge("Error creating network " + networkAgent.network.netId + ": "
   4081                         + e.getMessage());
   4082                 return;
   4083             }
   4084             networkAgent.created = true;
   4085             updateLinkProperties(networkAgent, null);
   4086             notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
   4087             networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
   4088             if (networkAgent.isVPN()) {
   4089                 // Temporarily disable the default proxy (not global).
   4090                 synchronized (mProxyLock) {
   4091                     if (!mDefaultProxyDisabled) {
   4092                         mDefaultProxyDisabled = true;
   4093                         if (mGlobalProxy == null && mDefaultProxy != null) {
   4094                             sendProxyBroadcast(null);
   4095                         }
   4096                     }
   4097                 }
   4098                 // TODO: support proxy per network.
   4099             }
   4100             // Consider network even though it is not yet validated.
   4101             rematchNetworkAndRequests(networkAgent, false);
   4102         } else if (state == NetworkInfo.State.DISCONNECTED ||
   4103                 state == NetworkInfo.State.SUSPENDED) {
   4104             networkAgent.asyncChannel.disconnect();
   4105             if (networkAgent.isVPN()) {
   4106                 synchronized (mProxyLock) {
   4107                     if (mDefaultProxyDisabled) {
   4108                         mDefaultProxyDisabled = false;
   4109                         if (mGlobalProxy == null && mDefaultProxy != null) {
   4110                             sendProxyBroadcast(mDefaultProxy);
   4111                         }
   4112                     }
   4113                 }
   4114             }
   4115         }
   4116     }
   4117 
   4118     private void updateNetworkScore(NetworkAgentInfo nai, int score) {
   4119         if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
   4120         if (score < 0) {
   4121             loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
   4122                     ").  Bumping score to min of 0");
   4123             score = 0;
   4124         }
   4125 
   4126         final int oldScore = nai.getCurrentScore();
   4127         nai.setCurrentScore(score);
   4128 
   4129         if (nai.created) rematchAllNetworksAndRequests(nai, oldScore);
   4130 
   4131         sendUpdatedScoreToFactories(nai);
   4132     }
   4133 
   4134     // notify only this one new request of the current state
   4135     protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
   4136         int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
   4137         // TODO - read state from monitor to decide what to send.
   4138 //        if (nai.networkMonitor.isLingering()) {
   4139 //            notifyType = NetworkCallbacks.LOSING;
   4140 //        } else if (nai.networkMonitor.isEvaluating()) {
   4141 //            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
   4142 //        }
   4143         callCallbackForRequest(nri, nai, notifyType);
   4144     }
   4145 
   4146     private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
   4147         // The NetworkInfo we actually send out has no bearing on the real
   4148         // state of affairs. For example, if the default connection is mobile,
   4149         // and a request for HIPRI has just gone away, we need to pretend that
   4150         // HIPRI has just disconnected. So we need to set the type to HIPRI and
   4151         // the state to DISCONNECTED, even though the network is of type MOBILE
   4152         // and is still connected.
   4153         NetworkInfo info = new NetworkInfo(nai.networkInfo);
   4154         info.setType(type);
   4155         if (connected) {
   4156             info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
   4157             sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
   4158         } else {
   4159             info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
   4160             Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
   4161             intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
   4162             intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
   4163             if (info.isFailover()) {
   4164                 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
   4165                 nai.networkInfo.setFailover(false);
   4166             }
   4167             if (info.getReason() != null) {
   4168                 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
   4169             }
   4170             if (info.getExtraInfo() != null) {
   4171                 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
   4172             }
   4173             NetworkAgentInfo newDefaultAgent = null;
   4174             if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
   4175                 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
   4176                 if (newDefaultAgent != null) {
   4177                     intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
   4178                             newDefaultAgent.networkInfo);
   4179                 } else {
   4180                     intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
   4181                 }
   4182             }
   4183             intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
   4184                     mDefaultInetConditionPublished);
   4185             final Intent immediateIntent = new Intent(intent);
   4186             immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
   4187             sendStickyBroadcast(immediateIntent);
   4188             sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
   4189             if (newDefaultAgent != null) {
   4190                 sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
   4191                 getConnectivityChangeDelay());
   4192             }
   4193         }
   4194     }
   4195 
   4196     protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
   4197         if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
   4198         for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
   4199             NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
   4200             NetworkRequestInfo nri = mNetworkRequests.get(nr);
   4201             if (VDBG) log(" sending notification for " + nr);
   4202             callCallbackForRequest(nri, networkAgent, notifyType);
   4203         }
   4204     }
   4205 
   4206     private String notifyTypeToName(int notifyType) {
   4207         switch (notifyType) {
   4208             case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
   4209             case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
   4210             case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
   4211             case ConnectivityManager.CALLBACK_LOST:        return "LOST";
   4212             case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
   4213             case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
   4214             case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
   4215             case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
   4216         }
   4217         return "UNKNOWN";
   4218     }
   4219 
   4220     private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
   4221         NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
   4222         if (nai != null) {
   4223             synchronized (nai) {
   4224                 return new LinkProperties(nai.linkProperties);
   4225             }
   4226         }
   4227         return new LinkProperties();
   4228     }
   4229 
   4230     private NetworkInfo getNetworkInfoForType(int networkType) {
   4231         if (!mLegacyTypeTracker.isTypeSupported(networkType))
   4232             return null;
   4233 
   4234         NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
   4235         if (nai != null) {
   4236             NetworkInfo result = new NetworkInfo(nai.networkInfo);
   4237             result.setType(networkType);
   4238             return result;
   4239         } else {
   4240             NetworkInfo result = new NetworkInfo(
   4241                     networkType, 0, ConnectivityManager.getNetworkTypeName(networkType), "");
   4242             result.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
   4243             result.setIsAvailable(true);
   4244             return result;
   4245         }
   4246     }
   4247 
   4248     private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
   4249         NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
   4250         if (nai != null) {
   4251             synchronized (nai) {
   4252                 return new NetworkCapabilities(nai.networkCapabilities);
   4253             }
   4254         }
   4255         return new NetworkCapabilities();
   4256     }
   4257 
   4258     @Override
   4259     public boolean addVpnAddress(String address, int prefixLength) {
   4260         throwIfLockdownEnabled();
   4261         int user = UserHandle.getUserId(Binder.getCallingUid());
   4262         synchronized (mVpns) {
   4263             return mVpns.get(user).addAddress(address, prefixLength);
   4264         }
   4265     }
   4266 
   4267     @Override
   4268     public boolean removeVpnAddress(String address, int prefixLength) {
   4269         throwIfLockdownEnabled();
   4270         int user = UserHandle.getUserId(Binder.getCallingUid());
   4271         synchronized (mVpns) {
   4272             return mVpns.get(user).removeAddress(address, prefixLength);
   4273         }
   4274     }
   4275 }
   4276