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