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