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