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