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