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