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