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