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