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