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