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