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