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