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