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