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