ConnectivityService.java revision 6bc2c2c34f2b23eae79ad733c97a691734055c4f
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
20import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
23import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_MOBILE;
26import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
27import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
28import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
29import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
30import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
31import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
32import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
33import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
34import static android.net.ConnectivityManager.TYPE_NONE;
35import static android.net.ConnectivityManager.TYPE_WIFI;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
37import static android.net.ConnectivityManager.TYPE_PROXY;
38import static android.net.ConnectivityManager.getNetworkTypeName;
39import static android.net.ConnectivityManager.isNetworkTypeValid;
40import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
41import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
42
43import android.app.AlarmManager;
44import android.app.AppOpsManager;
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.ApplicationInfo;
56import android.content.pm.PackageManager;
57import android.content.pm.PackageManager.NameNotFoundException;
58import android.content.res.Configuration;
59import android.content.res.Resources;
60import android.database.ContentObserver;
61import android.net.CaptivePortalTracker;
62import android.net.ConnectivityManager;
63import android.net.IConnectivityManager;
64import android.net.INetworkManagementEventObserver;
65import android.net.INetworkPolicyListener;
66import android.net.INetworkPolicyManager;
67import android.net.INetworkStatsService;
68import android.net.LinkAddress;
69import android.net.LinkProperties;
70import android.net.LinkProperties.CompareResult;
71import android.net.LinkQualityInfo;
72import android.net.MobileDataStateTracker;
73import android.net.Network;
74import android.net.NetworkAgent;
75import android.net.NetworkCapabilities;
76import android.net.NetworkConfig;
77import android.net.NetworkInfo;
78import android.net.NetworkInfo.DetailedState;
79import android.net.NetworkFactory;
80import android.net.NetworkQuotaInfo;
81import android.net.NetworkRequest;
82import android.net.NetworkState;
83import android.net.NetworkStateTracker;
84import android.net.NetworkUtils;
85import android.net.Proxy;
86import android.net.ProxyDataTracker;
87import android.net.ProxyInfo;
88import android.net.RouteInfo;
89import android.net.SamplingDataTracker;
90import android.net.UidRange;
91import android.net.Uri;
92import android.net.wimax.WimaxManagerConstants;
93import android.os.AsyncTask;
94import android.os.Binder;
95import android.os.Build;
96import android.os.FileUtils;
97import android.os.Handler;
98import android.os.HandlerThread;
99import android.os.IBinder;
100import android.os.INetworkManagementService;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Messenger;
104import android.os.ParcelFileDescriptor;
105import android.os.PowerManager;
106import android.os.Process;
107import android.os.RemoteException;
108import android.os.ServiceManager;
109import android.os.SystemClock;
110import android.os.SystemProperties;
111import android.os.UserHandle;
112import android.os.UserManager;
113import android.provider.Settings;
114import android.security.Credentials;
115import android.security.KeyStore;
116import android.telephony.TelephonyManager;
117import android.text.TextUtils;
118import android.util.Slog;
119import android.util.SparseArray;
120import android.util.SparseIntArray;
121import android.util.Xml;
122
123import com.android.internal.R;
124import com.android.internal.annotations.GuardedBy;
125import com.android.internal.net.LegacyVpnInfo;
126import com.android.internal.net.VpnConfig;
127import com.android.internal.net.VpnProfile;
128import com.android.internal.telephony.DctConstants;
129import com.android.internal.telephony.Phone;
130import com.android.internal.telephony.PhoneConstants;
131import com.android.internal.telephony.TelephonyIntents;
132import com.android.internal.util.AsyncChannel;
133import com.android.internal.util.IndentingPrintWriter;
134import com.android.internal.util.XmlUtils;
135import com.android.server.am.BatteryStatsService;
136import com.android.server.connectivity.DataConnectionStats;
137import com.android.server.connectivity.Nat464Xlat;
138import com.android.server.connectivity.NetworkAgentInfo;
139import com.android.server.connectivity.NetworkMonitor;
140import com.android.server.connectivity.PacManager;
141import com.android.server.connectivity.Tethering;
142import com.android.server.connectivity.Vpn;
143import com.android.server.net.BaseNetworkObserver;
144import com.android.server.net.LockdownVpnTracker;
145import com.google.android.collect.Lists;
146import com.google.android.collect.Sets;
147
148import dalvik.system.DexClassLoader;
149
150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152
153import java.io.File;
154import java.io.FileDescriptor;
155import java.io.FileNotFoundException;
156import java.io.FileReader;
157import java.io.IOException;
158import java.io.PrintWriter;
159import java.lang.reflect.Constructor;
160import java.net.HttpURLConnection;
161import java.net.Inet4Address;
162import java.net.Inet6Address;
163import java.net.InetAddress;
164import java.net.URL;
165import java.net.UnknownHostException;
166import java.util.ArrayList;
167import java.util.Arrays;
168import java.util.Collection;
169import java.util.GregorianCalendar;
170import java.util.HashMap;
171import java.util.HashSet;
172import java.util.List;
173import java.util.Map;
174import java.util.Random;
175import java.util.concurrent.atomic.AtomicBoolean;
176import java.util.concurrent.atomic.AtomicInteger;
177
178import javax.net.ssl.HostnameVerifier;
179import javax.net.ssl.HttpsURLConnection;
180import javax.net.ssl.SSLSession;
181
182import static android.net.ConnectivityManager.INVALID_NET_ID;
183
184/**
185 * @hide
186 */
187public class ConnectivityService extends IConnectivityManager.Stub {
188    private static final String TAG = "ConnectivityService";
189
190    private static final boolean DBG = true;
191    private static final boolean VDBG = true; // STOPSHIP
192
193    // network sampling debugging
194    private static final boolean SAMPLE_DBG = false;
195
196    private static final boolean LOGD_RULES = false;
197
198    // TODO: create better separation between radio types and network types
199
200    // how long to wait before switching back to a radio's default network
201    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
202    // system property that can override the above value
203    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
204            "android.telephony.apn-restore";
205
206    // Default value if FAIL_FAST_TIME_MS is not set
207    private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
208    // system property that can override DEFAULT_FAIL_FAST_TIME_MS
209    private static final String FAIL_FAST_TIME_MS =
210            "persist.radio.fail_fast_time_ms";
211
212    private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
213            "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
214
215    private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
216
217    private PendingIntent mSampleIntervalElapsedIntent;
218
219    // Set network sampling interval at 12 minutes, this way, even if the timers get
220    // aggregated, it will fire at around 15 minutes, which should allow us to
221    // aggregate this timer with other timers (specially the socket keep alive timers)
222    private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60);
223
224    // start network sampling a minute after booting ...
225    private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60);
226
227    AlarmManager mAlarmManager;
228
229    // used in recursive route setting to add gateways for the host for which
230    // a host route was requested.
231    private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
232
233    private Tethering mTethering;
234
235    private KeyStore mKeyStore;
236
237    @GuardedBy("mVpns")
238    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
239
240    private boolean mLockdownEnabled;
241    private LockdownVpnTracker mLockdownTracker;
242
243    private Nat464Xlat mClat;
244
245    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
246    private Object mRulesLock = new Object();
247    /** Currently active network rules by UID. */
248    private SparseIntArray mUidRules = new SparseIntArray();
249    /** Set of ifaces that are costly. */
250    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
251
252    /**
253     * Sometimes we want to refer to the individual network state
254     * trackers separately, and sometimes we just want to treat them
255     * abstractly.
256     */
257    private NetworkStateTracker mNetTrackers[];
258
259    /*
260     * Handles captive portal check on a network.
261     * Only set if device has {@link PackageManager#FEATURE_WIFI}.
262     */
263    private CaptivePortalTracker mCaptivePortalTracker;
264
265    /**
266     * The link properties that define the current links
267     */
268    private LinkProperties mCurrentLinkProperties[];
269
270    /**
271     * A per Net list of the PID's that requested access to the net
272     * used both as a refcount and for per-PID DNS selection
273     */
274    private List<Integer> mNetRequestersPids[];
275
276    // priority order of the nettrackers
277    // (excluding dynamically set mNetworkPreference)
278    // TODO - move mNetworkTypePreference into this
279    private int[] mPriorityList;
280
281    private Context mContext;
282    private int mNetworkPreference;
283    private int mActiveDefaultNetwork = -1;
284    // 0 is full bad, 100 is full good
285    private int mDefaultInetCondition = 0;
286    private int mDefaultInetConditionPublished = 0;
287    private boolean mInetConditionChangeInFlight = false;
288    private int mDefaultConnectionSequence = 0;
289
290    private Object mDnsLock = new Object();
291    private int mNumDnsEntries;
292
293    private boolean mTestMode;
294    private static ConnectivityService sServiceInstance;
295
296    private INetworkManagementService mNetd;
297    private INetworkPolicyManager mPolicyManager;
298
299    private static final int ENABLED  = 1;
300    private static final int DISABLED = 0;
301
302    private static final boolean ADD = true;
303    private static final boolean REMOVE = false;
304
305    private static final boolean TO_DEFAULT_TABLE = true;
306    private static final boolean TO_SECONDARY_TABLE = false;
307
308    private static final boolean EXEMPT = true;
309    private static final boolean UNEXEMPT = false;
310
311    /**
312     * used internally as a delayed event to make us switch back to the
313     * default network
314     */
315    private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
316
317    /**
318     * used internally to change our mobile data enabled flag
319     */
320    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
321
322    /**
323     * used internally to synchronize inet condition reports
324     * arg1 = networkType
325     * arg2 = condition (0 bad, 100 good)
326     */
327    private static final int EVENT_INET_CONDITION_CHANGE = 4;
328
329    /**
330     * used internally to mark the end of inet condition hold periods
331     * arg1 = networkType
332     */
333    private static final int EVENT_INET_CONDITION_HOLD_END = 5;
334
335    /**
336     * used internally to clear a wakelock when transitioning
337     * from one net to another.  Clear happens when we get a new
338     * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
339     * after a timeout if no network is found (typically 1 min).
340     */
341    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
342
343    /**
344     * used internally to reload global proxy settings
345     */
346    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
347
348    /**
349     * used internally to set external dependency met/unmet
350     * arg1 = ENABLED (met) or DISABLED (unmet)
351     * arg2 = NetworkType
352     */
353    private static final int EVENT_SET_DEPENDENCY_MET = 10;
354
355    /**
356     * used internally to send a sticky broadcast delayed.
357     */
358    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
359
360    /**
361     * Used internally to
362     * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
363     */
364    private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
365
366    /**
367     * Used internally to disable fail fast of mobile data
368     */
369    private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
370
371    /**
372     * used internally to indicate that data sampling interval is up
373     */
374    private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
375
376    /**
377     * PAC manager has received new port.
378     */
379    private static final int EVENT_PROXY_HAS_CHANGED = 16;
380
381    /**
382     * used internally when registering NetworkFactories
383     * obj = NetworkFactoryInfo
384     */
385    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
386
387    /**
388     * used internally when registering NetworkAgents
389     * obj = Messenger
390     */
391    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
392
393    /**
394     * used to add a network request
395     * includes a NetworkRequestInfo
396     */
397    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
398
399    /**
400     * indicates a timeout period is over - check if we had a network yet or not
401     * and if not, call the timeout calback (but leave the request live until they
402     * cancel it.
403     * includes a NetworkRequestInfo
404     */
405    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
406
407    /**
408     * used to add a network listener - no request
409     * includes a NetworkRequestInfo
410     */
411    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
412
413    /**
414     * used to remove a network request, either a listener or a real request
415     * arg1 = UID of caller
416     * obj  = NetworkRequest
417     */
418    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
419
420    /**
421     * used internally when registering NetworkFactories
422     * obj = Messenger
423     */
424    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
425
426    /**
427     * used internally to expire a wakelock when transitioning
428     * from one net to another.  Expire happens when we fail to find
429     * a new network (typically after 1 minute) -
430     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
431     * a replacement network.
432     */
433    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
434
435
436    /** Handler used for internal events. */
437    final private InternalHandler mHandler;
438    /** Handler used for incoming {@link NetworkStateTracker} events. */
439    final private NetworkStateTrackerHandler mTrackerHandler;
440
441    // list of DeathRecipients used to make sure features are turned off when
442    // a process dies
443    private List<FeatureUser> mFeatureUsers;
444
445    private boolean mSystemReady;
446    private Intent mInitialBroadcast;
447
448    private PowerManager.WakeLock mNetTransitionWakeLock;
449    private String mNetTransitionWakeLockCausedBy = "";
450    private int mNetTransitionWakeLockSerialNumber;
451    private int mNetTransitionWakeLockTimeout;
452
453    private InetAddress mDefaultDns;
454
455    // Lock for protecting access to mAddedRoutes and mExemptAddresses
456    private final Object mRoutesLock = new Object();
457
458    // this collection is used to refcount the added routes - if there are none left
459    // it's time to remove the route from the route table
460    @GuardedBy("mRoutesLock")
461    private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
462
463    // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
464    // used to handle cleanup of exempt rules
465    @GuardedBy("mRoutesLock")
466    private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
467
468    // used in DBG mode to track inet condition reports
469    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
470    private ArrayList mInetLog;
471
472    // track the current default http proxy - tell the world if we get a new one (real change)
473    private ProxyInfo mDefaultProxy = null;
474    private Object mProxyLock = new Object();
475    private boolean mDefaultProxyDisabled = false;
476
477    // track the global proxy.
478    private ProxyInfo mGlobalProxy = null;
479
480    private PacManager mPacManager = null;
481
482    private SettingsObserver mSettingsObserver;
483
484    private AppOpsManager mAppOpsManager;
485
486    private UserManager mUserManager;
487
488    NetworkConfig[] mNetConfigs;
489    int mNetworksDefined;
490
491    private static class RadioAttributes {
492        public int mSimultaneity;
493        public int mType;
494        public RadioAttributes(String init) {
495            String fragments[] = init.split(",");
496            mType = Integer.parseInt(fragments[0]);
497            mSimultaneity = Integer.parseInt(fragments[1]);
498        }
499    }
500    RadioAttributes[] mRadioAttributes;
501
502    // the set of network types that can only be enabled by system/sig apps
503    List mProtectedNetworks;
504
505    private DataConnectionStats mDataConnectionStats;
506
507    private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
508
509    TelephonyManager mTelephonyManager;
510
511    // sequence number for Networks
512    private final static int MIN_NET_ID = 10; // some reserved marks
513    private final static int MAX_NET_ID = 65535;
514    private int mNextNetId = MIN_NET_ID;
515
516    // sequence number of NetworkRequests
517    private int mNextNetworkRequestId = 1;
518
519    private static final int UID_UNUSED = -1;
520
521    /**
522     * Implements support for the legacy "one network per network type" model.
523     *
524     * We used to have a static array of NetworkStateTrackers, one for each
525     * network type, but that doesn't work any more now that we can have,
526     * for example, more that one wifi network. This class stores all the
527     * NetworkAgentInfo objects that support a given type, but the legacy
528     * API will only see the first one.
529     *
530     * It serves two main purposes:
531     *
532     * 1. Provide information about "the network for a given type" (since this
533     *    API only supports one).
534     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
535     *    the first network for a given type changes, or if the default network
536     *    changes.
537     */
538    private class LegacyTypeTracker {
539        /**
540         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
541         * Each list holds references to all NetworkAgentInfos that are used to
542         * satisfy requests for that network type.
543         *
544         * This array is built out at startup such that an unsupported network
545         * doesn't get an ArrayList instance, making this a tristate:
546         * unsupported, supported but not active and active.
547         *
548         * The actual lists are populated when we scan the network types that
549         * are supported on this device.
550         */
551        private ArrayList<NetworkAgentInfo> mTypeLists[];
552
553        public LegacyTypeTracker() {
554            mTypeLists = (ArrayList<NetworkAgentInfo>[])
555                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
556        }
557
558        public void addSupportedType(int type) {
559            if (mTypeLists[type] != null) {
560                throw new IllegalStateException(
561                        "legacy list for type " + type + "already initialized");
562            }
563            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
564        }
565
566        private boolean isDefaultNetwork(NetworkAgentInfo nai) {
567            return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai;
568        }
569
570        public boolean isTypeSupported(int type) {
571            return isNetworkTypeValid(type) && mTypeLists[type] != null;
572        }
573
574        public NetworkAgentInfo getNetworkForType(int type) {
575            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
576                return mTypeLists[type].get(0);
577            } else {
578                return null;
579            }
580        }
581
582        public void add(int type, NetworkAgentInfo nai) {
583            if (!isTypeSupported(type)) {
584                return;  // Invalid network type.
585            }
586            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
587
588            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
589            if (list.contains(nai)) {
590                loge("Attempting to register duplicate agent for type " + type + ": " + nai);
591                return;
592            }
593
594            if (list.isEmpty() || isDefaultNetwork(nai)) {
595                if (VDBG) log("Sending connected broadcast for type " + type +
596                              "isDefaultNetwork=" + isDefaultNetwork(nai));
597                sendLegacyNetworkBroadcast(nai, true, type);
598            }
599            list.add(nai);
600        }
601
602        public void remove(NetworkAgentInfo nai) {
603            if (VDBG) log("Removing agent " + nai);
604            for (int type = 0; type < mTypeLists.length; type++) {
605                ArrayList<NetworkAgentInfo> list = mTypeLists[type];
606                if (list == null || list.isEmpty()) {
607                    continue;
608                }
609
610                boolean wasFirstNetwork = false;
611                if (list.get(0).equals(nai)) {
612                    // This network was the first in the list. Send broadcast.
613                    wasFirstNetwork = true;
614                }
615                list.remove(nai);
616
617                if (wasFirstNetwork || isDefaultNetwork(nai)) {
618                    if (VDBG) log("Sending disconnected broadcast for type " + type +
619                                  "isDefaultNetwork=" + isDefaultNetwork(nai));
620                    sendLegacyNetworkBroadcast(nai, false, type);
621                }
622
623                if (!list.isEmpty() && wasFirstNetwork) {
624                    if (VDBG) log("Other network available for type " + type +
625                                  ", sending connected broadcast");
626                    sendLegacyNetworkBroadcast(list.get(0), false, type);
627                }
628            }
629        }
630    }
631    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
632
633    public ConnectivityService(Context context, INetworkManagementService netd,
634            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
635        // Currently, omitting a NetworkFactory will create one internally
636        // TODO: create here when we have cleaner WiMAX support
637        this(context, netd, statsService, policyManager, null);
638    }
639
640    public ConnectivityService(Context context, INetworkManagementService netManager,
641            INetworkStatsService statsService, INetworkPolicyManager policyManager,
642            NetworkFactory netFactory) {
643        if (DBG) log("ConnectivityService starting up");
644
645        NetworkCapabilities netCap = new NetworkCapabilities();
646        netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
647        netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
648        mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
649        NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
650                NetworkRequestInfo.REQUEST);
651        mNetworkRequests.put(mDefaultRequest, nri);
652
653        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
654        handlerThread.start();
655        mHandler = new InternalHandler(handlerThread.getLooper());
656        mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
657
658        if (netFactory == null) {
659            netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
660        }
661
662        // setup our unique device name
663        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
664            String id = Settings.Secure.getString(context.getContentResolver(),
665                    Settings.Secure.ANDROID_ID);
666            if (id != null && id.length() > 0) {
667                String name = new String("android-").concat(id);
668                SystemProperties.set("net.hostname", name);
669            }
670        }
671
672        // read our default dns server ip
673        String dns = Settings.Global.getString(context.getContentResolver(),
674                Settings.Global.DEFAULT_DNS_SERVER);
675        if (dns == null || dns.length() == 0) {
676            dns = context.getResources().getString(
677                    com.android.internal.R.string.config_default_dns_server);
678        }
679        try {
680            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
681        } catch (IllegalArgumentException e) {
682            loge("Error setting defaultDns using " + dns);
683        }
684
685        mContext = checkNotNull(context, "missing Context");
686        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
687        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
688        mKeyStore = KeyStore.getInstance();
689        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
690
691        try {
692            mPolicyManager.registerListener(mPolicyListener);
693        } catch (RemoteException e) {
694            // ouch, no rules updates means some processes may never get network
695            loge("unable to register INetworkPolicyListener" + e.toString());
696        }
697
698        final PowerManager powerManager = (PowerManager) context.getSystemService(
699                Context.POWER_SERVICE);
700        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
701        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
702                com.android.internal.R.integer.config_networkTransitionTimeout);
703
704        mNetTrackers = new NetworkStateTracker[
705                ConnectivityManager.MAX_NETWORK_TYPE+1];
706        mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
707
708        mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
709        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
710
711        // Load device network attributes from resources
712        String[] raStrings = context.getResources().getStringArray(
713                com.android.internal.R.array.radioAttributes);
714        for (String raString : raStrings) {
715            RadioAttributes r = new RadioAttributes(raString);
716            if (VDBG) log("raString=" + raString + " r=" + r);
717            if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
718                loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
719                continue;
720            }
721            if (mRadioAttributes[r.mType] != null) {
722                loge("Error in radioAttributes - ignoring attempt to redefine type " +
723                        r.mType);
724                continue;
725            }
726            mRadioAttributes[r.mType] = r;
727        }
728
729        // TODO: What is the "correct" way to do determine if this is a wifi only device?
730        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
731        log("wifiOnly=" + wifiOnly);
732        String[] naStrings = context.getResources().getStringArray(
733                com.android.internal.R.array.networkAttributes);
734        for (String naString : naStrings) {
735            try {
736                NetworkConfig n = new NetworkConfig(naString);
737                if (VDBG) log("naString=" + naString + " config=" + n);
738                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
739                    loge("Error in networkAttributes - ignoring attempt to define type " +
740                            n.type);
741                    continue;
742                }
743                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
744                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
745                            n.type);
746                    continue;
747                }
748                if (mNetConfigs[n.type] != null) {
749                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
750                            n.type);
751                    continue;
752                }
753                if (mRadioAttributes[n.radio] == null) {
754                    loge("Error in networkAttributes - ignoring attempt to use undefined " +
755                            "radio " + n.radio + " in network type " + n.type);
756                    continue;
757                }
758                mLegacyTypeTracker.addSupportedType(n.type);
759
760                mNetConfigs[n.type] = n;
761                mNetworksDefined++;
762            } catch(Exception e) {
763                // ignore it - leave the entry null
764            }
765        }
766        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
767
768        mProtectedNetworks = new ArrayList<Integer>();
769        int[] protectedNetworks = context.getResources().getIntArray(
770                com.android.internal.R.array.config_protectedNetworks);
771        for (int p : protectedNetworks) {
772            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
773                mProtectedNetworks.add(p);
774            } else {
775                if (DBG) loge("Ignoring protectedNetwork " + p);
776            }
777        }
778
779        // high priority first
780        mPriorityList = new int[mNetworksDefined];
781        {
782            int insertionPoint = mNetworksDefined-1;
783            int currentLowest = 0;
784            int nextLowest = 0;
785            while (insertionPoint > -1) {
786                for (NetworkConfig na : mNetConfigs) {
787                    if (na == null) continue;
788                    if (na.priority < currentLowest) continue;
789                    if (na.priority > currentLowest) {
790                        if (na.priority < nextLowest || nextLowest == 0) {
791                            nextLowest = na.priority;
792                        }
793                        continue;
794                    }
795                    mPriorityList[insertionPoint--] = na.type;
796                }
797                currentLowest = nextLowest;
798                nextLowest = 0;
799            }
800        }
801
802        mNetRequestersPids =
803                (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
804        for (int i : mPriorityList) {
805            mNetRequestersPids[i] = new ArrayList<Integer>();
806        }
807
808        mFeatureUsers = new ArrayList<FeatureUser>();
809
810        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
811                && SystemProperties.get("ro.build.type").equals("eng");
812
813        // Create and start trackers for hard-coded networks
814        for (int targetNetworkType : mPriorityList) {
815            final NetworkConfig config = mNetConfigs[targetNetworkType];
816            final NetworkStateTracker tracker;
817            try {
818                tracker = netFactory.createTracker(targetNetworkType, config);
819                mNetTrackers[targetNetworkType] = tracker;
820            } catch (IllegalArgumentException e) {
821                Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
822                        + " tracker: " + e);
823                continue;
824            }
825
826            tracker.startMonitoring(context, mTrackerHandler);
827            if (config.isDefault()) {
828                tracker.reconnect();
829            }
830        }
831
832        mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
833
834        //set up the listener for user state for creating user VPNs
835        IntentFilter intentFilter = new IntentFilter();
836        intentFilter.addAction(Intent.ACTION_USER_STARTING);
837        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
838        mContext.registerReceiverAsUser(
839                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
840        mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
841
842        try {
843            mNetd.registerObserver(mTethering);
844            mNetd.registerObserver(mDataActivityObserver);
845            mNetd.registerObserver(mClat);
846        } catch (RemoteException e) {
847            loge("Error registering observer :" + e);
848        }
849
850        if (DBG) {
851            mInetLog = new ArrayList();
852        }
853
854        mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
855        mSettingsObserver.observe(mContext);
856
857        mDataConnectionStats = new DataConnectionStats(mContext);
858        mDataConnectionStats.startMonitoring();
859
860        // start network sampling ..
861        Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
862        mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
863                SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
864
865        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
866        setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
867
868        IntentFilter filter = new IntentFilter();
869        filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
870        mContext.registerReceiver(
871                new BroadcastReceiver() {
872                    @Override
873                    public void onReceive(Context context, Intent intent) {
874                        String action = intent.getAction();
875                        if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
876                            mHandler.sendMessage(mHandler.obtainMessage
877                                    (EVENT_SAMPLE_INTERVAL_ELAPSED));
878                        }
879                    }
880                },
881                new IntentFilter(filter));
882
883        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
884
885        filter = new IntentFilter();
886        filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
887        mContext.registerReceiver(mProvisioningReceiver, filter);
888
889        mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
890
891        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
892    }
893
894    private synchronized int nextNetworkRequestId() {
895        return mNextNetworkRequestId++;
896    }
897
898    private synchronized int nextNetId() {
899        int netId = mNextNetId;
900        if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
901        return netId;
902    }
903
904    /**
905     * Factory that creates {@link NetworkStateTracker} instances using given
906     * {@link NetworkConfig}.
907     *
908     * TODO - this is obsolete and will be deleted.  It's replaced by the
909     * registerNetworkFactory call and protocol.
910     * @Deprecated in favor of registerNetworkFactory dynamic bindings
911     */
912    public interface NetworkFactory {
913        public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
914    }
915
916    private static class DefaultNetworkFactory implements NetworkFactory {
917        private final Context mContext;
918        private final Handler mTrackerHandler;
919
920        public DefaultNetworkFactory(Context context, Handler trackerHandler) {
921            mContext = context;
922            mTrackerHandler = trackerHandler;
923        }
924
925        @Override
926        public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
927            switch (config.radio) {
928                case TYPE_WIMAX:
929                    return makeWimaxStateTracker(mContext, mTrackerHandler);
930                case TYPE_PROXY:
931                    return new ProxyDataTracker();
932                default:
933                    throw new IllegalArgumentException(
934                            "Trying to create a NetworkStateTracker for an unknown radio type: "
935                            + config.radio);
936            }
937        }
938    }
939
940    /**
941     * Loads external WiMAX library and registers as system service, returning a
942     * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
943     * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
944     */
945    private static NetworkStateTracker makeWimaxStateTracker(
946            Context context, Handler trackerHandler) {
947        // Initialize Wimax
948        DexClassLoader wimaxClassLoader;
949        Class wimaxStateTrackerClass = null;
950        Class wimaxServiceClass = null;
951        Class wimaxManagerClass;
952        String wimaxJarLocation;
953        String wimaxLibLocation;
954        String wimaxManagerClassName;
955        String wimaxServiceClassName;
956        String wimaxStateTrackerClassName;
957
958        NetworkStateTracker wimaxStateTracker = null;
959
960        boolean isWimaxEnabled = context.getResources().getBoolean(
961                com.android.internal.R.bool.config_wimaxEnabled);
962
963        if (isWimaxEnabled) {
964            try {
965                wimaxJarLocation = context.getResources().getString(
966                        com.android.internal.R.string.config_wimaxServiceJarLocation);
967                wimaxLibLocation = context.getResources().getString(
968                        com.android.internal.R.string.config_wimaxNativeLibLocation);
969                wimaxManagerClassName = context.getResources().getString(
970                        com.android.internal.R.string.config_wimaxManagerClassname);
971                wimaxServiceClassName = context.getResources().getString(
972                        com.android.internal.R.string.config_wimaxServiceClassname);
973                wimaxStateTrackerClassName = context.getResources().getString(
974                        com.android.internal.R.string.config_wimaxStateTrackerClassname);
975
976                if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
977                wimaxClassLoader =  new DexClassLoader(wimaxJarLocation,
978                        new ContextWrapper(context).getCacheDir().getAbsolutePath(),
979                        wimaxLibLocation, ClassLoader.getSystemClassLoader());
980
981                try {
982                    wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
983                    wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
984                    wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
985                } catch (ClassNotFoundException ex) {
986                    loge("Exception finding Wimax classes: " + ex.toString());
987                    return null;
988                }
989            } catch(Resources.NotFoundException ex) {
990                loge("Wimax Resources does not exist!!! ");
991                return null;
992            }
993
994            try {
995                if (DBG) log("Starting Wimax Service... ");
996
997                Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
998                        (new Class[] {Context.class, Handler.class});
999                wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
1000                        context, trackerHandler);
1001
1002                Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
1003                        (new Class[] {Context.class, wimaxStateTrackerClass});
1004                wmxSrvConst.setAccessible(true);
1005                IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
1006                wmxSrvConst.setAccessible(false);
1007
1008                ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
1009
1010            } catch(Exception ex) {
1011                loge("Exception creating Wimax classes: " + ex.toString());
1012                return null;
1013            }
1014        } else {
1015            loge("Wimax is not enabled or not added to the network attributes!!! ");
1016            return null;
1017        }
1018
1019        return wimaxStateTracker;
1020    }
1021
1022    private int getConnectivityChangeDelay() {
1023        final ContentResolver cr = mContext.getContentResolver();
1024
1025        /** Check system properties for the default value then use secure settings value, if any. */
1026        int defaultDelay = SystemProperties.getInt(
1027                "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
1028                ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
1029        return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
1030                defaultDelay);
1031    }
1032
1033    private boolean teardown(NetworkStateTracker netTracker) {
1034        if (netTracker.teardown()) {
1035            netTracker.setTeardownRequested(true);
1036            return true;
1037        } else {
1038            return false;
1039        }
1040    }
1041
1042    /**
1043     * Check if UID should be blocked from using the network represented by the
1044     * given {@link NetworkStateTracker}.
1045     */
1046    private boolean isNetworkBlocked(int networkType, int uid) {
1047        final boolean networkCostly;
1048        final int uidRules;
1049
1050        LinkProperties lp = getLinkPropertiesForType(networkType);
1051        final String iface = (lp == null ? "" : lp.getInterfaceName());
1052        synchronized (mRulesLock) {
1053            networkCostly = mMeteredIfaces.contains(iface);
1054            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1055        }
1056
1057        if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
1058            return true;
1059        }
1060
1061        // no restrictive rules; network is visible
1062        return false;
1063    }
1064
1065    /**
1066     * Return a filtered {@link NetworkInfo}, potentially marked
1067     * {@link DetailedState#BLOCKED} based on
1068     * {@link #isNetworkBlocked}.
1069     */
1070    private NetworkInfo getFilteredNetworkInfo(int networkType, int uid) {
1071        NetworkInfo info = getNetworkInfoForType(networkType);
1072        return getFilteredNetworkInfo(info, networkType, uid);
1073    }
1074
1075    private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, int networkType, int uid) {
1076        if (isNetworkBlocked(networkType, uid)) {
1077            // network is blocked; clone and override state
1078            info = new NetworkInfo(info);
1079            info.setDetailedState(DetailedState.BLOCKED, null, null);
1080        }
1081        if (mLockdownTracker != null) {
1082            info = mLockdownTracker.augmentNetworkInfo(info);
1083        }
1084        return info;
1085    }
1086
1087    /**
1088     * Return NetworkInfo for the active (i.e., connected) network interface.
1089     * It is assumed that at most one network is active at a time. If more
1090     * than one is active, it is indeterminate which will be returned.
1091     * @return the info for the active network, or {@code null} if none is
1092     * active
1093     */
1094    @Override
1095    public NetworkInfo getActiveNetworkInfo() {
1096        enforceAccessPermission();
1097        final int uid = Binder.getCallingUid();
1098        return getNetworkInfo(mActiveDefaultNetwork, uid);
1099    }
1100
1101    // only called when the default request is satisfied
1102    private void updateActiveDefaultNetwork(NetworkAgentInfo nai) {
1103        if (nai != null) {
1104            mActiveDefaultNetwork = nai.networkInfo.getType();
1105        } else {
1106            mActiveDefaultNetwork = TYPE_NONE;
1107        }
1108    }
1109
1110    /**
1111     * Find the first Provisioning network.
1112     *
1113     * @return NetworkInfo or null if none.
1114     */
1115    private NetworkInfo getProvisioningNetworkInfo() {
1116        enforceAccessPermission();
1117
1118        // Find the first Provisioning Network
1119        NetworkInfo provNi = null;
1120        for (NetworkInfo ni : getAllNetworkInfo()) {
1121            if (ni.isConnectedToProvisioningNetwork()) {
1122                provNi = ni;
1123                break;
1124            }
1125        }
1126        if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
1127        return provNi;
1128    }
1129
1130    /**
1131     * Find the first Provisioning network or the ActiveDefaultNetwork
1132     * if there is no Provisioning network
1133     *
1134     * @return NetworkInfo or null if none.
1135     */
1136    @Override
1137    public NetworkInfo getProvisioningOrActiveNetworkInfo() {
1138        enforceAccessPermission();
1139
1140        NetworkInfo provNi = getProvisioningNetworkInfo();
1141        if (provNi == null) {
1142            final int uid = Binder.getCallingUid();
1143            provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1144        }
1145        if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1146        return provNi;
1147    }
1148
1149    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1150        enforceAccessPermission();
1151        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1152            return getNetworkInfoForType(mActiveDefaultNetwork);
1153        }
1154        return null;
1155    }
1156
1157    @Override
1158    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1159        enforceConnectivityInternalPermission();
1160        return getNetworkInfo(mActiveDefaultNetwork, uid);
1161    }
1162
1163    @Override
1164    public NetworkInfo getNetworkInfo(int networkType) {
1165        enforceAccessPermission();
1166        final int uid = Binder.getCallingUid();
1167        return getNetworkInfo(networkType, uid);
1168    }
1169
1170    private NetworkInfo getNetworkInfo(int networkType, int uid) {
1171        NetworkInfo info = null;
1172        if (isNetworkTypeValid(networkType)) {
1173            if (getNetworkInfoForType(networkType) != null) {
1174                info = getFilteredNetworkInfo(networkType, uid);
1175            }
1176        }
1177        return info;
1178    }
1179
1180    @Override
1181    public NetworkInfo getNetworkInfoForNetwork(Network network) {
1182        enforceAccessPermission();
1183        if (network == null) return null;
1184
1185        final int uid = Binder.getCallingUid();
1186        NetworkAgentInfo nai = null;
1187        synchronized (mNetworkForNetId) {
1188            nai = mNetworkForNetId.get(network.netId);
1189        }
1190        if (nai == null) return null;
1191        synchronized (nai) {
1192            if (nai.networkInfo == null) return null;
1193
1194            return getFilteredNetworkInfo(nai.networkInfo, nai.networkInfo.getType(), uid);
1195        }
1196    }
1197
1198    @Override
1199    public NetworkInfo[] getAllNetworkInfo() {
1200        enforceAccessPermission();
1201        final int uid = Binder.getCallingUid();
1202        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1203        synchronized (mRulesLock) {
1204            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1205                    networkType++) {
1206                if (getNetworkInfoForType(networkType) != null) {
1207                    result.add(getFilteredNetworkInfo(networkType, uid));
1208                }
1209            }
1210        }
1211        return result.toArray(new NetworkInfo[result.size()]);
1212    }
1213
1214    @Override
1215    public Network[] getAllNetworks() {
1216        enforceAccessPermission();
1217        final ArrayList<Network> result = new ArrayList();
1218        synchronized (mNetworkForNetId) {
1219            for (int i = 0; i < mNetworkForNetId.size(); i++) {
1220                result.add(new Network(mNetworkForNetId.valueAt(i).network));
1221            }
1222        }
1223        return result.toArray(new Network[result.size()]);
1224    }
1225
1226    @Override
1227    public boolean isNetworkSupported(int networkType) {
1228        enforceAccessPermission();
1229        return (isNetworkTypeValid(networkType) && (getNetworkInfoForType(networkType) != null));
1230    }
1231
1232    /**
1233     * Return LinkProperties for the active (i.e., connected) default
1234     * network interface.  It is assumed that at most one default network
1235     * is active at a time. If more than one is active, it is indeterminate
1236     * which will be returned.
1237     * @return the ip properties for the active network, or {@code null} if
1238     * none is active
1239     */
1240    @Override
1241    public LinkProperties getActiveLinkProperties() {
1242        return getLinkPropertiesForType(mActiveDefaultNetwork);
1243    }
1244
1245    @Override
1246    public LinkProperties getLinkPropertiesForType(int networkType) {
1247        enforceAccessPermission();
1248        if (isNetworkTypeValid(networkType)) {
1249            return getLinkPropertiesForTypeInternal(networkType);
1250        }
1251        return null;
1252    }
1253
1254    // TODO - this should be ALL networks
1255    @Override
1256    public LinkProperties getLinkProperties(Network network) {
1257        enforceAccessPermission();
1258        NetworkAgentInfo nai = null;
1259        synchronized (mNetworkForNetId) {
1260            nai = mNetworkForNetId.get(network.netId);
1261        }
1262
1263        if (nai != null) {
1264            synchronized (nai) {
1265                return new LinkProperties(nai.linkProperties);
1266            }
1267        }
1268        return null;
1269    }
1270
1271    @Override
1272    public NetworkCapabilities getNetworkCapabilities(Network network) {
1273        enforceAccessPermission();
1274        NetworkAgentInfo nai = null;
1275        synchronized (mNetworkForNetId) {
1276            nai = mNetworkForNetId.get(network.netId);
1277        }
1278        if (nai != null) {
1279            synchronized (nai) {
1280                return new NetworkCapabilities(nai.networkCapabilities);
1281            }
1282        }
1283        return null;
1284    }
1285
1286    @Override
1287    public NetworkState[] getAllNetworkState() {
1288        enforceAccessPermission();
1289        final int uid = Binder.getCallingUid();
1290        final ArrayList<NetworkState> result = Lists.newArrayList();
1291        synchronized (mRulesLock) {
1292            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1293                    networkType++) {
1294                if (getNetworkInfoForType(networkType) != null) {
1295                    final NetworkInfo info = getFilteredNetworkInfo(networkType, uid);
1296                    final LinkProperties lp = getLinkPropertiesForTypeInternal(networkType);
1297                    final NetworkCapabilities netcap = getNetworkCapabilitiesForType(networkType);
1298                    result.add(new NetworkState(info, lp, netcap));
1299                }
1300            }
1301        }
1302        return result.toArray(new NetworkState[result.size()]);
1303    }
1304
1305    private NetworkState getNetworkStateUnchecked(int networkType) {
1306        if (isNetworkTypeValid(networkType)) {
1307            NetworkInfo info = getNetworkInfoForType(networkType);
1308            if (info != null) {
1309                return new NetworkState(info,
1310                        getLinkPropertiesForTypeInternal(networkType),
1311                        getNetworkCapabilitiesForType(networkType));
1312            }
1313        }
1314        return null;
1315    }
1316
1317    @Override
1318    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1319        enforceAccessPermission();
1320
1321        final long token = Binder.clearCallingIdentity();
1322        try {
1323            final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1324            if (state != null) {
1325                try {
1326                    return mPolicyManager.getNetworkQuotaInfo(state);
1327                } catch (RemoteException e) {
1328                }
1329            }
1330            return null;
1331        } finally {
1332            Binder.restoreCallingIdentity(token);
1333        }
1334    }
1335
1336    @Override
1337    public boolean isActiveNetworkMetered() {
1338        enforceAccessPermission();
1339        final long token = Binder.clearCallingIdentity();
1340        try {
1341            return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1342        } finally {
1343            Binder.restoreCallingIdentity(token);
1344        }
1345    }
1346
1347    private boolean isNetworkMeteredUnchecked(int networkType) {
1348        final NetworkState state = getNetworkStateUnchecked(networkType);
1349        if (state != null) {
1350            try {
1351                return mPolicyManager.isNetworkMetered(state);
1352            } catch (RemoteException e) {
1353            }
1354        }
1355        return false;
1356    }
1357
1358    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1359        @Override
1360        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1361            int deviceType = Integer.parseInt(label);
1362            sendDataActivityBroadcast(deviceType, active, tsNanos);
1363        }
1364    };
1365
1366    /**
1367     * Used to notice when the calling process dies so we can self-expire
1368     *
1369     * Also used to know if the process has cleaned up after itself when
1370     * our auto-expire timer goes off.  The timer has a link to an object.
1371     *
1372     */
1373    private class FeatureUser implements IBinder.DeathRecipient {
1374        int mNetworkType;
1375        String mFeature;
1376        IBinder mBinder;
1377        int mPid;
1378        int mUid;
1379        long mCreateTime;
1380
1381        FeatureUser(int type, String feature, IBinder binder) {
1382            super();
1383            mNetworkType = type;
1384            mFeature = feature;
1385            mBinder = binder;
1386            mPid = getCallingPid();
1387            mUid = getCallingUid();
1388            mCreateTime = System.currentTimeMillis();
1389
1390            try {
1391                mBinder.linkToDeath(this, 0);
1392            } catch (RemoteException e) {
1393                binderDied();
1394            }
1395        }
1396
1397        void unlinkDeathRecipient() {
1398            mBinder.unlinkToDeath(this, 0);
1399        }
1400
1401        public void binderDied() {
1402            log("ConnectivityService FeatureUser binderDied(" +
1403                    mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1404                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1405            stopUsingNetworkFeature(this, false);
1406        }
1407
1408        public void expire() {
1409            if (VDBG) {
1410                log("ConnectivityService FeatureUser expire(" +
1411                        mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1412                        (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1413            }
1414            stopUsingNetworkFeature(this, false);
1415        }
1416
1417        public boolean isSameUser(FeatureUser u) {
1418            if (u == null) return false;
1419
1420            return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1421        }
1422
1423        public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1424            if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1425                TextUtils.equals(mFeature, feature)) {
1426                return true;
1427            }
1428            return false;
1429        }
1430
1431        public String toString() {
1432            return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1433                    (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1434        }
1435    }
1436
1437    // javadoc from interface
1438    public int startUsingNetworkFeature(int networkType, String feature,
1439            IBinder binder) {
1440        long startTime = 0;
1441        if (DBG) {
1442            startTime = SystemClock.elapsedRealtime();
1443        }
1444        if (VDBG) {
1445            log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1446                    + Binder.getCallingUid());
1447        }
1448        enforceChangePermission();
1449        try {
1450            if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1451                    mNetConfigs[networkType] == null) {
1452                return PhoneConstants.APN_REQUEST_FAILED;
1453            }
1454
1455            FeatureUser f = new FeatureUser(networkType, feature, binder);
1456
1457            // TODO - move this into individual networktrackers
1458            int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1459
1460            if (mLockdownEnabled) {
1461                // Since carrier APNs usually aren't available from VPN
1462                // endpoint, mark them as unavailable.
1463                return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1464            }
1465
1466            if (mProtectedNetworks.contains(usedNetworkType)) {
1467                enforceConnectivityInternalPermission();
1468            }
1469
1470            // if UID is restricted, don't allow them to bring up metered APNs
1471            final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1472            final int uidRules;
1473            synchronized (mRulesLock) {
1474                uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1475            }
1476            if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1477                return PhoneConstants.APN_REQUEST_FAILED;
1478            }
1479
1480            NetworkStateTracker network = mNetTrackers[usedNetworkType];
1481            if (network != null) {
1482                Integer currentPid = new Integer(getCallingPid());
1483                if (usedNetworkType != networkType) {
1484                    NetworkInfo ni = network.getNetworkInfo();
1485
1486                    if (ni.isAvailable() == false) {
1487                        if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1488                            if (DBG) log("special network not available ni=" + ni.getTypeName());
1489                            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1490                        } else {
1491                            // else make the attempt anyway - probably giving REQUEST_STARTED below
1492                            if (DBG) {
1493                                log("special network not available, but try anyway ni=" +
1494                                        ni.getTypeName());
1495                            }
1496                        }
1497                    }
1498
1499                    int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1500
1501                    synchronized(this) {
1502                        boolean addToList = true;
1503                        if (restoreTimer < 0) {
1504                            // In case there is no timer is specified for the feature,
1505                            // make sure we don't add duplicate entry with the same request.
1506                            for (FeatureUser u : mFeatureUsers) {
1507                                if (u.isSameUser(f)) {
1508                                    // Duplicate user is found. Do not add.
1509                                    addToList = false;
1510                                    break;
1511                                }
1512                            }
1513                        }
1514
1515                        if (addToList) mFeatureUsers.add(f);
1516                        if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1517                            // this gets used for per-pid dns when connected
1518                            mNetRequestersPids[usedNetworkType].add(currentPid);
1519                        }
1520                    }
1521
1522                    if (restoreTimer >= 0) {
1523                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
1524                                EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1525                    }
1526
1527                    if ((ni.isConnectedOrConnecting() == true) &&
1528                            !network.isTeardownRequested()) {
1529                        if (ni.isConnected() == true) {
1530                            final long token = Binder.clearCallingIdentity();
1531                            try {
1532                                // add the pid-specific dns
1533                                handleDnsConfigurationChange(usedNetworkType);
1534                                if (VDBG) log("special network already active");
1535                            } finally {
1536                                Binder.restoreCallingIdentity(token);
1537                            }
1538                            return PhoneConstants.APN_ALREADY_ACTIVE;
1539                        }
1540                        if (VDBG) log("special network already connecting");
1541                        return PhoneConstants.APN_REQUEST_STARTED;
1542                    }
1543
1544                    // check if the radio in play can make another contact
1545                    // assume if cannot for now
1546
1547                    if (DBG) {
1548                        log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1549                                feature);
1550                    }
1551                    if (network.reconnect()) {
1552                        if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
1553                        return PhoneConstants.APN_REQUEST_STARTED;
1554                    } else {
1555                        if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
1556                        return PhoneConstants.APN_REQUEST_FAILED;
1557                    }
1558                } else {
1559                    // need to remember this unsupported request so we respond appropriately on stop
1560                    synchronized(this) {
1561                        mFeatureUsers.add(f);
1562                        if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1563                            // this gets used for per-pid dns when connected
1564                            mNetRequestersPids[usedNetworkType].add(currentPid);
1565                        }
1566                    }
1567                    if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
1568                    return -1;
1569                }
1570            }
1571            if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
1572            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1573         } finally {
1574            if (DBG) {
1575                final long execTime = SystemClock.elapsedRealtime() - startTime;
1576                if (execTime > 250) {
1577                    loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1578                } else {
1579                    if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1580                }
1581            }
1582         }
1583    }
1584
1585    // javadoc from interface
1586    public int stopUsingNetworkFeature(int networkType, String feature) {
1587        enforceChangePermission();
1588
1589        int pid = getCallingPid();
1590        int uid = getCallingUid();
1591
1592        FeatureUser u = null;
1593        boolean found = false;
1594
1595        synchronized(this) {
1596            for (FeatureUser x : mFeatureUsers) {
1597                if (x.isSameUser(pid, uid, networkType, feature)) {
1598                    u = x;
1599                    found = true;
1600                    break;
1601                }
1602            }
1603        }
1604        if (found && u != null) {
1605            if (VDBG) log("stopUsingNetworkFeature: X");
1606            // stop regardless of how many other time this proc had called start
1607            return stopUsingNetworkFeature(u, true);
1608        } else {
1609            // none found!
1610            if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
1611            return 1;
1612        }
1613    }
1614
1615    private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1616        int networkType = u.mNetworkType;
1617        String feature = u.mFeature;
1618        int pid = u.mPid;
1619        int uid = u.mUid;
1620
1621        NetworkStateTracker tracker = null;
1622        boolean callTeardown = false;  // used to carry our decision outside of sync block
1623
1624        if (VDBG) {
1625            log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1626        }
1627
1628        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1629            if (DBG) {
1630                log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1631                        ", net is invalid");
1632            }
1633            return -1;
1634        }
1635
1636        // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1637        // sync block
1638        synchronized(this) {
1639            // check if this process still has an outstanding start request
1640            if (!mFeatureUsers.contains(u)) {
1641                if (VDBG) {
1642                    log("stopUsingNetworkFeature: this process has no outstanding requests" +
1643                        ", ignoring");
1644                }
1645                return 1;
1646            }
1647            u.unlinkDeathRecipient();
1648            mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1649            // If we care about duplicate requests, check for that here.
1650            //
1651            // This is done to support the extension of a request - the app
1652            // can request we start the network feature again and renew the
1653            // auto-shutoff delay.  Normal "stop" calls from the app though
1654            // do not pay attention to duplicate requests - in effect the
1655            // API does not refcount and a single stop will counter multiple starts.
1656            if (ignoreDups == false) {
1657                for (FeatureUser x : mFeatureUsers) {
1658                    if (x.isSameUser(u)) {
1659                        if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1660                        return 1;
1661                    }
1662                }
1663            }
1664
1665            // TODO - move to individual network trackers
1666            int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1667
1668            tracker =  mNetTrackers[usedNetworkType];
1669            if (tracker == null) {
1670                if (DBG) {
1671                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1672                            " no known tracker for used net type " + usedNetworkType);
1673                }
1674                return -1;
1675            }
1676            if (usedNetworkType != networkType) {
1677                Integer currentPid = new Integer(pid);
1678                mNetRequestersPids[usedNetworkType].remove(currentPid);
1679
1680                final long token = Binder.clearCallingIdentity();
1681                try {
1682                    reassessPidDns(pid, true);
1683                } finally {
1684                    Binder.restoreCallingIdentity(token);
1685                }
1686                flushVmDnsCache();
1687                if (mNetRequestersPids[usedNetworkType].size() != 0) {
1688                    if (VDBG) {
1689                        log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1690                                " others still using it");
1691                    }
1692                    return 1;
1693                }
1694                callTeardown = true;
1695            } else {
1696                if (DBG) {
1697                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1698                            " not a known feature - dropping");
1699                }
1700            }
1701        }
1702
1703        if (callTeardown) {
1704            if (DBG) {
1705                log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1706            }
1707            tracker.teardown();
1708            return 1;
1709        } else {
1710            return -1;
1711        }
1712    }
1713
1714    /**
1715     * Check if the address falls into any of currently running VPN's route's.
1716     */
1717    private boolean isAddressUnderVpn(InetAddress address) {
1718        synchronized (mVpns) {
1719            synchronized (mRoutesLock) {
1720                int uid = UserHandle.getCallingUserId();
1721                Vpn vpn = mVpns.get(uid);
1722                if (vpn == null) {
1723                    return false;
1724                }
1725
1726                // Check if an exemption exists for this address.
1727                for (LinkAddress destination : mExemptAddresses) {
1728                    if (!NetworkUtils.addressTypeMatches(address, destination.getAddress())) {
1729                        continue;
1730                    }
1731
1732                    int prefix = destination.getPrefixLength();
1733                    InetAddress addrMasked = NetworkUtils.getNetworkPart(address, prefix);
1734                    InetAddress destMasked = NetworkUtils.getNetworkPart(destination.getAddress(),
1735                            prefix);
1736
1737                    if (addrMasked.equals(destMasked)) {
1738                        return false;
1739                    }
1740                }
1741
1742                // Finally check if the address is covered by the VPN.
1743                return vpn.isAddressCovered(address);
1744            }
1745        }
1746    }
1747
1748    /**
1749     * @deprecated use requestRouteToHostAddress instead
1750     *
1751     * Ensure that a network route exists to deliver traffic to the specified
1752     * host via the specified network interface.
1753     * @param networkType the type of the network over which traffic to the
1754     * specified host is to be routed
1755     * @param hostAddress the IP address of the host to which the route is
1756     * desired
1757     * @return {@code true} on success, {@code false} on failure
1758     */
1759    public boolean requestRouteToHost(int networkType, int hostAddress, String packageName) {
1760        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1761
1762        if (inetAddress == null) {
1763            return false;
1764        }
1765
1766        return requestRouteToHostAddress(networkType, inetAddress.getAddress(), packageName);
1767    }
1768
1769    /**
1770     * Ensure that a network route exists to deliver traffic to the specified
1771     * host via the specified network interface.
1772     * @param networkType the type of the network over which traffic to the
1773     * specified host is to be routed
1774     * @param hostAddress the IP address of the host to which the route is
1775     * desired
1776     * @return {@code true} on success, {@code false} on failure
1777     */
1778    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
1779            String packageName) {
1780        enforceChangePermission();
1781        if (mProtectedNetworks.contains(networkType)) {
1782            enforceConnectivityInternalPermission();
1783        }
1784        boolean exempt;
1785        InetAddress addr;
1786        try {
1787            addr = InetAddress.getByAddress(hostAddress);
1788        } catch (UnknownHostException e) {
1789            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1790            return false;
1791        }
1792        // System apps may request routes bypassing the VPN to keep other networks working.
1793        if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1794            exempt = true;
1795        } else {
1796            mAppOpsManager.checkPackage(Binder.getCallingUid(), packageName);
1797            try {
1798                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName,
1799                        0);
1800                exempt = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
1801            } catch (NameNotFoundException e) {
1802                throw new IllegalArgumentException("Failed to find calling package details", e);
1803            }
1804        }
1805
1806        // Non-exempt routeToHost's can only be added if the host is not covered by the VPN.
1807        // This can be either because the VPN's routes do not cover the destination or a
1808        // system application added an exemption that covers this destination.
1809        if (!exempt && isAddressUnderVpn(addr)) {
1810            return false;
1811        }
1812
1813        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1814            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1815            return false;
1816        }
1817
1818        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1819        if (nai == null) {
1820            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1821                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1822            } else {
1823                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1824            }
1825            return false;
1826        }
1827        DetailedState netState;
1828        synchronized (nai) {
1829            netState = nai.networkInfo.getDetailedState();
1830        }
1831
1832        if ((netState != DetailedState.CONNECTED &&
1833                netState != DetailedState.CAPTIVE_PORTAL_CHECK)) {
1834            if (VDBG) {
1835                log("requestRouteToHostAddress on down network "
1836                        + "(" + networkType + ") - dropped"
1837                        + " netState=" + netState);
1838            }
1839            return false;
1840        }
1841        final int uid = Binder.getCallingUid();
1842        final long token = Binder.clearCallingIdentity();
1843        try {
1844            LinkProperties lp = null;
1845            int netId = INVALID_NET_ID;
1846            synchronized (nai) {
1847                lp = nai.linkProperties;
1848                netId = nai.network.netId;
1849            }
1850            boolean ok = modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt, netId, uid);
1851            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1852            return ok;
1853        } finally {
1854            Binder.restoreCallingIdentity(token);
1855        }
1856    }
1857
1858    private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1859            boolean exempt, int netId) {
1860        return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt, netId, false, UID_UNUSED);
1861    }
1862
1863    private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable, int netId) {
1864        return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT, netId, false, UID_UNUSED);
1865    }
1866
1867    private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1868            boolean toDefaultTable, boolean exempt, int netId, int uid) {
1869        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1870        if (bestRoute == null) {
1871            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1872        } else {
1873            String iface = bestRoute.getInterface();
1874            if (bestRoute.getGateway().equals(addr)) {
1875                // if there is no better route, add the implied hostroute for our gateway
1876                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1877            } else {
1878                // if we will connect to this through another route, add a direct route
1879                // to it's gateway
1880                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1881            }
1882        }
1883        return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt, netId, true, uid);
1884    }
1885
1886    /*
1887     * TODO: Clean all this stuff up. Once we have UID-based routing, stuff will break due to
1888     *       incorrect tracking of mAddedRoutes, so a cleanup becomes necessary and urgent. But at
1889     *       the same time, there'll be no more need to track mAddedRoutes or mExemptAddresses,
1890     *       or even have the concept of an exempt address, or do things like "selectBestRoute", or
1891     *       determine "default" vs "secondary" table, etc., so the cleanup becomes possible.
1892     */
1893    private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1894            boolean toDefaultTable, boolean exempt, int netId, boolean legacy, int uid) {
1895        if ((lp == null) || (r == null)) {
1896            if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1897            return false;
1898        }
1899
1900        if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1901            loge("Error modifying route - too much recursion");
1902            return false;
1903        }
1904
1905        String ifaceName = r.getInterface();
1906        if(ifaceName == null) {
1907            loge("Error modifying route - no interface name");
1908            return false;
1909        }
1910        if (r.hasGateway()) {
1911            RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1912            if (bestRoute != null) {
1913                if (bestRoute.getGateway().equals(r.getGateway())) {
1914                    // if there is no better route, add the implied hostroute for our gateway
1915                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1916                } else {
1917                    // if we will connect to our gateway through another route, add a direct
1918                    // route to it's gateway
1919                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1920                                                        bestRoute.getGateway(),
1921                                                        ifaceName);
1922                }
1923                modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt, netId,
1924                        legacy, uid);
1925            }
1926        }
1927        if (doAdd) {
1928            if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1929            try {
1930                if (toDefaultTable) {
1931                    synchronized (mRoutesLock) {
1932                        // only track default table - only one apps can effect
1933                        mAddedRoutes.add(r);
1934                        if (legacy) {
1935                            mNetd.addLegacyRouteForNetId(netId, r, uid);
1936                        } else {
1937                            mNetd.addRoute(netId, r);
1938                        }
1939                        if (exempt) {
1940                            LinkAddress dest = r.getDestinationLinkAddress();
1941                            if (!mExemptAddresses.contains(dest)) {
1942                                mNetd.setHostExemption(dest);
1943                                mExemptAddresses.add(dest);
1944                            }
1945                        }
1946                    }
1947                } else {
1948                    if (legacy) {
1949                        mNetd.addLegacyRouteForNetId(netId, r, uid);
1950                    } else {
1951                        mNetd.addRoute(netId, r);
1952                    }
1953                }
1954            } catch (Exception e) {
1955                // never crash - catch them all
1956                if (DBG) loge("Exception trying to add a route: " + e);
1957                return false;
1958            }
1959        } else {
1960            // if we remove this one and there are no more like it, then refcount==0 and
1961            // we can remove it from the table
1962            if (toDefaultTable) {
1963                synchronized (mRoutesLock) {
1964                    mAddedRoutes.remove(r);
1965                    if (mAddedRoutes.contains(r) == false) {
1966                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1967                        try {
1968                            if (legacy) {
1969                                mNetd.removeLegacyRouteForNetId(netId, r, uid);
1970                            } else {
1971                                mNetd.removeRoute(netId, r);
1972                            }
1973                            LinkAddress dest = r.getDestinationLinkAddress();
1974                            if (mExemptAddresses.contains(dest)) {
1975                                mNetd.clearHostExemption(dest);
1976                                mExemptAddresses.remove(dest);
1977                            }
1978                        } catch (Exception e) {
1979                            // never crash - catch them all
1980                            if (VDBG) loge("Exception trying to remove a route: " + e);
1981                            return false;
1982                        }
1983                    } else {
1984                        if (VDBG) log("not removing " + r + " as it's still in use");
1985                    }
1986                }
1987            } else {
1988                if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1989                try {
1990                    if (legacy) {
1991                        mNetd.removeLegacyRouteForNetId(netId, r, uid);
1992                    } else {
1993                        mNetd.removeRoute(netId, r);
1994                    }
1995                } catch (Exception e) {
1996                    // never crash - catch them all
1997                    if (VDBG) loge("Exception trying to remove a route: " + e);
1998                    return false;
1999                }
2000            }
2001        }
2002        return true;
2003    }
2004
2005    public void setDataDependency(int networkType, boolean met) {
2006        enforceConnectivityInternalPermission();
2007
2008        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
2009                (met ? ENABLED : DISABLED), networkType));
2010    }
2011
2012    private void handleSetDependencyMet(int networkType, boolean met) {
2013        if (mNetTrackers[networkType] != null) {
2014            if (DBG) {
2015                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
2016            }
2017            mNetTrackers[networkType].setDependencyMet(met);
2018        }
2019    }
2020
2021    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
2022        @Override
2023        public void onUidRulesChanged(int uid, int uidRules) {
2024            // caller is NPMS, since we only register with them
2025            if (LOGD_RULES) {
2026                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
2027            }
2028
2029            synchronized (mRulesLock) {
2030                // skip update when we've already applied rules
2031                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
2032                if (oldRules == uidRules) return;
2033
2034                mUidRules.put(uid, uidRules);
2035            }
2036
2037            // TODO: notify UID when it has requested targeted updates
2038        }
2039
2040        @Override
2041        public void onMeteredIfacesChanged(String[] meteredIfaces) {
2042            // caller is NPMS, since we only register with them
2043            if (LOGD_RULES) {
2044                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
2045            }
2046
2047            synchronized (mRulesLock) {
2048                mMeteredIfaces.clear();
2049                for (String iface : meteredIfaces) {
2050                    mMeteredIfaces.add(iface);
2051                }
2052            }
2053        }
2054
2055        @Override
2056        public void onRestrictBackgroundChanged(boolean restrictBackground) {
2057            // caller is NPMS, since we only register with them
2058            if (LOGD_RULES) {
2059                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
2060            }
2061
2062            // kick off connectivity change broadcast for active network, since
2063            // global background policy change is radical.
2064            final int networkType = mActiveDefaultNetwork;
2065            if (isNetworkTypeValid(networkType)) {
2066                final NetworkStateTracker tracker = mNetTrackers[networkType];
2067                if (tracker != null) {
2068                    final NetworkInfo info = tracker.getNetworkInfo();
2069                    if (info != null && info.isConnected()) {
2070                        sendConnectedBroadcast(info);
2071                    }
2072                }
2073            }
2074        }
2075    };
2076
2077    @Override
2078    public void setPolicyDataEnable(int networkType, boolean enabled) {
2079        // only someone like NPMS should only be calling us
2080        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2081
2082        mHandler.sendMessage(mHandler.obtainMessage(
2083                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
2084    }
2085
2086    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
2087   // TODO - handle this passing to factories
2088//        if (isNetworkTypeValid(networkType)) {
2089//            final NetworkStateTracker tracker = mNetTrackers[networkType];
2090//            if (tracker != null) {
2091//                tracker.setPolicyDataEnable(enabled);
2092//            }
2093//        }
2094    }
2095
2096    private void enforceAccessPermission() {
2097        mContext.enforceCallingOrSelfPermission(
2098                android.Manifest.permission.ACCESS_NETWORK_STATE,
2099                "ConnectivityService");
2100    }
2101
2102    private void enforceChangePermission() {
2103        mContext.enforceCallingOrSelfPermission(
2104                android.Manifest.permission.CHANGE_NETWORK_STATE,
2105                "ConnectivityService");
2106    }
2107
2108    // TODO Make this a special check when it goes public
2109    private void enforceTetherChangePermission() {
2110        mContext.enforceCallingOrSelfPermission(
2111                android.Manifest.permission.CHANGE_NETWORK_STATE,
2112                "ConnectivityService");
2113    }
2114
2115    private void enforceTetherAccessPermission() {
2116        mContext.enforceCallingOrSelfPermission(
2117                android.Manifest.permission.ACCESS_NETWORK_STATE,
2118                "ConnectivityService");
2119    }
2120
2121    private void enforceConnectivityInternalPermission() {
2122        mContext.enforceCallingOrSelfPermission(
2123                android.Manifest.permission.CONNECTIVITY_INTERNAL,
2124                "ConnectivityService");
2125    }
2126
2127    private void enforceMarkNetworkSocketPermission() {
2128        //Media server special case
2129        if (Binder.getCallingUid() == Process.MEDIA_UID) {
2130            return;
2131        }
2132        mContext.enforceCallingOrSelfPermission(
2133                android.Manifest.permission.MARK_NETWORK_SOCKET,
2134                "ConnectivityService");
2135    }
2136
2137    /**
2138     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
2139     * network, we ignore it. If it is for the active network, we send out a
2140     * broadcast. But first, we check whether it might be possible to connect
2141     * to a different network.
2142     * @param info the {@code NetworkInfo} for the network
2143     */
2144    private void handleDisconnect(NetworkInfo info) {
2145
2146        int prevNetType = info.getType();
2147
2148        mNetTrackers[prevNetType].setTeardownRequested(false);
2149        int thisNetId = mNetTrackers[prevNetType].getNetwork().netId;
2150
2151        // Remove idletimer previously setup in {@code handleConnect}
2152// Already in place in new function. This is dead code.
2153//        if (mNetConfigs[prevNetType].isDefault()) {
2154//            removeDataActivityTracking(prevNetType);
2155//        }
2156
2157        /*
2158         * If the disconnected network is not the active one, then don't report
2159         * this as a loss of connectivity. What probably happened is that we're
2160         * getting the disconnect for a network that we explicitly disabled
2161         * in accordance with network preference policies.
2162         */
2163        if (!mNetConfigs[prevNetType].isDefault()) {
2164            List<Integer> pids = mNetRequestersPids[prevNetType];
2165            for (Integer pid : pids) {
2166                // will remove them because the net's no longer connected
2167                // need to do this now as only now do we know the pids and
2168                // can properly null things that are no longer referenced.
2169                reassessPidDns(pid.intValue(), false);
2170            }
2171        }
2172
2173        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
2174        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2175        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2176        if (info.isFailover()) {
2177            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2178            info.setFailover(false);
2179        }
2180        if (info.getReason() != null) {
2181            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2182        }
2183        if (info.getExtraInfo() != null) {
2184            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2185                    info.getExtraInfo());
2186        }
2187
2188        if (mNetConfigs[prevNetType].isDefault()) {
2189            tryFailover(prevNetType);
2190            if (mActiveDefaultNetwork != -1) {
2191                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2192                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2193            } else {
2194                mDefaultInetConditionPublished = 0; // we're not connected anymore
2195                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2196            }
2197        }
2198        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2199
2200        // Reset interface if no other connections are using the same interface
2201        boolean doReset = true;
2202        LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
2203        if (linkProperties != null) {
2204            String oldIface = linkProperties.getInterfaceName();
2205            if (TextUtils.isEmpty(oldIface) == false) {
2206                for (NetworkStateTracker networkStateTracker : mNetTrackers) {
2207                    if (networkStateTracker == null) continue;
2208                    NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
2209                    if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
2210                        LinkProperties l = networkStateTracker.getLinkProperties();
2211                        if (l == null) continue;
2212                        if (oldIface.equals(l.getInterfaceName())) {
2213                            doReset = false;
2214                            break;
2215                        }
2216                    }
2217                }
2218            }
2219        }
2220
2221        // do this before we broadcast the change
2222// Already done in new function. This is dead code.
2223//        handleConnectivityChange(prevNetType, doReset);
2224
2225        final Intent immediateIntent = new Intent(intent);
2226        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2227        sendStickyBroadcast(immediateIntent);
2228        sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
2229        /*
2230         * If the failover network is already connected, then immediately send
2231         * out a followup broadcast indicating successful failover
2232         */
2233        if (mActiveDefaultNetwork != -1) {
2234            sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
2235                    getConnectivityChangeDelay());
2236        }
2237        try {
2238//            mNetd.removeNetwork(thisNetId);
2239        } catch (Exception e) {
2240            loge("Exception removing network: " + e);
2241        } finally {
2242            mNetTrackers[prevNetType].setNetId(INVALID_NET_ID);
2243        }
2244    }
2245
2246    private void tryFailover(int prevNetType) {
2247        /*
2248         * If this is a default network, check if other defaults are available.
2249         * Try to reconnect on all available and let them hash it out when
2250         * more than one connects.
2251         */
2252        if (mNetConfigs[prevNetType].isDefault()) {
2253            if (mActiveDefaultNetwork == prevNetType) {
2254                if (DBG) {
2255                    log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2256                }
2257                mActiveDefaultNetwork = -1;
2258                try {
2259                    mNetd.clearDefaultNetId();
2260                } catch (Exception e) {
2261                    loge("Exception clearing default network :" + e);
2262                }
2263            }
2264
2265            // don't signal a reconnect for anything lower or equal priority than our
2266            // current connected default
2267            // TODO - don't filter by priority now - nice optimization but risky
2268//            int currentPriority = -1;
2269//            if (mActiveDefaultNetwork != -1) {
2270//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
2271//            }
2272
2273            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
2274                if (checkType == prevNetType) continue;
2275                if (mNetConfigs[checkType] == null) continue;
2276                if (!mNetConfigs[checkType].isDefault()) continue;
2277                if (mNetTrackers[checkType] == null) continue;
2278
2279// Enabling the isAvailable() optimization caused mobile to not get
2280// selected if it was in the middle of error handling. Specifically
2281// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2282// would not be available and we wouldn't get connected to anything.
2283// So removing the isAvailable() optimization below for now. TODO: This
2284// optimization should work and we need to investigate why it doesn't work.
2285// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2286// complete before it is really complete.
2287
2288//                if (!mNetTrackers[checkType].isAvailable()) continue;
2289
2290//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
2291
2292                NetworkStateTracker checkTracker = mNetTrackers[checkType];
2293                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2294                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2295                    checkInfo.setFailover(true);
2296                    checkTracker.reconnect();
2297                }
2298                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
2299            }
2300        }
2301    }
2302
2303    public void sendConnectedBroadcast(NetworkInfo info) {
2304        enforceConnectivityInternalPermission();
2305        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2306        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2307    }
2308
2309    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
2310        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2311        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
2312    }
2313
2314    private void sendInetConditionBroadcast(NetworkInfo info) {
2315        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2316    }
2317
2318    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2319        if (mLockdownTracker != null) {
2320            info = mLockdownTracker.augmentNetworkInfo(info);
2321        }
2322
2323        Intent intent = new Intent(bcastType);
2324        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2325        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2326        if (info.isFailover()) {
2327            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2328            info.setFailover(false);
2329        }
2330        if (info.getReason() != null) {
2331            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2332        }
2333        if (info.getExtraInfo() != null) {
2334            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2335                    info.getExtraInfo());
2336        }
2337        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2338        return intent;
2339    }
2340
2341    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2342        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2343    }
2344
2345    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2346        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
2347    }
2348
2349    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
2350        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2351        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2352        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
2353        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
2354        final long ident = Binder.clearCallingIdentity();
2355        try {
2356            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2357                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2358        } finally {
2359            Binder.restoreCallingIdentity(ident);
2360        }
2361    }
2362
2363    private void sendStickyBroadcast(Intent intent) {
2364        synchronized(this) {
2365            if (!mSystemReady) {
2366                mInitialBroadcast = new Intent(intent);
2367            }
2368            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2369            if (VDBG) {
2370                log("sendStickyBroadcast: action=" + intent.getAction());
2371            }
2372
2373            final long ident = Binder.clearCallingIdentity();
2374            try {
2375                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2376            } finally {
2377                Binder.restoreCallingIdentity(ident);
2378            }
2379        }
2380    }
2381
2382    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2383        if (delayMs <= 0) {
2384            sendStickyBroadcast(intent);
2385        } else {
2386            if (VDBG) {
2387                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2388                        + intent.getAction());
2389            }
2390            mHandler.sendMessageDelayed(mHandler.obtainMessage(
2391                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2392        }
2393    }
2394
2395    void systemReady() {
2396        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
2397            mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2398        }
2399        loadGlobalProxy();
2400
2401        synchronized(this) {
2402            mSystemReady = true;
2403            if (mInitialBroadcast != null) {
2404                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2405                mInitialBroadcast = null;
2406            }
2407        }
2408        // load the global proxy at startup
2409        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2410
2411        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2412        // for user to unlock device.
2413        if (!updateLockdownVpn()) {
2414            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2415            mContext.registerReceiver(mUserPresentReceiver, filter);
2416        }
2417    }
2418
2419    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2420        @Override
2421        public void onReceive(Context context, Intent intent) {
2422            // Try creating lockdown tracker, since user present usually means
2423            // unlocked keystore.
2424            if (updateLockdownVpn()) {
2425                mContext.unregisterReceiver(this);
2426            }
2427        }
2428    };
2429
2430    private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2431        if (((type != mNetworkPreference)
2432                      && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2433                   || (mNetworkPreference == mActiveDefaultNetwork)) {
2434            return false;
2435        }
2436        return true;
2437    }
2438
2439    private void handleConnect(NetworkInfo info) {
2440        final int newNetType = info.getType();
2441
2442        // snapshot isFailover, because sendConnectedBroadcast() resets it
2443        boolean isFailover = info.isFailover();
2444        final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2445        final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2446
2447        if (VDBG) {
2448            log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2449                    + " isFailover" + isFailover);
2450        }
2451
2452        // if this is a default net and other default is running
2453        // kill the one not preferred
2454        if (mNetConfigs[newNetType].isDefault()) {
2455            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2456                if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2457                   String teardownPolicy = SystemProperties.get("net.teardownPolicy");
2458                   if (TextUtils.equals(teardownPolicy, "keep") == false) {
2459                        // tear down the other
2460                        NetworkStateTracker otherNet =
2461                                mNetTrackers[mActiveDefaultNetwork];
2462                        if (DBG) {
2463                            log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2464                                " teardown");
2465                        }
2466                        if (!teardown(otherNet)) {
2467                            loge("Network declined teardown request");
2468                            teardown(thisNet);
2469                            return;
2470                        }
2471                    } else {
2472                        //TODO - remove
2473                        loge("network teardown skipped due to net.teardownPolicy setting");
2474                    }
2475                } else {
2476                       // don't accept this one
2477                        if (VDBG) {
2478                            log("Not broadcasting CONNECT_ACTION " +
2479                                "to torn down network " + info.getTypeName());
2480                        }
2481                        teardown(thisNet);
2482                        return;
2483                }
2484            }
2485            int thisNetId = nextNetId();
2486            thisNet.setNetId(thisNetId);
2487            try {
2488//                mNetd.createNetwork(thisNetId, thisIface);
2489            } catch (Exception e) {
2490                loge("Exception creating network :" + e);
2491                teardown(thisNet);
2492                return;
2493            }
2494// Already in place in new function. This is dead code.
2495//            setupDataActivityTracking(newNetType);
2496            synchronized (ConnectivityService.this) {
2497                // have a new default network, release the transition wakelock in a second
2498                // if it's held.  The second pause is to allow apps to reconnect over the
2499                // new network
2500                if (mNetTransitionWakeLock.isHeld()) {
2501                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
2502                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2503                            mNetTransitionWakeLockSerialNumber, 0),
2504                            1000);
2505                }
2506            }
2507            mActiveDefaultNetwork = newNetType;
2508            try {
2509                mNetd.setDefaultNetId(thisNetId);
2510            } catch (Exception e) {
2511                loge("Exception setting default network :" + e);
2512            }
2513            // this will cause us to come up initially as unconnected and switching
2514            // to connected after our normal pause unless somebody reports us as reall
2515            // disconnected
2516            mDefaultInetConditionPublished = 0;
2517            mDefaultConnectionSequence++;
2518            mInetConditionChangeInFlight = false;
2519            // Don't do this - if we never sign in stay, grey
2520            //reportNetworkCondition(mActiveDefaultNetwork, 100);
2521            updateNetworkSettings(thisNet);
2522        } else {
2523            int thisNetId = nextNetId();
2524            thisNet.setNetId(thisNetId);
2525            try {
2526//                mNetd.createNetwork(thisNetId, thisIface);
2527            } catch (Exception e) {
2528                loge("Exception creating network :" + e);
2529                teardown(thisNet);
2530                return;
2531            }
2532        }
2533        thisNet.setTeardownRequested(false);
2534// Already in place in new function. This is dead code.
2535//        updateMtuSizeSettings(thisNet);
2536//        handleConnectivityChange(newNetType, false);
2537        sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2538
2539        // notify battery stats service about this network
2540        if (thisIface != null) {
2541            try {
2542                BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2543            } catch (RemoteException e) {
2544                // ignored; service lives in system_server
2545            }
2546        }
2547    }
2548
2549    /** @hide */
2550    @Override
2551    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2552        enforceConnectivityInternalPermission();
2553        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2554//        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2555    }
2556
2557    /**
2558     * Setup data activity tracking for the given network.
2559     *
2560     * Every {@code setupDataActivityTracking} should be paired with a
2561     * {@link #removeDataActivityTracking} for cleanup.
2562     */
2563    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2564        final String iface = networkAgent.linkProperties.getInterfaceName();
2565
2566        final int timeout;
2567        int type = ConnectivityManager.TYPE_NONE;
2568
2569        if (networkAgent.networkCapabilities.hasTransport(
2570                NetworkCapabilities.TRANSPORT_CELLULAR)) {
2571            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2572                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2573                                             5);
2574            type = ConnectivityManager.TYPE_MOBILE;
2575        } else if (networkAgent.networkCapabilities.hasTransport(
2576                NetworkCapabilities.TRANSPORT_WIFI)) {
2577            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2578                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2579                                             0);
2580            type = ConnectivityManager.TYPE_WIFI;
2581        } else {
2582            // do not track any other networks
2583            timeout = 0;
2584        }
2585
2586        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
2587            try {
2588                mNetd.addIdleTimer(iface, timeout, type);
2589            } catch (Exception e) {
2590                // You shall not crash!
2591                loge("Exception in setupDataActivityTracking " + e);
2592            }
2593        }
2594    }
2595
2596    /**
2597     * Remove data activity tracking when network disconnects.
2598     */
2599    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2600        final String iface = networkAgent.linkProperties.getInterfaceName();
2601        final NetworkCapabilities caps = networkAgent.networkCapabilities;
2602
2603        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2604                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
2605            try {
2606                // the call fails silently if no idletimer setup for this interface
2607                mNetd.removeIdleTimer(iface);
2608            } catch (Exception e) {
2609                loge("Exception in removeDataActivityTracking " + e);
2610            }
2611        }
2612    }
2613
2614    /**
2615     * After a change in the connectivity state of a network. We're mainly
2616     * concerned with making sure that the list of DNS servers is set up
2617     * according to which networks are connected, and ensuring that the
2618     * right routing table entries exist.
2619     *
2620     * TODO - delete when we're sure all this functionallity is captured.
2621     */
2622    private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) {
2623        int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2624        boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
2625        if (VDBG) {
2626            log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2627                    + " resetMask=" + resetMask);
2628        }
2629
2630        /*
2631         * If a non-default network is enabled, add the host routes that
2632         * will allow it's DNS servers to be accessed.
2633         */
2634        handleDnsConfigurationChange(netType);
2635
2636        LinkProperties newLp = null;
2637
2638        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2639            newLp = mNetTrackers[netType].getLinkProperties();
2640            if (VDBG) {
2641                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2642                        " doReset=" + doReset + " resetMask=" + resetMask +
2643                        "\n   curLp=" + curLp +
2644                        "\n   newLp=" + newLp);
2645            }
2646
2647            if (curLp != null) {
2648                if (curLp.isIdenticalInterfaceName(newLp)) {
2649                    CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2650                    if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2651                        for (LinkAddress linkAddr : car.removed) {
2652                            if (linkAddr.getAddress() instanceof Inet4Address) {
2653                                resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2654                            }
2655                            if (linkAddr.getAddress() instanceof Inet6Address) {
2656                                resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2657                            }
2658                        }
2659                        if (DBG) {
2660                            log("handleConnectivityChange: addresses changed" +
2661                                    " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2662                                    "\n   car=" + car);
2663                        }
2664                    } else {
2665                        if (VDBG) {
2666                            log("handleConnectivityChange: addresses are the same reset per" +
2667                                   " doReset linkProperty[" + netType + "]:" +
2668                                   " resetMask=" + resetMask);
2669                        }
2670                    }
2671                } else {
2672                    resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2673                    if (DBG) {
2674                        log("handleConnectivityChange: interface not not equivalent reset both" +
2675                                " linkProperty[" + netType + "]:" +
2676                                " resetMask=" + resetMask);
2677                    }
2678                }
2679            }
2680            if (mNetConfigs[netType].isDefault()) {
2681                handleApplyDefaultProxy(newLp.getHttpProxy());
2682            }
2683        } else {
2684            if (VDBG) {
2685                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2686                        " doReset=" + doReset + " resetMask=" + resetMask +
2687                        "\n  curLp=" + curLp +
2688                        "\n  newLp= null");
2689            }
2690        }
2691        mCurrentLinkProperties[netType] = newLp;
2692        boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt,
2693                                        mNetTrackers[netType].getNetwork().netId);
2694
2695        if (resetMask != 0 || resetDns) {
2696            if (VDBG) log("handleConnectivityChange: resetting");
2697            if (curLp != null) {
2698                if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
2699                for (String iface : curLp.getAllInterfaceNames()) {
2700                    if (TextUtils.isEmpty(iface) == false) {
2701                        if (resetMask != 0) {
2702                            if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2703                            NetworkUtils.resetConnections(iface, resetMask);
2704
2705                            // Tell VPN the interface is down. It is a temporary
2706                            // but effective fix to make VPN aware of the change.
2707                            if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2708                                synchronized(mVpns) {
2709                                    for (int i = 0; i < mVpns.size(); i++) {
2710                                        mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2711                                    }
2712                                }
2713                            }
2714                        }
2715                    } else {
2716                        loge("Can't reset connection for type "+netType);
2717                    }
2718                }
2719                if (resetDns) {
2720                    flushVmDnsCache();
2721                    if (VDBG) log("resetting DNS cache for type " + netType);
2722                    try {
2723                        mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId);
2724                    } catch (Exception e) {
2725                        // never crash - catch them all
2726                        if (DBG) loge("Exception resetting dns cache: " + e);
2727                    }
2728                }
2729            }
2730        }
2731
2732        // TODO: Temporary notifying upstread change to Tethering.
2733        //       @see bug/4455071
2734        /** Notify TetheringService if interface name has been changed. */
2735        if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2736                             PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2737            if (isTetheringSupported()) {
2738                mTethering.handleTetherIfaceChange();
2739            }
2740        }
2741    }
2742
2743    /**
2744     * Add and remove routes using the old properties (null if not previously connected),
2745     * new properties (null if becoming disconnected).  May even be double null, which
2746     * is a noop.
2747     * Uses isLinkDefault to determine if default routes should be set or conversely if
2748     * host routes should be set to the dns servers
2749     * returns a boolean indicating the routes changed
2750     */
2751    private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2752            boolean isLinkDefault, boolean exempt, int netId) {
2753        Collection<RouteInfo> routesToAdd = null;
2754        CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2755        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2756        if (curLp != null) {
2757            // check for the delta between the current set and the new
2758            routeDiff = curLp.compareAllRoutes(newLp);
2759            dnsDiff = curLp.compareDnses(newLp);
2760        } else if (newLp != null) {
2761            routeDiff.added = newLp.getAllRoutes();
2762            dnsDiff.added = newLp.getDnsServers();
2763        }
2764
2765        boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2766
2767        for (RouteInfo r : routeDiff.removed) {
2768            if (isLinkDefault || ! r.isDefaultRoute()) {
2769                if (VDBG) log("updateRoutes: default remove route r=" + r);
2770                removeRoute(curLp, r, TO_DEFAULT_TABLE, netId);
2771            }
2772            if (isLinkDefault == false) {
2773                // remove from a secondary route table
2774                removeRoute(curLp, r, TO_SECONDARY_TABLE, netId);
2775            }
2776        }
2777
2778        for (RouteInfo r :  routeDiff.added) {
2779            if (isLinkDefault || ! r.isDefaultRoute()) {
2780                addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId);
2781            } else {
2782                // add to a secondary route table
2783                addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId);
2784
2785                // many radios add a default route even when we don't want one.
2786                // remove the default route unless somebody else has asked for it
2787                String ifaceName = newLp.getInterfaceName();
2788                synchronized (mRoutesLock) {
2789                    if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2790                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2791                        try {
2792                            mNetd.removeRoute(netId, r);
2793                        } catch (Exception e) {
2794                            // never crash - catch them all
2795                            if (DBG) loge("Exception trying to remove a route: " + e);
2796                        }
2797                    }
2798                }
2799            }
2800        }
2801
2802        return routesChanged;
2803    }
2804
2805    /**
2806     * Reads the network specific MTU size from reources.
2807     * and set it on it's iface.
2808     */
2809    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2810        final String iface = newLp.getInterfaceName();
2811        final int mtu = newLp.getMtu();
2812        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2813            if (VDBG) log("identical MTU - not setting");
2814            return;
2815        }
2816
2817        if (mtu < 68 || mtu > 10000) {
2818            loge("Unexpected mtu value: " + mtu + ", " + iface);
2819            return;
2820        }
2821
2822        try {
2823            if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2824            mNetd.setMtu(iface, mtu);
2825        } catch (Exception e) {
2826            Slog.e(TAG, "exception in setMtu()" + e);
2827        }
2828    }
2829
2830    /**
2831     * Reads the network specific TCP buffer sizes from SystemProperties
2832     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2833     * wide use
2834     */
2835    private void updateNetworkSettings(NetworkStateTracker nt) {
2836        String key = nt.getTcpBufferSizesPropName();
2837        String bufferSizes = key == null ? null : SystemProperties.get(key);
2838
2839        if (TextUtils.isEmpty(bufferSizes)) {
2840            if (VDBG) log(key + " not found in system properties. Using defaults");
2841
2842            // Setting to default values so we won't be stuck to previous values
2843            key = "net.tcp.buffersize.default";
2844            bufferSizes = SystemProperties.get(key);
2845        }
2846
2847        // Set values in kernel
2848        if (bufferSizes.length() != 0) {
2849            if (VDBG) {
2850                log("Setting TCP values: [" + bufferSizes
2851                        + "] which comes from [" + key + "]");
2852            }
2853            setBufferSize(bufferSizes);
2854        }
2855
2856        final String defaultRwndKey = "net.tcp.default_init_rwnd";
2857        int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
2858        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
2859            Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
2860        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2861        if (rwndValue != 0) {
2862            SystemProperties.set(sysctlKey, rwndValue.toString());
2863        }
2864    }
2865
2866    /**
2867     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2868     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2869     *
2870     * @param bufferSizes in the format of "readMin, readInitial, readMax,
2871     *        writeMin, writeInitial, writeMax"
2872     */
2873    private void setBufferSize(String bufferSizes) {
2874        try {
2875            String[] values = bufferSizes.split(",");
2876
2877            if (values.length == 6) {
2878              final String prefix = "/sys/kernel/ipv4/tcp_";
2879                FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2880                FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2881                FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2882                FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2883                FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2884                FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2885            } else {
2886                loge("Invalid buffersize string: " + bufferSizes);
2887            }
2888        } catch (IOException e) {
2889            loge("Can't set tcp buffer sizes:" + e);
2890        }
2891    }
2892
2893    /**
2894     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2895     * on the highest priority active net which this process requested.
2896     * If there aren't any, clear it out
2897     */
2898    private void reassessPidDns(int pid, boolean doBump)
2899    {
2900        if (VDBG) log("reassessPidDns for pid " + pid);
2901        Integer myPid = new Integer(pid);
2902        for(int i : mPriorityList) {
2903            if (mNetConfigs[i].isDefault()) {
2904                continue;
2905            }
2906            NetworkStateTracker nt = mNetTrackers[i];
2907            if (nt.getNetworkInfo().isConnected() &&
2908                    !nt.isTeardownRequested()) {
2909                LinkProperties p = nt.getLinkProperties();
2910                if (p == null) continue;
2911                if (mNetRequestersPids[i].contains(myPid)) {
2912                    try {
2913                        // TODO: Reimplement this via local variable in bionic.
2914                        // mNetd.setDnsNetworkForPid(nt.getNetwork().netId, pid);
2915                    } catch (Exception e) {
2916                        Slog.e(TAG, "exception reasseses pid dns: " + e);
2917                    }
2918                    return;
2919                }
2920           }
2921        }
2922        // nothing found - delete
2923        try {
2924            // TODO: Reimplement this via local variable in bionic.
2925            // mNetd.clearDnsNetworkForPid(pid);
2926        } catch (Exception e) {
2927            Slog.e(TAG, "exception clear interface from pid: " + e);
2928        }
2929    }
2930
2931    private void flushVmDnsCache() {
2932        /*
2933         * Tell the VMs to toss their DNS caches
2934         */
2935        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2936        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2937        /*
2938         * Connectivity events can happen before boot has completed ...
2939         */
2940        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2941        final long ident = Binder.clearCallingIdentity();
2942        try {
2943            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2944        } finally {
2945            Binder.restoreCallingIdentity(ident);
2946        }
2947    }
2948
2949    // Caller must grab mDnsLock.
2950    private void updateDnsLocked(String network, int netId,
2951            Collection<InetAddress> dnses, String domains) {
2952        int last = 0;
2953        if (dnses.size() == 0 && mDefaultDns != null) {
2954            dnses = new ArrayList();
2955            dnses.add(mDefaultDns);
2956            if (DBG) {
2957                loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2958            }
2959        }
2960
2961        try {
2962            mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains);
2963
2964            for (InetAddress dns : dnses) {
2965                ++last;
2966                String key = "net.dns" + last;
2967                String value = dns.getHostAddress();
2968                SystemProperties.set(key, value);
2969            }
2970            for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2971                String key = "net.dns" + i;
2972                SystemProperties.set(key, "");
2973            }
2974            mNumDnsEntries = last;
2975        } catch (Exception e) {
2976            loge("exception setting default dns interface: " + e);
2977        }
2978    }
2979
2980    private void handleDnsConfigurationChange(int netType) {
2981        // add default net's dns entries
2982        NetworkStateTracker nt = mNetTrackers[netType];
2983        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2984            LinkProperties p = nt.getLinkProperties();
2985            if (p == null) return;
2986            Collection<InetAddress> dnses = p.getDnsServers();
2987            int netId = nt.getNetwork().netId;
2988            if (mNetConfigs[netType].isDefault()) {
2989                String network = nt.getNetworkInfo().getTypeName();
2990                synchronized (mDnsLock) {
2991                    updateDnsLocked(network, netId, dnses, p.getDomains());
2992                }
2993            } else {
2994                try {
2995                    mNetd.setDnsServersForNetwork(netId,
2996                            NetworkUtils.makeStrings(dnses), p.getDomains());
2997                } catch (Exception e) {
2998                    if (DBG) loge("exception setting dns servers: " + e);
2999                }
3000                // set per-pid dns for attached secondary nets
3001                List<Integer> pids = mNetRequestersPids[netType];
3002                for (Integer pid : pids) {
3003                    try {
3004                        // TODO: Reimplement this via local variable in bionic.
3005                        // mNetd.setDnsNetworkForPid(netId, pid);
3006                    } catch (Exception e) {
3007                        Slog.e(TAG, "exception setting interface for pid: " + e);
3008                    }
3009                }
3010            }
3011            flushVmDnsCache();
3012        }
3013    }
3014
3015    @Override
3016    public int getRestoreDefaultNetworkDelay(int networkType) {
3017        String restoreDefaultNetworkDelayStr = SystemProperties.get(
3018                NETWORK_RESTORE_DELAY_PROP_NAME);
3019        if(restoreDefaultNetworkDelayStr != null &&
3020                restoreDefaultNetworkDelayStr.length() != 0) {
3021            try {
3022                return Integer.valueOf(restoreDefaultNetworkDelayStr);
3023            } catch (NumberFormatException e) {
3024            }
3025        }
3026        // if the system property isn't set, use the value for the apn type
3027        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3028
3029        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
3030                (mNetConfigs[networkType] != null)) {
3031            ret = mNetConfigs[networkType].restoreTime;
3032        }
3033        return ret;
3034    }
3035
3036    @Override
3037    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
3038        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
3039        if (mContext.checkCallingOrSelfPermission(
3040                android.Manifest.permission.DUMP)
3041                != PackageManager.PERMISSION_GRANTED) {
3042            pw.println("Permission Denial: can't dump ConnectivityService " +
3043                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
3044                    Binder.getCallingUid());
3045            return;
3046        }
3047
3048        pw.println("NetworkFactories for:");
3049        pw.increaseIndent();
3050        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3051            pw.println(nfi.name);
3052        }
3053        pw.decreaseIndent();
3054        pw.println();
3055
3056        NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3057        pw.print("Active default network: ");
3058        if (defaultNai == null) {
3059            pw.println("none");
3060        } else {
3061            pw.println(defaultNai.network.netId);
3062        }
3063        pw.println();
3064
3065        pw.println("Current Networks:");
3066        pw.increaseIndent();
3067        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3068            pw.println(nai.toString());
3069            pw.increaseIndent();
3070            pw.println("Requests:");
3071            pw.increaseIndent();
3072            for (int i = 0; i < nai.networkRequests.size(); i++) {
3073                pw.println(nai.networkRequests.valueAt(i).toString());
3074            }
3075            pw.decreaseIndent();
3076            pw.println("Lingered:");
3077            pw.increaseIndent();
3078            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
3079            pw.decreaseIndent();
3080            pw.decreaseIndent();
3081        }
3082        pw.decreaseIndent();
3083        pw.println();
3084
3085        pw.println("Network Requests:");
3086        pw.increaseIndent();
3087        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3088            pw.println(nri.toString());
3089        }
3090        pw.println();
3091        pw.decreaseIndent();
3092
3093        synchronized (this) {
3094            pw.println("NetworkTranstionWakeLock is currently " +
3095                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
3096            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
3097        }
3098        pw.println();
3099
3100        mTethering.dump(fd, pw, args);
3101
3102        if (mInetLog != null) {
3103            pw.println();
3104            pw.println("Inet condition reports:");
3105            pw.increaseIndent();
3106            for(int i = 0; i < mInetLog.size(); i++) {
3107                pw.println(mInetLog.get(i));
3108            }
3109            pw.decreaseIndent();
3110        }
3111    }
3112
3113    // must be stateless - things change under us.
3114    private class NetworkStateTrackerHandler extends Handler {
3115        public NetworkStateTrackerHandler(Looper looper) {
3116            super(looper);
3117        }
3118
3119        @Override
3120        public void handleMessage(Message msg) {
3121            NetworkInfo info;
3122            switch (msg.what) {
3123                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
3124                    handleAsyncChannelHalfConnect(msg);
3125                    break;
3126                }
3127                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
3128                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3129                    if (nai != null) nai.asyncChannel.disconnect();
3130                    break;
3131                }
3132                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
3133                    handleAsyncChannelDisconnected(msg);
3134                    break;
3135                }
3136                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3137                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3138                    if (nai == null) {
3139                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
3140                    } else {
3141                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
3142                    }
3143                    break;
3144                }
3145                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3146                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3147                    if (nai == null) {
3148                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
3149                    } else {
3150                        if (VDBG) log("Update of Linkproperties for " + nai.name());
3151                        LinkProperties oldLp = nai.linkProperties;
3152                        synchronized (nai) {
3153                            nai.linkProperties = (LinkProperties)msg.obj;
3154                        }
3155                        updateLinkProperties(nai, oldLp);
3156                    }
3157                    break;
3158                }
3159                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3160                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3161                    if (nai == null) {
3162                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
3163                        break;
3164                    }
3165                    info = (NetworkInfo) msg.obj;
3166                    updateNetworkInfo(nai, info);
3167                    break;
3168                }
3169                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3170                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3171                    if (nai == null) {
3172                        loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
3173                        break;
3174                    }
3175                    Integer score = (Integer) msg.obj;
3176                    if (score != null) updateNetworkScore(nai, score.intValue());
3177                    break;
3178                }
3179                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
3180                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3181                    if (nai == null) {
3182                        loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
3183                        break;
3184                    }
3185                    try {
3186                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
3187                    } catch (RemoteException e) {
3188                    }
3189                    break;
3190                }
3191                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
3192                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3193                    if (nai == null) {
3194                        loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
3195                        break;
3196                    }
3197                    try {
3198                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
3199                    } catch (RemoteException e) {
3200                    }
3201                    break;
3202                }
3203                case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
3204                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
3205                    handleConnectionValidated(nai);
3206                    break;
3207                }
3208                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
3209                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
3210                    handleLingerComplete(nai);
3211                    break;
3212                }
3213                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
3214                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3215                    if (nai == null) {
3216                        loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3217                        break;
3218                    }
3219                    setProvNotificationVisibleIntent(msg.arg1 != 0, nai.networkInfo.getType(),
3220                            nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
3221                    break;
3222                }
3223                case NetworkStateTracker.EVENT_STATE_CHANGED: {
3224                    info = (NetworkInfo) msg.obj;
3225                    NetworkInfo.State state = info.getState();
3226
3227                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
3228                            (state == NetworkInfo.State.DISCONNECTED) ||
3229                            (state == NetworkInfo.State.SUSPENDED)) {
3230                        log("ConnectivityChange for " +
3231                            info.getTypeName() + ": " +
3232                            state + "/" + info.getDetailedState());
3233                    }
3234
3235                    // Since mobile has the notion of a network/apn that can be used for
3236                    // provisioning we need to check every time we're connected as
3237                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
3238                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
3239                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
3240                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
3241                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
3242                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
3243                                        Settings.Global.DEVICE_PROVISIONED, 0))
3244                            && (((state == NetworkInfo.State.CONNECTED)
3245                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
3246                                || info.isConnectedToProvisioningNetwork())) {
3247                        log("ConnectivityChange checkMobileProvisioning for"
3248                                + " TYPE_MOBILE or ProvisioningNetwork");
3249                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
3250                    }
3251
3252                    EventLogTags.writeConnectivityStateChanged(
3253                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
3254
3255                    if (info.isConnectedToProvisioningNetwork()) {
3256                        /**
3257                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
3258                         * for now its an in between network, its a network that
3259                         * is actually a default network but we don't want it to be
3260                         * announced as such to keep background applications from
3261                         * trying to use it. It turns out that some still try so we
3262                         * take the additional step of clearing any default routes
3263                         * to the link that may have incorrectly setup by the lower
3264                         * levels.
3265                         */
3266                        LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
3267                        if (DBG) {
3268                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3269                        }
3270
3271                        // Clear any default routes setup by the radio so
3272                        // any activity by applications trying to use this
3273                        // connection will fail until the provisioning network
3274                        // is enabled.
3275                        for (RouteInfo r : lp.getRoutes()) {
3276                            removeRoute(lp, r, TO_DEFAULT_TABLE,
3277                                        mNetTrackers[info.getType()].getNetwork().netId);
3278                        }
3279                    } else if (state == NetworkInfo.State.DISCONNECTED) {
3280                    } else if (state == NetworkInfo.State.SUSPENDED) {
3281                    } else if (state == NetworkInfo.State.CONNECTED) {
3282                    //    handleConnect(info);
3283                    }
3284                    if (mLockdownTracker != null) {
3285                        mLockdownTracker.onNetworkInfoChanged(info);
3286                    }
3287                    break;
3288                }
3289                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
3290                    info = (NetworkInfo) msg.obj;
3291                    // TODO: Temporary allowing network configuration
3292                    //       change not resetting sockets.
3293                    //       @see bug/4455071
3294                    handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
3295                            false);
3296                    break;
3297                }
3298                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
3299                    info = (NetworkInfo) msg.obj;
3300                    int type = info.getType();
3301                    if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]);
3302                    break;
3303                }
3304            }
3305        }
3306    }
3307
3308    private void handleAsyncChannelHalfConnect(Message msg) {
3309        AsyncChannel ac = (AsyncChannel) msg.obj;
3310        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
3311            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3312                if (VDBG) log("NetworkFactory connected");
3313                // A network factory has connected.  Send it all current NetworkRequests.
3314                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3315                    if (nri.isRequest == false) continue;
3316                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
3317                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
3318                            (nai != null ? nai.currentScore : 0), 0, nri.request);
3319                }
3320            } else {
3321                loge("Error connecting NetworkFactory");
3322                mNetworkFactoryInfos.remove(msg.obj);
3323            }
3324        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
3325            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3326                if (VDBG) log("NetworkAgent connected");
3327                // A network agent has requested a connection.  Establish the connection.
3328                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
3329                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
3330            } else {
3331                loge("Error connecting NetworkAgent");
3332                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
3333                if (nai != null) {
3334                    synchronized (mNetworkForNetId) {
3335                        mNetworkForNetId.remove(nai.network.netId);
3336                    }
3337                    mLegacyTypeTracker.remove(nai);
3338                }
3339            }
3340        }
3341    }
3342    private void handleAsyncChannelDisconnected(Message msg) {
3343        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3344        if (nai != null) {
3345            if (DBG) {
3346                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
3347            }
3348            // A network agent has disconnected.
3349            // Tell netd to clean up the configuration for this network
3350            // (routing rules, DNS, etc).
3351            try {
3352                mNetd.removeNetwork(nai.network.netId);
3353            } catch (Exception e) {
3354                loge("Exception removing network: " + e);
3355            }
3356            // TODO - if we move the logic to the network agent (have them disconnect
3357            // because they lost all their requests or because their score isn't good)
3358            // then they would disconnect organically, report their new state and then
3359            // disconnect the channel.
3360            if (nai.networkInfo.isConnected()) {
3361                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3362                        null, null);
3363            }
3364            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3365            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
3366            mNetworkAgentInfos.remove(msg.replyTo);
3367            updateClat(null, nai.linkProperties, nai);
3368            mLegacyTypeTracker.remove(nai);
3369            synchronized (mNetworkForNetId) {
3370                mNetworkForNetId.remove(nai.network.netId);
3371            }
3372            // Since we've lost the network, go through all the requests that
3373            // it was satisfying and see if any other factory can satisfy them.
3374            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
3375            for (int i = 0; i < nai.networkRequests.size(); i++) {
3376                NetworkRequest request = nai.networkRequests.valueAt(i);
3377                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
3378                if (VDBG) {
3379                    log(" checking request " + request + ", currentNetwork = " +
3380                            (currentNetwork != null ? currentNetwork.name() : "null"));
3381                }
3382                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3383                    mNetworkForRequestId.remove(request.requestId);
3384                    sendUpdatedScoreToFactories(request, 0);
3385                    NetworkAgentInfo alternative = null;
3386                    for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
3387                        NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
3388                        if (existing.networkInfo.isConnected() &&
3389                                request.networkCapabilities.satisfiedByNetworkCapabilities(
3390                                existing.networkCapabilities) &&
3391                                (alternative == null ||
3392                                 alternative.currentScore < existing.currentScore)) {
3393                            alternative = existing;
3394                        }
3395                    }
3396                    if (alternative != null && !toActivate.contains(alternative)) {
3397                        toActivate.add(alternative);
3398                    }
3399                }
3400            }
3401            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
3402                removeDataActivityTracking(nai);
3403                mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
3404                requestNetworkTransitionWakelock(nai.name());
3405            }
3406            for (NetworkAgentInfo networkToActivate : toActivate) {
3407                networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
3408            }
3409        }
3410    }
3411
3412    private void handleRegisterNetworkRequest(Message msg) {
3413        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3414        final NetworkCapabilities newCap = nri.request.networkCapabilities;
3415        int score = 0;
3416
3417        // Check for the best currently alive network that satisfies this request
3418        NetworkAgentInfo bestNetwork = null;
3419        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
3420            if (VDBG) log("handleRegisterNetworkRequest checking " + network.name());
3421            if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
3422                if (VDBG) log("apparently satisfied.  currentScore=" + network.currentScore);
3423                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
3424                    bestNetwork = network;
3425                }
3426            }
3427        }
3428        if (bestNetwork != null) {
3429            if (VDBG) log("using " + bestNetwork.name());
3430            if (nri.isRequest && bestNetwork.networkInfo.isConnected()) {
3431                // Cancel any lingering so the linger timeout doesn't teardown this network
3432                // even though we have a request for it.
3433                bestNetwork.networkLingered.clear();
3434                bestNetwork.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
3435            }
3436            bestNetwork.addRequest(nri.request);
3437            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
3438            int legacyType = nri.request.legacyType;
3439            if (legacyType != TYPE_NONE) {
3440                mLegacyTypeTracker.add(legacyType, bestNetwork);
3441            }
3442            notifyNetworkCallback(bestNetwork, nri);
3443            score = bestNetwork.currentScore;
3444        }
3445        mNetworkRequests.put(nri.request, nri);
3446        if (msg.what == EVENT_REGISTER_NETWORK_REQUEST) {
3447            if (DBG) log("sending new NetworkRequest to factories");
3448            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3449                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
3450                        0, nri.request);
3451            }
3452        }
3453    }
3454
3455    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
3456        NetworkRequestInfo nri = mNetworkRequests.get(request);
3457        if (nri != null) {
3458            if (nri.mUid != callingUid) {
3459                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
3460                return;
3461            }
3462            if (DBG) log("releasing NetworkRequest " + request);
3463            mNetworkRequests.remove(request);
3464            // tell the network currently servicing this that it's no longer interested
3465            NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId);
3466            if (affectedNetwork != null) {
3467                mNetworkForRequestId.remove(nri.request.requestId);
3468                affectedNetwork.networkRequests.remove(nri.request.requestId);
3469                if (VDBG) {
3470                    log(" Removing from current network " + affectedNetwork.name() + ", leaving " +
3471                            affectedNetwork.networkRequests.size() + " requests.");
3472                }
3473            }
3474
3475            if (nri.isRequest) {
3476                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3477                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3478                            nri.request);
3479                }
3480
3481                if (affectedNetwork != null) {
3482                    // check if this network still has live requests - otherwise, tear down
3483                    // TODO - probably push this to the NF/NA
3484                    boolean keep = affectedNetwork.isVPN();
3485                    for (int i = 0; i < affectedNetwork.networkRequests.size() && !keep; i++) {
3486                        NetworkRequest r = affectedNetwork.networkRequests.valueAt(i);
3487                        if (mNetworkRequests.get(r).isRequest) {
3488                            keep = true;
3489                        }
3490                    }
3491                    if (keep == false) {
3492                        if (DBG) log("no live requests for " + affectedNetwork.name() +
3493                                "; disconnecting");
3494                        affectedNetwork.asyncChannel.disconnect();
3495                    }
3496                }
3497            }
3498            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
3499        }
3500    }
3501
3502    private class InternalHandler extends Handler {
3503        public InternalHandler(Looper looper) {
3504            super(looper);
3505        }
3506
3507        @Override
3508        public void handleMessage(Message msg) {
3509            NetworkInfo info;
3510            switch (msg.what) {
3511                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
3512                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
3513                    String causedBy = null;
3514                    synchronized (ConnectivityService.this) {
3515                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3516                                mNetTransitionWakeLock.isHeld()) {
3517                            mNetTransitionWakeLock.release();
3518                            causedBy = mNetTransitionWakeLockCausedBy;
3519                        } else {
3520                            break;
3521                        }
3522                    }
3523                    if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
3524                        log("Failed to find a new network - expiring NetTransition Wakelock");
3525                    } else {
3526                        log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
3527                                " cleared because we found a replacement network");
3528                    }
3529                    break;
3530                }
3531                case EVENT_RESTORE_DEFAULT_NETWORK: {
3532                    FeatureUser u = (FeatureUser)msg.obj;
3533                    u.expire();
3534                    break;
3535                }
3536                case EVENT_INET_CONDITION_CHANGE: {
3537                    int netType = msg.arg1;
3538                    int condition = msg.arg2;
3539                    handleInetConditionChange(netType, condition);
3540                    break;
3541                }
3542                case EVENT_INET_CONDITION_HOLD_END: {
3543                    int netType = msg.arg1;
3544                    int sequence = msg.arg2;
3545                    handleInetConditionHoldEnd(netType, sequence);
3546                    break;
3547                }
3548                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
3549                    handleDeprecatedGlobalHttpProxy();
3550                    break;
3551                }
3552                case EVENT_SET_DEPENDENCY_MET: {
3553                    boolean met = (msg.arg1 == ENABLED);
3554                    handleSetDependencyMet(msg.arg2, met);
3555                    break;
3556                }
3557                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
3558                    Intent intent = (Intent)msg.obj;
3559                    sendStickyBroadcast(intent);
3560                    break;
3561                }
3562                case EVENT_SET_POLICY_DATA_ENABLE: {
3563                    final int networkType = msg.arg1;
3564                    final boolean enabled = msg.arg2 == ENABLED;
3565                    handleSetPolicyDataEnable(networkType, enabled);
3566                    break;
3567                }
3568                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3569                    int tag = mEnableFailFastMobileDataTag.get();
3570                    if (msg.arg1 == tag) {
3571                        MobileDataStateTracker mobileDst =
3572                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3573                        if (mobileDst != null) {
3574                            mobileDst.setEnableFailFastMobileData(msg.arg2);
3575                        }
3576                    } else {
3577                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3578                                + " != tag:" + tag);
3579                    }
3580                    break;
3581                }
3582                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
3583                    handleNetworkSamplingTimeout();
3584                    break;
3585                }
3586                case EVENT_PROXY_HAS_CHANGED: {
3587                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
3588                    break;
3589                }
3590                case EVENT_REGISTER_NETWORK_FACTORY: {
3591                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3592                    break;
3593                }
3594                case EVENT_UNREGISTER_NETWORK_FACTORY: {
3595                    handleUnregisterNetworkFactory((Messenger)msg.obj);
3596                    break;
3597                }
3598                case EVENT_REGISTER_NETWORK_AGENT: {
3599                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3600                    break;
3601                }
3602                case EVENT_REGISTER_NETWORK_REQUEST:
3603                case EVENT_REGISTER_NETWORK_LISTENER: {
3604                    handleRegisterNetworkRequest(msg);
3605                    break;
3606                }
3607                case EVENT_RELEASE_NETWORK_REQUEST: {
3608                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
3609                    break;
3610                }
3611            }
3612        }
3613    }
3614
3615    // javadoc from interface
3616    public int tether(String iface) {
3617        enforceTetherChangePermission();
3618
3619        if (isTetheringSupported()) {
3620            return mTethering.tether(iface);
3621        } else {
3622            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3623        }
3624    }
3625
3626    // javadoc from interface
3627    public int untether(String iface) {
3628        enforceTetherChangePermission();
3629
3630        if (isTetheringSupported()) {
3631            return mTethering.untether(iface);
3632        } else {
3633            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3634        }
3635    }
3636
3637    // javadoc from interface
3638    public int getLastTetherError(String iface) {
3639        enforceTetherAccessPermission();
3640
3641        if (isTetheringSupported()) {
3642            return mTethering.getLastTetherError(iface);
3643        } else {
3644            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3645        }
3646    }
3647
3648    // TODO - proper iface API for selection by property, inspection, etc
3649    public String[] getTetherableUsbRegexs() {
3650        enforceTetherAccessPermission();
3651        if (isTetheringSupported()) {
3652            return mTethering.getTetherableUsbRegexs();
3653        } else {
3654            return new String[0];
3655        }
3656    }
3657
3658    public String[] getTetherableWifiRegexs() {
3659        enforceTetherAccessPermission();
3660        if (isTetheringSupported()) {
3661            return mTethering.getTetherableWifiRegexs();
3662        } else {
3663            return new String[0];
3664        }
3665    }
3666
3667    public String[] getTetherableBluetoothRegexs() {
3668        enforceTetherAccessPermission();
3669        if (isTetheringSupported()) {
3670            return mTethering.getTetherableBluetoothRegexs();
3671        } else {
3672            return new String[0];
3673        }
3674    }
3675
3676    public int setUsbTethering(boolean enable) {
3677        enforceTetherChangePermission();
3678        if (isTetheringSupported()) {
3679            return mTethering.setUsbTethering(enable);
3680        } else {
3681            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3682        }
3683    }
3684
3685    // TODO - move iface listing, queries, etc to new module
3686    // javadoc from interface
3687    public String[] getTetherableIfaces() {
3688        enforceTetherAccessPermission();
3689        return mTethering.getTetherableIfaces();
3690    }
3691
3692    public String[] getTetheredIfaces() {
3693        enforceTetherAccessPermission();
3694        return mTethering.getTetheredIfaces();
3695    }
3696
3697    public String[] getTetheringErroredIfaces() {
3698        enforceTetherAccessPermission();
3699        return mTethering.getErroredIfaces();
3700    }
3701
3702    public String[] getTetheredDhcpRanges() {
3703        enforceConnectivityInternalPermission();
3704        return mTethering.getTetheredDhcpRanges();
3705    }
3706
3707    // if ro.tether.denied = true we default to no tethering
3708    // gservices could set the secure setting to 1 though to enable it on a build where it
3709    // had previously been turned off.
3710    public boolean isTetheringSupported() {
3711        enforceTetherAccessPermission();
3712        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3713        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3714                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3715                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
3716        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3717                mTethering.getTetherableWifiRegexs().length != 0 ||
3718                mTethering.getTetherableBluetoothRegexs().length != 0) &&
3719                mTethering.getUpstreamIfaceTypes().length != 0);
3720    }
3721
3722    // Called when we lose the default network and have no replacement yet.
3723    // This will automatically be cleared after X seconds or a new default network
3724    // becomes CONNECTED, whichever happens first.  The timer is started by the
3725    // first caller and not restarted by subsequent callers.
3726    private void requestNetworkTransitionWakelock(String forWhom) {
3727        int serialNum = 0;
3728        synchronized (this) {
3729            if (mNetTransitionWakeLock.isHeld()) return;
3730            serialNum = ++mNetTransitionWakeLockSerialNumber;
3731            mNetTransitionWakeLock.acquire();
3732            mNetTransitionWakeLockCausedBy = forWhom;
3733        }
3734        mHandler.sendMessageDelayed(mHandler.obtainMessage(
3735                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
3736                mNetTransitionWakeLockTimeout);
3737        return;
3738    }
3739
3740    // 100 percent is full good, 0 is full bad.
3741    public void reportInetCondition(int networkType, int percentage) {
3742        if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3743        mContext.enforceCallingOrSelfPermission(
3744                android.Manifest.permission.STATUS_BAR,
3745                "ConnectivityService");
3746
3747        if (DBG) {
3748            int pid = getCallingPid();
3749            int uid = getCallingUid();
3750            String s = pid + "(" + uid + ") reports inet is " +
3751                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3752                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3753            mInetLog.add(s);
3754            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3755                mInetLog.remove(0);
3756            }
3757        }
3758        mHandler.sendMessage(mHandler.obtainMessage(
3759            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3760    }
3761
3762    public void reportBadNetwork(Network network) {
3763        //TODO
3764    }
3765
3766    private void handleInetConditionChange(int netType, int condition) {
3767        if (mActiveDefaultNetwork == -1) {
3768            if (DBG) log("handleInetConditionChange: no active default network - ignore");
3769            return;
3770        }
3771        if (mActiveDefaultNetwork != netType) {
3772            if (DBG) log("handleInetConditionChange: net=" + netType +
3773                            " != default=" + mActiveDefaultNetwork + " - ignore");
3774            return;
3775        }
3776        if (VDBG) {
3777            log("handleInetConditionChange: net=" +
3778                    netType + ", condition=" + condition +
3779                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3780        }
3781        mDefaultInetCondition = condition;
3782        int delay;
3783        if (mInetConditionChangeInFlight == false) {
3784            if (VDBG) log("handleInetConditionChange: starting a change hold");
3785            // setup a new hold to debounce this
3786            if (mDefaultInetCondition > 50) {
3787                delay = Settings.Global.getInt(mContext.getContentResolver(),
3788                        Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3789            } else {
3790                delay = Settings.Global.getInt(mContext.getContentResolver(),
3791                        Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3792            }
3793            mInetConditionChangeInFlight = true;
3794            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3795                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3796        } else {
3797            // we've set the new condition, when this hold ends that will get picked up
3798            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3799        }
3800    }
3801
3802    private void handleInetConditionHoldEnd(int netType, int sequence) {
3803        if (DBG) {
3804            log("handleInetConditionHoldEnd: net=" + netType +
3805                    ", condition=" + mDefaultInetCondition +
3806                    ", published condition=" + mDefaultInetConditionPublished);
3807        }
3808        mInetConditionChangeInFlight = false;
3809
3810        if (mActiveDefaultNetwork == -1) {
3811            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3812            return;
3813        }
3814        if (mDefaultConnectionSequence != sequence) {
3815            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3816            return;
3817        }
3818        // TODO: Figure out why this optimization sometimes causes a
3819        //       change in mDefaultInetCondition to be missed and the
3820        //       UI to not be updated.
3821        //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3822        //    if (DBG) log("no change in condition - aborting");
3823        //    return;
3824        //}
3825        NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork);
3826        if (networkInfo.isConnected() == false) {
3827            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3828            return;
3829        }
3830        mDefaultInetConditionPublished = mDefaultInetCondition;
3831        sendInetConditionBroadcast(networkInfo);
3832        return;
3833    }
3834
3835    public ProxyInfo getProxy() {
3836        // this information is already available as a world read/writable jvm property
3837        // so this API change wouldn't have a benifit.  It also breaks the passing
3838        // of proxy info to all the JVMs.
3839        // enforceAccessPermission();
3840        synchronized (mProxyLock) {
3841            ProxyInfo ret = mGlobalProxy;
3842            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3843            return ret;
3844        }
3845    }
3846
3847    public void setGlobalProxy(ProxyInfo proxyProperties) {
3848        enforceConnectivityInternalPermission();
3849
3850        synchronized (mProxyLock) {
3851            if (proxyProperties == mGlobalProxy) return;
3852            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3853            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3854
3855            String host = "";
3856            int port = 0;
3857            String exclList = "";
3858            String pacFileUrl = "";
3859            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3860                    (proxyProperties.getPacFileUrl() != null))) {
3861                if (!proxyProperties.isValid()) {
3862                    if (DBG)
3863                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3864                    return;
3865                }
3866                mGlobalProxy = new ProxyInfo(proxyProperties);
3867                host = mGlobalProxy.getHost();
3868                port = mGlobalProxy.getPort();
3869                exclList = mGlobalProxy.getExclusionListAsString();
3870                if (proxyProperties.getPacFileUrl() != null) {
3871                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
3872                }
3873            } else {
3874                mGlobalProxy = null;
3875            }
3876            ContentResolver res = mContext.getContentResolver();
3877            final long token = Binder.clearCallingIdentity();
3878            try {
3879                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3880                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3881                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3882                        exclList);
3883                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3884            } finally {
3885                Binder.restoreCallingIdentity(token);
3886            }
3887        }
3888
3889        if (mGlobalProxy == null) {
3890            proxyProperties = mDefaultProxy;
3891        }
3892        sendProxyBroadcast(proxyProperties);
3893    }
3894
3895    private void loadGlobalProxy() {
3896        ContentResolver res = mContext.getContentResolver();
3897        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3898        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3899        String exclList = Settings.Global.getString(res,
3900                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3901        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3902        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3903            ProxyInfo proxyProperties;
3904            if (!TextUtils.isEmpty(pacFileUrl)) {
3905                proxyProperties = new ProxyInfo(pacFileUrl);
3906            } else {
3907                proxyProperties = new ProxyInfo(host, port, exclList);
3908            }
3909            if (!proxyProperties.isValid()) {
3910                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3911                return;
3912            }
3913
3914            synchronized (mProxyLock) {
3915                mGlobalProxy = proxyProperties;
3916            }
3917        }
3918    }
3919
3920    public ProxyInfo getGlobalProxy() {
3921        // this information is already available as a world read/writable jvm property
3922        // so this API change wouldn't have a benifit.  It also breaks the passing
3923        // of proxy info to all the JVMs.
3924        // enforceAccessPermission();
3925        synchronized (mProxyLock) {
3926            return mGlobalProxy;
3927        }
3928    }
3929
3930    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3931        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3932                && (proxy.getPacFileUrl() == null)) {
3933            proxy = null;
3934        }
3935        synchronized (mProxyLock) {
3936            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3937            if (mDefaultProxy == proxy) return; // catches repeated nulls
3938            if (proxy != null &&  !proxy.isValid()) {
3939                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3940                return;
3941            }
3942
3943            // This call could be coming from the PacManager, containing the port of the local
3944            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3945            // global (to get the correct local port), and send a broadcast.
3946            // TODO: Switch PacManager to have its own message to send back rather than
3947            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3948            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
3949                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3950                mGlobalProxy = proxy;
3951                sendProxyBroadcast(mGlobalProxy);
3952                return;
3953            }
3954            mDefaultProxy = proxy;
3955
3956            if (mGlobalProxy != null) return;
3957            if (!mDefaultProxyDisabled) {
3958                sendProxyBroadcast(proxy);
3959            }
3960        }
3961    }
3962
3963    private void handleDeprecatedGlobalHttpProxy() {
3964        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3965                Settings.Global.HTTP_PROXY);
3966        if (!TextUtils.isEmpty(proxy)) {
3967            String data[] = proxy.split(":");
3968            if (data.length == 0) {
3969                return;
3970            }
3971
3972            String proxyHost =  data[0];
3973            int proxyPort = 8080;
3974            if (data.length > 1) {
3975                try {
3976                    proxyPort = Integer.parseInt(data[1]);
3977                } catch (NumberFormatException e) {
3978                    return;
3979                }
3980            }
3981            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3982            setGlobalProxy(p);
3983        }
3984    }
3985
3986    private void sendProxyBroadcast(ProxyInfo proxy) {
3987        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3988        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3989        if (DBG) log("sending Proxy Broadcast for " + proxy);
3990        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3991        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3992            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3993        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3994        final long ident = Binder.clearCallingIdentity();
3995        try {
3996            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3997        } finally {
3998            Binder.restoreCallingIdentity(ident);
3999        }
4000    }
4001
4002    private static class SettingsObserver extends ContentObserver {
4003        private int mWhat;
4004        private Handler mHandler;
4005        SettingsObserver(Handler handler, int what) {
4006            super(handler);
4007            mHandler = handler;
4008            mWhat = what;
4009        }
4010
4011        void observe(Context context) {
4012            ContentResolver resolver = context.getContentResolver();
4013            resolver.registerContentObserver(Settings.Global.getUriFor(
4014                    Settings.Global.HTTP_PROXY), false, this);
4015        }
4016
4017        @Override
4018        public void onChange(boolean selfChange) {
4019            mHandler.obtainMessage(mWhat).sendToTarget();
4020        }
4021    }
4022
4023    private static void log(String s) {
4024        Slog.d(TAG, s);
4025    }
4026
4027    private static void loge(String s) {
4028        Slog.e(TAG, s);
4029    }
4030
4031    int convertFeatureToNetworkType(int networkType, String feature) {
4032        int usedNetworkType = networkType;
4033
4034        if(networkType == ConnectivityManager.TYPE_MOBILE) {
4035            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
4036                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
4037            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
4038                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
4039            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
4040                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
4041                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
4042            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
4043                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
4044            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
4045                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
4046            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
4047                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
4048            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
4049                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
4050            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) {
4051                usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY;
4052            } else {
4053                Slog.e(TAG, "Can't match any mobile netTracker!");
4054            }
4055        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
4056            if (TextUtils.equals(feature, "p2p")) {
4057                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
4058            } else {
4059                Slog.e(TAG, "Can't match any wifi netTracker!");
4060            }
4061        } else {
4062            Slog.e(TAG, "Unexpected network type");
4063        }
4064        return usedNetworkType;
4065    }
4066
4067    private static <T> T checkNotNull(T value, String message) {
4068        if (value == null) {
4069            throw new NullPointerException(message);
4070        }
4071        return value;
4072    }
4073
4074    /**
4075     * Prepare for a VPN application. This method is used by VpnDialogs
4076     * and not available in ConnectivityManager. Permissions are checked
4077     * in Vpn class.
4078     * @hide
4079     */
4080    @Override
4081    public boolean prepareVpn(String oldPackage, String newPackage) {
4082        throwIfLockdownEnabled();
4083        int user = UserHandle.getUserId(Binder.getCallingUid());
4084        synchronized(mVpns) {
4085            return mVpns.get(user).prepare(oldPackage, newPackage);
4086        }
4087    }
4088
4089    @Override
4090    public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
4091        enforceMarkNetworkSocketPermission();
4092        final long token = Binder.clearCallingIdentity();
4093        try {
4094            int mark = mNetd.getMarkForUid(uid);
4095            // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
4096            if (mark == -1) {
4097                mark = 0;
4098            }
4099            NetworkUtils.markSocket(socket.getFd(), mark);
4100        } catch (RemoteException e) {
4101        } finally {
4102            Binder.restoreCallingIdentity(token);
4103        }
4104    }
4105
4106    /**
4107     * Configure a TUN interface and return its file descriptor. Parameters
4108     * are encoded and opaque to this class. This method is used by VpnBuilder
4109     * and not available in ConnectivityManager. Permissions are checked in
4110     * Vpn class.
4111     * @hide
4112     */
4113    @Override
4114    public ParcelFileDescriptor establishVpn(VpnConfig config) {
4115        throwIfLockdownEnabled();
4116        int user = UserHandle.getUserId(Binder.getCallingUid());
4117        synchronized(mVpns) {
4118            return mVpns.get(user).establish(config);
4119        }
4120    }
4121
4122    /**
4123     * Start legacy VPN, controlling native daemons as needed. Creates a
4124     * secondary thread to perform connection work, returning quickly.
4125     */
4126    @Override
4127    public void startLegacyVpn(VpnProfile profile) {
4128        throwIfLockdownEnabled();
4129        final LinkProperties egress = getActiveLinkProperties();
4130        if (egress == null) {
4131            throw new IllegalStateException("Missing active network connection");
4132        }
4133        int user = UserHandle.getUserId(Binder.getCallingUid());
4134        synchronized(mVpns) {
4135            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4136        }
4137    }
4138
4139    /**
4140     * Return the information of the ongoing legacy VPN. This method is used
4141     * by VpnSettings and not available in ConnectivityManager. Permissions
4142     * are checked in Vpn class.
4143     * @hide
4144     */
4145    @Override
4146    public LegacyVpnInfo getLegacyVpnInfo() {
4147        throwIfLockdownEnabled();
4148        int user = UserHandle.getUserId(Binder.getCallingUid());
4149        synchronized(mVpns) {
4150            return mVpns.get(user).getLegacyVpnInfo();
4151        }
4152    }
4153
4154    /**
4155     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
4156     * not available in ConnectivityManager.
4157     * Permissions are checked in Vpn class.
4158     * @hide
4159     */
4160    @Override
4161    public VpnConfig getVpnConfig() {
4162        int user = UserHandle.getUserId(Binder.getCallingUid());
4163        synchronized(mVpns) {
4164            return mVpns.get(user).getVpnConfig();
4165        }
4166    }
4167
4168    @Override
4169    public boolean updateLockdownVpn() {
4170        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4171            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4172            return false;
4173        }
4174
4175        // Tear down existing lockdown if profile was removed
4176        mLockdownEnabled = LockdownVpnTracker.isEnabled();
4177        if (mLockdownEnabled) {
4178            if (!mKeyStore.isUnlocked()) {
4179                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
4180                return false;
4181            }
4182
4183            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
4184            final VpnProfile profile = VpnProfile.decode(
4185                    profileName, mKeyStore.get(Credentials.VPN + profileName));
4186            int user = UserHandle.getUserId(Binder.getCallingUid());
4187            synchronized(mVpns) {
4188                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
4189                            profile));
4190            }
4191        } else {
4192            setLockdownTracker(null);
4193        }
4194
4195        return true;
4196    }
4197
4198    /**
4199     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4200     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4201     */
4202    private void setLockdownTracker(LockdownVpnTracker tracker) {
4203        // Shutdown any existing tracker
4204        final LockdownVpnTracker existing = mLockdownTracker;
4205        mLockdownTracker = null;
4206        if (existing != null) {
4207            existing.shutdown();
4208        }
4209
4210        try {
4211            if (tracker != null) {
4212                mNetd.setFirewallEnabled(true);
4213                mNetd.setFirewallInterfaceRule("lo", true);
4214                mLockdownTracker = tracker;
4215                mLockdownTracker.init();
4216            } else {
4217                mNetd.setFirewallEnabled(false);
4218            }
4219        } catch (RemoteException e) {
4220            // ignored; NMS lives inside system_server
4221        }
4222    }
4223
4224    private void throwIfLockdownEnabled() {
4225        if (mLockdownEnabled) {
4226            throw new IllegalStateException("Unavailable in lockdown mode");
4227        }
4228    }
4229
4230    public void supplyMessenger(int networkType, Messenger messenger) {
4231        enforceConnectivityInternalPermission();
4232
4233        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
4234            mNetTrackers[networkType].supplyMessenger(messenger);
4235        }
4236    }
4237
4238    public int findConnectionTypeForIface(String iface) {
4239        enforceConnectivityInternalPermission();
4240
4241        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
4242        for (NetworkStateTracker tracker : mNetTrackers) {
4243            if (tracker != null) {
4244                LinkProperties lp = tracker.getLinkProperties();
4245                if (lp != null && iface.equals(lp.getInterfaceName())) {
4246                    return tracker.getNetworkInfo().getType();
4247                }
4248            }
4249        }
4250        return ConnectivityManager.TYPE_NONE;
4251    }
4252
4253    /**
4254     * Have mobile data fail fast if enabled.
4255     *
4256     * @param enabled DctConstants.ENABLED/DISABLED
4257     */
4258    private void setEnableFailFastMobileData(int enabled) {
4259        int tag;
4260
4261        if (enabled == DctConstants.ENABLED) {
4262            tag = mEnableFailFastMobileDataTag.incrementAndGet();
4263        } else {
4264            tag = mEnableFailFastMobileDataTag.get();
4265        }
4266        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
4267                         enabled));
4268    }
4269
4270    private boolean isMobileDataStateTrackerReady() {
4271        MobileDataStateTracker mdst =
4272                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4273        return (mdst != null) && (mdst.isReady());
4274    }
4275
4276    /**
4277     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
4278     */
4279
4280    /**
4281     * No connection was possible to the network.
4282     * This is NOT a warm sim.
4283     */
4284    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
4285
4286    /**
4287     * A connection was made to the internet, all is well.
4288     * This is NOT a warm sim.
4289     */
4290    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
4291
4292    /**
4293     * A connection was made but no dns server was available to resolve a name to address.
4294     * This is NOT a warm sim since provisioning network is supported.
4295     */
4296    private static final int CMP_RESULT_CODE_NO_DNS = 2;
4297
4298    /**
4299     * A connection was made but could not open a TCP connection.
4300     * This is NOT a warm sim since provisioning network is supported.
4301     */
4302    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
4303
4304    /**
4305     * A connection was made but there was a redirection, we appear to be in walled garden.
4306     * This is an indication of a warm sim on a mobile network such as T-Mobile.
4307     */
4308    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
4309
4310    /**
4311     * The mobile network is a provisioning network.
4312     * This is an indication of a warm sim on a mobile network such as AT&T.
4313     */
4314    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
4315
4316    /**
4317     * The mobile network is provisioning
4318     */
4319    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
4320
4321    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
4322    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
4323
4324    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
4325
4326    @Override
4327    public int checkMobileProvisioning(int suggestedTimeOutMs) {
4328        int timeOutMs = -1;
4329        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4330        enforceConnectivityInternalPermission();
4331
4332        final long token = Binder.clearCallingIdentity();
4333        try {
4334            timeOutMs = suggestedTimeOutMs;
4335            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4336                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4337            }
4338
4339            // Check that mobile networks are supported
4340            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4341                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4342                if (DBG) log("checkMobileProvisioning: X no mobile network");
4343                return timeOutMs;
4344            }
4345
4346            // If we're already checking don't do it again
4347            // TODO: Add a queue of results...
4348            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4349                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4350                return timeOutMs;
4351            }
4352
4353            // Start off with mobile notification off
4354            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4355
4356            CheckMp checkMp = new CheckMp(mContext, this);
4357            CheckMp.CallBack cb = new CheckMp.CallBack() {
4358                @Override
4359                void onComplete(Integer result) {
4360                    if (DBG) log("CheckMp.onComplete: result=" + result);
4361                    NetworkInfo ni =
4362                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4363                    switch(result) {
4364                        case CMP_RESULT_CODE_CONNECTABLE:
4365                        case CMP_RESULT_CODE_NO_CONNECTION:
4366                        case CMP_RESULT_CODE_NO_DNS:
4367                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
4368                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
4369                            break;
4370                        }
4371                        case CMP_RESULT_CODE_REDIRECTED: {
4372                            if (DBG) log("CheckMp.onComplete: warm sim");
4373                            String url = getMobileProvisioningUrl();
4374                            if (TextUtils.isEmpty(url)) {
4375                                url = getMobileRedirectedProvisioningUrl();
4376                            }
4377                            if (TextUtils.isEmpty(url) == false) {
4378                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4379                                setProvNotificationVisible(true,
4380                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4381                                        url);
4382                            } else {
4383                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
4384                            }
4385                            break;
4386                        }
4387                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
4388                            String url = getMobileProvisioningUrl();
4389                            if (TextUtils.isEmpty(url) == false) {
4390                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4391                                setProvNotificationVisible(true,
4392                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4393                                        url);
4394                                // Mark that we've got a provisioning network and
4395                                // Disable Mobile Data until user actually starts provisioning.
4396                                mIsProvisioningNetwork.set(true);
4397                                MobileDataStateTracker mdst = (MobileDataStateTracker)
4398                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4399
4400                                // Disable radio until user starts provisioning
4401                                mdst.setRadio(false);
4402                            } else {
4403                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
4404                            }
4405                            break;
4406                        }
4407                        case CMP_RESULT_CODE_IS_PROVISIONING: {
4408                            // FIXME: Need to know when provisioning is done. Probably we can
4409                            // check the completion status if successful we're done if we
4410                            // "timedout" or still connected to provisioning APN turn off data?
4411                            if (DBG) log("CheckMp.onComplete: provisioning started");
4412                            mIsStartingProvisioning.set(false);
4413                            break;
4414                        }
4415                        default: {
4416                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
4417                            break;
4418                        }
4419                    }
4420                    mIsCheckingMobileProvisioning.set(false);
4421                }
4422            };
4423            CheckMp.Params params =
4424                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
4425            if (DBG) log("checkMobileProvisioning: params=" + params);
4426            // TODO: Reenable when calls to the now defunct
4427            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
4428            //       This code should be moved to the Telephony code.
4429            // checkMp.execute(params);
4430        } finally {
4431            Binder.restoreCallingIdentity(token);
4432            if (DBG) log("checkMobileProvisioning: X");
4433        }
4434        return timeOutMs;
4435    }
4436
4437    static class CheckMp extends
4438            AsyncTask<CheckMp.Params, Void, Integer> {
4439        private static final String CHECKMP_TAG = "CheckMp";
4440
4441        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4442        private static boolean mTestingFailures;
4443
4444        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4445        private static final int MAX_LOOPS = 4;
4446
4447        // Number of milli-seconds to complete all of the retires
4448        public static final int MAX_TIMEOUT_MS =  60000;
4449
4450        // The socket should retry only 5 seconds, the default is longer
4451        private static final int SOCKET_TIMEOUT_MS = 5000;
4452
4453        // Sleep time for network errors
4454        private static final int NET_ERROR_SLEEP_SEC = 3;
4455
4456        // Sleep time for network route establishment
4457        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4458
4459        // Short sleep time for polling :(
4460        private static final int POLLING_SLEEP_SEC = 1;
4461
4462        private Context mContext;
4463        private ConnectivityService mCs;
4464        private TelephonyManager mTm;
4465        private Params mParams;
4466
4467        /**
4468         * Parameters for AsyncTask.execute
4469         */
4470        static class Params {
4471            private String mUrl;
4472            private long mTimeOutMs;
4473            private CallBack mCb;
4474
4475            Params(String url, long timeOutMs, CallBack cb) {
4476                mUrl = url;
4477                mTimeOutMs = timeOutMs;
4478                mCb = cb;
4479            }
4480
4481            @Override
4482            public String toString() {
4483                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4484            }
4485        }
4486
4487        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4488        // issued by name or ip address, for Google its by name so when we construct
4489        // this HostnameVerifier we'll pass the original Uri and use it to verify
4490        // the host. If the host name in the original uril fails we'll test the
4491        // hostname parameter just incase things change.
4492        static class CheckMpHostnameVerifier implements HostnameVerifier {
4493            Uri mOrgUri;
4494
4495            CheckMpHostnameVerifier(Uri orgUri) {
4496                mOrgUri = orgUri;
4497            }
4498
4499            @Override
4500            public boolean verify(String hostname, SSLSession session) {
4501                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4502                String orgUriHost = mOrgUri.getHost();
4503                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4504                if (DBG) {
4505                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4506                        + " orgUriHost=" + orgUriHost);
4507                }
4508                return retVal;
4509            }
4510        }
4511
4512        /**
4513         * The call back object passed in Params. onComplete will be called
4514         * on the main thread.
4515         */
4516        abstract static class CallBack {
4517            // Called on the main thread.
4518            abstract void onComplete(Integer result);
4519        }
4520
4521        public CheckMp(Context context, ConnectivityService cs) {
4522            if (Build.IS_DEBUGGABLE) {
4523                mTestingFailures =
4524                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4525            } else {
4526                mTestingFailures = false;
4527            }
4528
4529            mContext = context;
4530            mCs = cs;
4531
4532            // Setup access to TelephonyService we'll be using.
4533            mTm = (TelephonyManager) mContext.getSystemService(
4534                    Context.TELEPHONY_SERVICE);
4535        }
4536
4537        /**
4538         * Get the default url to use for the test.
4539         */
4540        public String getDefaultUrl() {
4541            // See http://go/clientsdns for usage approval
4542            String server = Settings.Global.getString(mContext.getContentResolver(),
4543                    Settings.Global.CAPTIVE_PORTAL_SERVER);
4544            if (server == null) {
4545                server = "clients3.google.com";
4546            }
4547            return "http://" + server + "/generate_204";
4548        }
4549
4550        /**
4551         * Detect if its possible to connect to the http url. DNS based detection techniques
4552         * do not work at all hotspots. The best way to check is to perform a request to
4553         * a known address that fetches the data we expect.
4554         */
4555        private synchronized Integer isMobileOk(Params params) {
4556            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
4557            Uri orgUri = Uri.parse(params.mUrl);
4558            Random rand = new Random();
4559            mParams = params;
4560
4561            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4562                result = CMP_RESULT_CODE_NO_CONNECTION;
4563                log("isMobileOk: X not mobile capable result=" + result);
4564                return result;
4565            }
4566
4567            if (mCs.mIsStartingProvisioning.get()) {
4568                result = CMP_RESULT_CODE_IS_PROVISIONING;
4569                log("isMobileOk: X is provisioning result=" + result);
4570                return result;
4571            }
4572
4573            // See if we've already determined we've got a provisioning connection,
4574            // if so we don't need to do anything active.
4575            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4576                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4577            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4578            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4579
4580            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4581                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4582            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4583            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4584
4585            if (isDefaultProvisioning || isHipriProvisioning) {
4586                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4587                log("isMobileOk: X default || hipri is provisioning result=" + result);
4588                return result;
4589            }
4590
4591            try {
4592                // Continue trying to connect until time has run out
4593                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
4594
4595                if (!mCs.isMobileDataStateTrackerReady()) {
4596                    // Wait for MobileDataStateTracker to be ready.
4597                    if (DBG) log("isMobileOk: mdst is not ready");
4598                    while(SystemClock.elapsedRealtime() < endTime) {
4599                        if (mCs.isMobileDataStateTrackerReady()) {
4600                            // Enable fail fast as we'll do retries here and use a
4601                            // hipri connection so the default connection stays active.
4602                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4603                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4604                            break;
4605                        }
4606                        sleep(POLLING_SLEEP_SEC);
4607                    }
4608                }
4609
4610                log("isMobileOk: start hipri url=" + params.mUrl);
4611
4612                // First wait until we can start using hipri
4613                Binder binder = new Binder();
4614                while(SystemClock.elapsedRealtime() < endTime) {
4615                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4616                            Phone.FEATURE_ENABLE_HIPRI, binder);
4617                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4618                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4619                            log("isMobileOk: hipri started");
4620                            break;
4621                    }
4622                    if (VDBG) log("isMobileOk: hipri not started yet");
4623                    result = CMP_RESULT_CODE_NO_CONNECTION;
4624                    sleep(POLLING_SLEEP_SEC);
4625                }
4626
4627                // Continue trying to connect until time has run out
4628                while(SystemClock.elapsedRealtime() < endTime) {
4629                    try {
4630                        // Wait for hipri to connect.
4631                        // TODO: Don't poll and handle situation where hipri fails
4632                        // because default is retrying. See b/9569540
4633                        NetworkInfo.State state = mCs
4634                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4635                        if (state != NetworkInfo.State.CONNECTED) {
4636                            if (true/*VDBG*/) {
4637                                log("isMobileOk: not connected ni=" +
4638                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4639                            }
4640                            sleep(POLLING_SLEEP_SEC);
4641                            result = CMP_RESULT_CODE_NO_CONNECTION;
4642                            continue;
4643                        }
4644
4645                        // Hipri has started check if this is a provisioning url
4646                        MobileDataStateTracker mdst = (MobileDataStateTracker)
4647                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4648                        if (mdst.isProvisioningNetwork()) {
4649                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4650                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
4651                            return result;
4652                        } else {
4653                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4654                        }
4655
4656                        // Get of the addresses associated with the url host. We need to use the
4657                        // address otherwise HttpURLConnection object will use the name to get
4658                        // the addresses and will try every address but that will bypass the
4659                        // route to host we setup and the connection could succeed as the default
4660                        // interface might be connected to the internet via wifi or other interface.
4661                        InetAddress[] addresses;
4662                        try {
4663                            addresses = InetAddress.getAllByName(orgUri.getHost());
4664                        } catch (UnknownHostException e) {
4665                            result = CMP_RESULT_CODE_NO_DNS;
4666                            log("isMobileOk: X UnknownHostException result=" + result);
4667                            return result;
4668                        }
4669                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4670
4671                        // Get the type of addresses supported by this link
4672                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
4673                                ConnectivityManager.TYPE_MOBILE_HIPRI);
4674                        boolean linkHasIpv4 = lp.hasIPv4Address();
4675                        boolean linkHasIpv6 = lp.hasGlobalIPv6Address();
4676                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4677                                + " linkHasIpv6=" + linkHasIpv6);
4678
4679                        final ArrayList<InetAddress> validAddresses =
4680                                new ArrayList<InetAddress>(addresses.length);
4681
4682                        for (InetAddress addr : addresses) {
4683                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4684                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
4685                                validAddresses.add(addr);
4686                            }
4687                        }
4688
4689                        if (validAddresses.size() == 0) {
4690                            return CMP_RESULT_CODE_NO_CONNECTION;
4691                        }
4692
4693                        int addrTried = 0;
4694                        while (true) {
4695                            // Loop through at most MAX_LOOPS valid addresses or until
4696                            // we run out of time
4697                            if (addrTried++ >= MAX_LOOPS) {
4698                                log("isMobileOk: too many loops tried - giving up");
4699                                break;
4700                            }
4701                            if (SystemClock.elapsedRealtime() >= endTime) {
4702                                log("isMobileOk: spend too much time - giving up");
4703                                break;
4704                            }
4705
4706                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
4707                                    validAddresses.size()));
4708
4709                            // Make a route to host so we check the specific interface.
4710                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4711                                    hostAddr.getAddress(), null)) {
4712                                // Wait a short time to be sure the route is established ??
4713                                log("isMobileOk:"
4714                                        + " wait to establish route to hostAddr=" + hostAddr);
4715                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
4716                            } else {
4717                                log("isMobileOk:"
4718                                        + " could not establish route to hostAddr=" + hostAddr);
4719                                // Wait a short time before the next attempt
4720                                sleep(NET_ERROR_SLEEP_SEC);
4721                                continue;
4722                            }
4723
4724                            // Rewrite the url to have numeric address to use the specific route
4725                            // using http for half the attempts and https for the other half.
4726                            // Doing https first and http second as on a redirected walled garden
4727                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
4728                            // handshake timed out" which we declare as
4729                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4730                            // having http second we will be using logic used for some time.
4731                            URL newUrl;
4732                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4733                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
4734                                        orgUri.getPath());
4735                            log("isMobileOk: newUrl=" + newUrl);
4736
4737                            HttpURLConnection urlConn = null;
4738                            try {
4739                                // Open the connection set the request headers and get the response
4740                                urlConn = (HttpURLConnection)newUrl.openConnection(
4741                                        java.net.Proxy.NO_PROXY);
4742                                if (scheme.equals("https")) {
4743                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
4744                                            new CheckMpHostnameVerifier(orgUri));
4745                                }
4746                                urlConn.setInstanceFollowRedirects(false);
4747                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4748                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4749                                urlConn.setUseCaches(false);
4750                                urlConn.setAllowUserInteraction(false);
4751                                // Set the "Connection" to "Close" as by default "Keep-Alive"
4752                                // is used which is useless in this case.
4753                                urlConn.setRequestProperty("Connection", "close");
4754                                int responseCode = urlConn.getResponseCode();
4755
4756                                // For debug display the headers
4757                                Map<String, List<String>> headers = urlConn.getHeaderFields();
4758                                log("isMobileOk: headers=" + headers);
4759
4760                                // Close the connection
4761                                urlConn.disconnect();
4762                                urlConn = null;
4763
4764                                if (mTestingFailures) {
4765                                    // Pretend no connection, this tests using http and https
4766                                    result = CMP_RESULT_CODE_NO_CONNECTION;
4767                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
4768                                    continue;
4769                                }
4770
4771                                if (responseCode == 204) {
4772                                    // Return
4773                                    result = CMP_RESULT_CODE_CONNECTABLE;
4774                                    log("isMobileOk: X got expected responseCode=" + responseCode
4775                                            + " result=" + result);
4776                                    return result;
4777                                } else {
4778                                    // Retry to be sure this was redirected, we've gotten
4779                                    // occasions where a server returned 200 even though
4780                                    // the device didn't have a "warm" sim.
4781                                    log("isMobileOk: not expected responseCode=" + responseCode);
4782                                    // TODO - it would be nice in the single-address case to do
4783                                    // another DNS resolve here, but flushing the cache is a bit
4784                                    // heavy-handed.
4785                                    result = CMP_RESULT_CODE_REDIRECTED;
4786                                }
4787                            } catch (Exception e) {
4788                                log("isMobileOk: HttpURLConnection Exception" + e);
4789                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4790                                if (urlConn != null) {
4791                                    urlConn.disconnect();
4792                                    urlConn = null;
4793                                }
4794                                sleep(NET_ERROR_SLEEP_SEC);
4795                                continue;
4796                            }
4797                        }
4798                        log("isMobileOk: X loops|timed out result=" + result);
4799                        return result;
4800                    } catch (Exception e) {
4801                        log("isMobileOk: Exception e=" + e);
4802                        continue;
4803                    }
4804                }
4805                log("isMobileOk: timed out");
4806            } finally {
4807                log("isMobileOk: F stop hipri");
4808                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4809                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4810                        Phone.FEATURE_ENABLE_HIPRI);
4811
4812                // Wait for hipri to disconnect.
4813                long endTime = SystemClock.elapsedRealtime() + 5000;
4814
4815                while(SystemClock.elapsedRealtime() < endTime) {
4816                    NetworkInfo.State state = mCs
4817                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4818                    if (state != NetworkInfo.State.DISCONNECTED) {
4819                        if (VDBG) {
4820                            log("isMobileOk: connected ni=" +
4821                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4822                        }
4823                        sleep(POLLING_SLEEP_SEC);
4824                        continue;
4825                    }
4826                }
4827
4828                log("isMobileOk: X result=" + result);
4829            }
4830            return result;
4831        }
4832
4833        @Override
4834        protected Integer doInBackground(Params... params) {
4835            return isMobileOk(params[0]);
4836        }
4837
4838        @Override
4839        protected void onPostExecute(Integer result) {
4840            log("onPostExecute: result=" + result);
4841            if ((mParams != null) && (mParams.mCb != null)) {
4842                mParams.mCb.onComplete(result);
4843            }
4844        }
4845
4846        private String inetAddressesToString(InetAddress[] addresses) {
4847            StringBuffer sb = new StringBuffer();
4848            boolean firstTime = true;
4849            for(InetAddress addr : addresses) {
4850                if (firstTime) {
4851                    firstTime = false;
4852                } else {
4853                    sb.append(",");
4854                }
4855                sb.append(addr);
4856            }
4857            return sb.toString();
4858        }
4859
4860        private void printNetworkInfo() {
4861            boolean hasIccCard = mTm.hasIccCard();
4862            int simState = mTm.getSimState();
4863            log("hasIccCard=" + hasIccCard
4864                    + " simState=" + simState);
4865            NetworkInfo[] ni = mCs.getAllNetworkInfo();
4866            if (ni != null) {
4867                log("ni.length=" + ni.length);
4868                for (NetworkInfo netInfo: ni) {
4869                    log("netInfo=" + netInfo.toString());
4870                }
4871            } else {
4872                log("no network info ni=null");
4873            }
4874        }
4875
4876        /**
4877         * Sleep for a few seconds then return.
4878         * @param seconds
4879         */
4880        private static void sleep(int seconds) {
4881            long stopTime = System.nanoTime() + (seconds * 1000000000);
4882            long sleepTime;
4883            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
4884                try {
4885                    Thread.sleep(sleepTime / 1000000);
4886                } catch (InterruptedException ignored) {
4887                }
4888            }
4889        }
4890
4891        private static void log(String s) {
4892            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4893        }
4894    }
4895
4896    // TODO: Move to ConnectivityManager and make public?
4897    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4898            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
4899
4900    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4901        @Override
4902        public void onReceive(Context context, Intent intent) {
4903            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4904                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4905            }
4906        }
4907    };
4908
4909    private void handleMobileProvisioningAction(String url) {
4910        // Mark notification as not visible
4911        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4912
4913        // Check airplane mode
4914        boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(),
4915                Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
4916        // If provisioning network and not in airplane mode handle as a special case,
4917        // otherwise launch browser with the intent directly.
4918        if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) {
4919            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
4920            mIsProvisioningNetwork.set(false);
4921//            mIsStartingProvisioning.set(true);
4922//            MobileDataStateTracker mdst = (MobileDataStateTracker)
4923//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4924            // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here
4925//            mdst.setRadio(true);
4926//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
4927//            mdst.enableMobileProvisioning(url);
4928        } else {
4929            if (DBG) log("handleMobileProvisioningAction: not prov network");
4930            mIsProvisioningNetwork.set(false);
4931            // Check for  apps that can handle provisioning first
4932            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
4933            provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
4934                    + mTelephonyManager.getSimOperator());
4935            if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
4936                    != null) {
4937                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4938                        Intent.FLAG_ACTIVITY_NEW_TASK);
4939                mContext.startActivity(provisioningIntent);
4940            } else {
4941                // If no apps exist, use standard URL ACTION_VIEW method
4942                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4943                        Intent.CATEGORY_APP_BROWSER);
4944                newIntent.setData(Uri.parse(url));
4945                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4946                        Intent.FLAG_ACTIVITY_NEW_TASK);
4947                try {
4948                    mContext.startActivity(newIntent);
4949                } catch (ActivityNotFoundException e) {
4950                    loge("handleMobileProvisioningAction: startActivity failed" + e);
4951                }
4952            }
4953        }
4954    }
4955
4956    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4957    private volatile boolean mIsNotificationVisible = false;
4958
4959    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4960            String url) {
4961        if (DBG) {
4962            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4963                + " extraInfo=" + extraInfo + " url=" + url);
4964        }
4965        Intent intent = null;
4966        PendingIntent pendingIntent = null;
4967        if (visible) {
4968            switch (networkType) {
4969                case ConnectivityManager.TYPE_WIFI:
4970                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4971                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4972                            Intent.FLAG_ACTIVITY_NEW_TASK);
4973                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4974                    break;
4975                case ConnectivityManager.TYPE_MOBILE:
4976                case ConnectivityManager.TYPE_MOBILE_HIPRI:
4977                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4978                    intent.putExtra("EXTRA_URL", url);
4979                    intent.setFlags(0);
4980                    pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
4981                    break;
4982                default:
4983                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4984                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4985                            Intent.FLAG_ACTIVITY_NEW_TASK);
4986                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4987                    break;
4988            }
4989        }
4990        setProvNotificationVisibleIntent(visible, networkType, extraInfo, pendingIntent);
4991    }
4992
4993    private void setProvNotificationVisibleIntent(boolean visible, int networkType,
4994            String extraInfo, PendingIntent intent) {
4995        if (DBG) {
4996            log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
4997                networkType + " extraInfo=" + extraInfo);
4998        }
4999
5000        Resources r = Resources.getSystem();
5001        NotificationManager notificationManager = (NotificationManager) mContext
5002            .getSystemService(Context.NOTIFICATION_SERVICE);
5003
5004        if (visible) {
5005            CharSequence title;
5006            CharSequence details;
5007            int icon;
5008            Notification notification = new Notification();
5009            switch (networkType) {
5010                case ConnectivityManager.TYPE_WIFI:
5011                    title = r.getString(R.string.wifi_available_sign_in, 0);
5012                    details = r.getString(R.string.network_available_sign_in_detailed,
5013                            extraInfo);
5014                    icon = R.drawable.stat_notify_wifi_in_range;
5015                    break;
5016                case ConnectivityManager.TYPE_MOBILE:
5017                case ConnectivityManager.TYPE_MOBILE_HIPRI:
5018                    title = r.getString(R.string.network_available_sign_in, 0);
5019                    // TODO: Change this to pull from NetworkInfo once a printable
5020                    // name has been added to it
5021                    details = mTelephonyManager.getNetworkOperatorName();
5022                    icon = R.drawable.stat_notify_rssi_in_range;
5023                    break;
5024                default:
5025                    title = r.getString(R.string.network_available_sign_in, 0);
5026                    details = r.getString(R.string.network_available_sign_in_detailed,
5027                            extraInfo);
5028                    icon = R.drawable.stat_notify_rssi_in_range;
5029                    break;
5030            }
5031
5032            notification.when = 0;
5033            notification.icon = icon;
5034            notification.flags = Notification.FLAG_AUTO_CANCEL;
5035            notification.tickerText = title;
5036            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
5037            notification.contentIntent = intent;
5038
5039            try {
5040                notificationManager.notify(NOTIFICATION_ID, networkType, notification);
5041            } catch (NullPointerException npe) {
5042                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
5043                npe.printStackTrace();
5044            }
5045        } else {
5046            try {
5047                notificationManager.cancel(NOTIFICATION_ID, networkType);
5048            } catch (NullPointerException npe) {
5049                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
5050                npe.printStackTrace();
5051            }
5052        }
5053        mIsNotificationVisible = visible;
5054    }
5055
5056    /** Location to an updatable file listing carrier provisioning urls.
5057     *  An example:
5058     *
5059     * <?xml version="1.0" encoding="utf-8"?>
5060     *  <provisioningUrls>
5061     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
5062     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
5063     *  </provisioningUrls>
5064     */
5065    private static final String PROVISIONING_URL_PATH =
5066            "/data/misc/radio/provisioning_urls.xml";
5067    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
5068
5069    /** XML tag for root element. */
5070    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
5071    /** XML tag for individual url */
5072    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
5073    /** XML tag for redirected url */
5074    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
5075    /** XML attribute for mcc */
5076    private static final String ATTR_MCC = "mcc";
5077    /** XML attribute for mnc */
5078    private static final String ATTR_MNC = "mnc";
5079
5080    private static final int REDIRECTED_PROVISIONING = 1;
5081    private static final int PROVISIONING = 2;
5082
5083    private String getProvisioningUrlBaseFromFile(int type) {
5084        FileReader fileReader = null;
5085        XmlPullParser parser = null;
5086        Configuration config = mContext.getResources().getConfiguration();
5087        String tagType;
5088
5089        switch (type) {
5090            case PROVISIONING:
5091                tagType = TAG_PROVISIONING_URL;
5092                break;
5093            case REDIRECTED_PROVISIONING:
5094                tagType = TAG_REDIRECTED_URL;
5095                break;
5096            default:
5097                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
5098                        type);
5099        }
5100
5101        try {
5102            fileReader = new FileReader(mProvisioningUrlFile);
5103            parser = Xml.newPullParser();
5104            parser.setInput(fileReader);
5105            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
5106
5107            while (true) {
5108                XmlUtils.nextElement(parser);
5109
5110                String element = parser.getName();
5111                if (element == null) break;
5112
5113                if (element.equals(tagType)) {
5114                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
5115                    try {
5116                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
5117                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
5118                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
5119                                parser.next();
5120                                if (parser.getEventType() == XmlPullParser.TEXT) {
5121                                    return parser.getText();
5122                                }
5123                            }
5124                        }
5125                    } catch (NumberFormatException e) {
5126                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
5127                    }
5128                }
5129            }
5130            return null;
5131        } catch (FileNotFoundException e) {
5132            loge("Carrier Provisioning Urls file not found");
5133        } catch (XmlPullParserException e) {
5134            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
5135        } catch (IOException e) {
5136            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
5137        } finally {
5138            if (fileReader != null) {
5139                try {
5140                    fileReader.close();
5141                } catch (IOException e) {}
5142            }
5143        }
5144        return null;
5145    }
5146
5147    @Override
5148    public String getMobileRedirectedProvisioningUrl() {
5149        enforceConnectivityInternalPermission();
5150        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
5151        if (TextUtils.isEmpty(url)) {
5152            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
5153        }
5154        return url;
5155    }
5156
5157    @Override
5158    public String getMobileProvisioningUrl() {
5159        enforceConnectivityInternalPermission();
5160        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
5161        if (TextUtils.isEmpty(url)) {
5162            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
5163            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
5164        } else {
5165            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
5166        }
5167        // populate the iccid, imei and phone number in the provisioning url.
5168        if (!TextUtils.isEmpty(url)) {
5169            String phoneNumber = mTelephonyManager.getLine1Number();
5170            if (TextUtils.isEmpty(phoneNumber)) {
5171                phoneNumber = "0000000000";
5172            }
5173            url = String.format(url,
5174                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
5175                    mTelephonyManager.getDeviceId() /* IMEI */,
5176                    phoneNumber /* Phone numer */);
5177        }
5178
5179        return url;
5180    }
5181
5182    @Override
5183    public void setProvisioningNotificationVisible(boolean visible, int networkType,
5184            String extraInfo, String url) {
5185        enforceConnectivityInternalPermission();
5186        setProvNotificationVisible(visible, networkType, extraInfo, url);
5187    }
5188
5189    @Override
5190    public void setAirplaneMode(boolean enable) {
5191        enforceConnectivityInternalPermission();
5192        final long ident = Binder.clearCallingIdentity();
5193        try {
5194            final ContentResolver cr = mContext.getContentResolver();
5195            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
5196            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5197            intent.putExtra("state", enable);
5198            mContext.sendBroadcast(intent);
5199        } finally {
5200            Binder.restoreCallingIdentity(ident);
5201        }
5202    }
5203
5204    private void onUserStart(int userId) {
5205        synchronized(mVpns) {
5206            Vpn userVpn = mVpns.get(userId);
5207            if (userVpn != null) {
5208                loge("Starting user already has a VPN");
5209                return;
5210            }
5211            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
5212            mVpns.put(userId, userVpn);
5213        }
5214    }
5215
5216    private void onUserStop(int userId) {
5217        synchronized(mVpns) {
5218            Vpn userVpn = mVpns.get(userId);
5219            if (userVpn == null) {
5220                loge("Stopping user has no VPN");
5221                return;
5222            }
5223            mVpns.delete(userId);
5224        }
5225    }
5226
5227    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5228        @Override
5229        public void onReceive(Context context, Intent intent) {
5230            final String action = intent.getAction();
5231            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
5232            if (userId == UserHandle.USER_NULL) return;
5233
5234            if (Intent.ACTION_USER_STARTING.equals(action)) {
5235                onUserStart(userId);
5236            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
5237                onUserStop(userId);
5238            }
5239        }
5240    };
5241
5242    @Override
5243    public LinkQualityInfo getLinkQualityInfo(int networkType) {
5244        enforceAccessPermission();
5245        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
5246            return mNetTrackers[networkType].getLinkQualityInfo();
5247        } else {
5248            return null;
5249        }
5250    }
5251
5252    @Override
5253    public LinkQualityInfo getActiveLinkQualityInfo() {
5254        enforceAccessPermission();
5255        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
5256                mNetTrackers[mActiveDefaultNetwork] != null) {
5257            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
5258        } else {
5259            return null;
5260        }
5261    }
5262
5263    @Override
5264    public LinkQualityInfo[] getAllLinkQualityInfo() {
5265        enforceAccessPermission();
5266        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
5267        for (NetworkStateTracker tracker : mNetTrackers) {
5268            if (tracker != null) {
5269                LinkQualityInfo li = tracker.getLinkQualityInfo();
5270                if (li != null) {
5271                    result.add(li);
5272                }
5273            }
5274        }
5275
5276        return result.toArray(new LinkQualityInfo[result.size()]);
5277    }
5278
5279    /* Infrastructure for network sampling */
5280
5281    private void handleNetworkSamplingTimeout() {
5282
5283        log("Sampling interval elapsed, updating statistics ..");
5284
5285        // initialize list of interfaces ..
5286        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
5287                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
5288        for (NetworkStateTracker tracker : mNetTrackers) {
5289            if (tracker != null) {
5290                String ifaceName = tracker.getNetworkInterfaceName();
5291                if (ifaceName != null) {
5292                    mapIfaceToSample.put(ifaceName, null);
5293                }
5294            }
5295        }
5296
5297        // Read samples for all interfaces
5298        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
5299
5300        // process samples for all networks
5301        for (NetworkStateTracker tracker : mNetTrackers) {
5302            if (tracker != null) {
5303                String ifaceName = tracker.getNetworkInterfaceName();
5304                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
5305                if (ss != null) {
5306                    // end the previous sampling cycle
5307                    tracker.stopSampling(ss);
5308                    // start a new sampling cycle ..
5309                    tracker.startSampling(ss);
5310                }
5311            }
5312        }
5313
5314        log("Done.");
5315
5316        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
5317                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
5318                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
5319
5320        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
5321
5322        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
5323    }
5324
5325    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
5326        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
5327        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
5328    }
5329
5330    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
5331            new HashMap<Messenger, NetworkFactoryInfo>();
5332    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
5333            new HashMap<NetworkRequest, NetworkRequestInfo>();
5334
5335    private static class NetworkFactoryInfo {
5336        public final String name;
5337        public final Messenger messenger;
5338        public final AsyncChannel asyncChannel;
5339
5340        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
5341            this.name = name;
5342            this.messenger = messenger;
5343            this.asyncChannel = asyncChannel;
5344        }
5345    }
5346
5347    private class NetworkRequestInfo implements IBinder.DeathRecipient {
5348        static final boolean REQUEST = true;
5349        static final boolean LISTEN = false;
5350
5351        final NetworkRequest request;
5352        IBinder mBinder;
5353        final int mPid;
5354        final int mUid;
5355        final Messenger messenger;
5356        final boolean isRequest;
5357
5358        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
5359            super();
5360            messenger = m;
5361            request = r;
5362            mBinder = binder;
5363            mPid = getCallingPid();
5364            mUid = getCallingUid();
5365            this.isRequest = isRequest;
5366
5367            try {
5368                mBinder.linkToDeath(this, 0);
5369            } catch (RemoteException e) {
5370                binderDied();
5371            }
5372        }
5373
5374        void unlinkDeathRecipient() {
5375            mBinder.unlinkToDeath(this, 0);
5376        }
5377
5378        public void binderDied() {
5379            log("ConnectivityService NetworkRequestInfo binderDied(" +
5380                    request + ", " + mBinder + ")");
5381            releaseNetworkRequest(request);
5382        }
5383
5384        public String toString() {
5385            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
5386                    mPid + " for " + request;
5387        }
5388    }
5389
5390    @Override
5391    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
5392            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
5393        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
5394                == false) {
5395            enforceConnectivityInternalPermission();
5396        } else {
5397            enforceChangePermission();
5398        }
5399
5400        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
5401            throw new IllegalArgumentException("Bad timeout specified");
5402        }
5403        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5404                networkCapabilities), legacyType, nextNetworkRequestId());
5405        if (DBG) log("requestNetwork for " + networkRequest);
5406        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5407                NetworkRequestInfo.REQUEST);
5408
5409        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5410        if (timeoutMs > 0) {
5411            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5412                    nri), timeoutMs);
5413        }
5414        return networkRequest;
5415    }
5416
5417    @Override
5418    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5419            PendingIntent operation) {
5420        // TODO
5421        return null;
5422    }
5423
5424    @Override
5425    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5426            Messenger messenger, IBinder binder) {
5427        enforceAccessPermission();
5428
5429        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5430                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
5431        if (DBG) log("listenForNetwork for " + networkRequest);
5432        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5433                NetworkRequestInfo.LISTEN);
5434
5435        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5436        return networkRequest;
5437    }
5438
5439    @Override
5440    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5441            PendingIntent operation) {
5442    }
5443
5444    @Override
5445    public void releaseNetworkRequest(NetworkRequest networkRequest) {
5446        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
5447                0, networkRequest));
5448    }
5449
5450    @Override
5451    public void registerNetworkFactory(Messenger messenger, String name) {
5452        enforceConnectivityInternalPermission();
5453        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
5454        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
5455    }
5456
5457    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
5458        if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name);
5459        mNetworkFactoryInfos.put(nfi.messenger, nfi);
5460        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5461    }
5462
5463    @Override
5464    public void unregisterNetworkFactory(Messenger messenger) {
5465        enforceConnectivityInternalPermission();
5466        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5467    }
5468
5469    private void handleUnregisterNetworkFactory(Messenger messenger) {
5470        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5471        if (nfi == null) {
5472            if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory");
5473            return;
5474        }
5475        if (VDBG) log("unregisterNetworkFactory for " + nfi.name);
5476    }
5477
5478    /**
5479     * NetworkAgentInfo supporting a request by requestId.
5480     * These have already been vetted (their Capabilities satisfy the request)
5481     * and the are the highest scored network available.
5482     * the are keyed off the Requests requestId.
5483     */
5484    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
5485            new SparseArray<NetworkAgentInfo>();
5486
5487    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
5488            new SparseArray<NetworkAgentInfo>();
5489
5490    // NetworkAgentInfo keyed off its connecting messenger
5491    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
5492    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
5493            new HashMap<Messenger, NetworkAgentInfo>();
5494
5495    private final NetworkRequest mDefaultRequest;
5496
5497    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5498            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5499            int currentScore) {
5500        enforceConnectivityInternalPermission();
5501
5502        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(),
5503            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
5504            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler);
5505        if (VDBG) log("registerNetworkAgent " + nai);
5506        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
5507    }
5508
5509    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
5510        if (VDBG) log("Got NetworkAgent Messenger");
5511        mNetworkAgentInfos.put(na.messenger, na);
5512        synchronized (mNetworkForNetId) {
5513            mNetworkForNetId.put(na.network.netId, na);
5514        }
5515        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
5516        NetworkInfo networkInfo = na.networkInfo;
5517        na.networkInfo = null;
5518        updateNetworkInfo(na, networkInfo);
5519    }
5520
5521    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
5522        LinkProperties newLp = networkAgent.linkProperties;
5523        int netId = networkAgent.network.netId;
5524
5525        updateInterfaces(newLp, oldLp, netId);
5526        updateMtu(newLp, oldLp);
5527        // TODO - figure out what to do for clat
5528//        for (LinkProperties lp : newLp.getStackedLinks()) {
5529//            updateMtu(lp, null);
5530//        }
5531        updateRoutes(newLp, oldLp, netId);
5532        updateDnses(newLp, oldLp, netId);
5533        updateClat(newLp, oldLp, networkAgent);
5534    }
5535
5536    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
5537        // Update 464xlat state.
5538        if (mClat.requiresClat(na)) {
5539
5540            // If the connection was previously using clat, but is not using it now, stop the clat
5541            // daemon. Normally, this happens automatically when the connection disconnects, but if
5542            // the disconnect is not reported, or if the connection's LinkProperties changed for
5543            // some other reason (e.g., handoff changes the IP addresses on the link), it would
5544            // still be running. If it's not running, then stopping it is a no-op.
5545            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
5546                mClat.stopClat();
5547            }
5548            // If the link requires clat to be running, then start the daemon now.
5549            if (na.networkInfo.isConnected()) {
5550                mClat.startClat(na);
5551            } else {
5552                mClat.stopClat();
5553            }
5554        }
5555    }
5556
5557    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
5558        CompareResult<String> interfaceDiff = new CompareResult<String>();
5559        if (oldLp != null) {
5560            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
5561        } else if (newLp != null) {
5562            interfaceDiff.added = newLp.getAllInterfaceNames();
5563        }
5564        for (String iface : interfaceDiff.added) {
5565            try {
5566                mNetd.addInterfaceToNetwork(iface, netId);
5567            } catch (Exception e) {
5568                loge("Exception adding interface: " + e);
5569            }
5570        }
5571        for (String iface : interfaceDiff.removed) {
5572            try {
5573                mNetd.removeInterfaceFromNetwork(iface, netId);
5574            } catch (Exception e) {
5575                loge("Exception removing interface: " + e);
5576            }
5577        }
5578    }
5579
5580    private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
5581        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
5582        if (oldLp != null) {
5583            routeDiff = oldLp.compareAllRoutes(newLp);
5584        } else if (newLp != null) {
5585            routeDiff.added = newLp.getAllRoutes();
5586        }
5587
5588        // add routes before removing old in case it helps with continuous connectivity
5589
5590        // do this twice, adding non-nexthop routes first, then routes they are dependent on
5591        for (RouteInfo route : routeDiff.added) {
5592            if (route.hasGateway()) continue;
5593            try {
5594                mNetd.addRoute(netId, route);
5595            } catch (Exception e) {
5596                loge("Exception in addRoute for non-gateway: " + e);
5597            }
5598        }
5599        for (RouteInfo route : routeDiff.added) {
5600            if (route.hasGateway() == false) continue;
5601            try {
5602                mNetd.addRoute(netId, route);
5603            } catch (Exception e) {
5604                loge("Exception in addRoute for gateway: " + e);
5605            }
5606        }
5607
5608        for (RouteInfo route : routeDiff.removed) {
5609            try {
5610                mNetd.removeRoute(netId, route);
5611            } catch (Exception e) {
5612                loge("Exception in removeRoute: " + e);
5613            }
5614        }
5615    }
5616    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5617        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
5618            Collection<InetAddress> dnses = newLp.getDnsServers();
5619            if (dnses.size() == 0 && mDefaultDns != null) {
5620                dnses = new ArrayList();
5621                dnses.add(mDefaultDns);
5622                if (DBG) {
5623                    loge("no dns provided for netId " + netId + ", so using defaults");
5624                }
5625            }
5626            try {
5627                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
5628                    newLp.getDomains());
5629            } catch (Exception e) {
5630                loge("Exception in setDnsServersForNetwork: " + e);
5631            }
5632            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
5633            if (defaultNai != null && defaultNai.network.netId == netId) {
5634                setDefaultDnsSystemProperties(dnses);
5635            }
5636        }
5637    }
5638
5639    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
5640        int last = 0;
5641        for (InetAddress dns : dnses) {
5642            ++last;
5643            String key = "net.dns" + last;
5644            String value = dns.getHostAddress();
5645            SystemProperties.set(key, value);
5646        }
5647        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
5648            String key = "net.dns" + i;
5649            SystemProperties.set(key, "");
5650        }
5651        mNumDnsEntries = last;
5652    }
5653
5654
5655    private void updateCapabilities(NetworkAgentInfo networkAgent,
5656            NetworkCapabilities networkCapabilities) {
5657        // TODO - what else here?  Verify still satisfies everybody?
5658        // Check if satisfies somebody new?  call callbacks?
5659        synchronized (networkAgent) {
5660            networkAgent.networkCapabilities = networkCapabilities;
5661        }
5662    }
5663
5664    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5665        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5666        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
5667            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5668                    networkRequest);
5669        }
5670    }
5671
5672    private void callCallbackForRequest(NetworkRequestInfo nri,
5673            NetworkAgentInfo networkAgent, int notificationType) {
5674        if (nri.messenger == null) return;  // Default request has no msgr
5675        Object o;
5676        int a1 = 0;
5677        int a2 = 0;
5678        switch (notificationType) {
5679            case ConnectivityManager.CALLBACK_LOSING:
5680                a1 = 30 * 1000; // TODO - read this from NetworkMonitor
5681                // fall through
5682            case ConnectivityManager.CALLBACK_PRECHECK:
5683            case ConnectivityManager.CALLBACK_AVAILABLE:
5684            case ConnectivityManager.CALLBACK_LOST:
5685            case ConnectivityManager.CALLBACK_CAP_CHANGED:
5686            case ConnectivityManager.CALLBACK_IP_CHANGED: {
5687                o = new NetworkRequest(nri.request);
5688                a2 = networkAgent.network.netId;
5689                break;
5690            }
5691            case ConnectivityManager.CALLBACK_UNAVAIL:
5692            case ConnectivityManager.CALLBACK_RELEASED: {
5693                o = new NetworkRequest(nri.request);
5694                break;
5695            }
5696            default: {
5697                loge("Unknown notificationType " + notificationType);
5698                return;
5699            }
5700        }
5701        Message msg = Message.obtain();
5702        msg.arg1 = a1;
5703        msg.arg2 = a2;
5704        msg.obj = o;
5705        msg.what = notificationType;
5706        try {
5707            if (VDBG) log("sending notification " + notificationType + " for " + nri.request);
5708            nri.messenger.send(msg);
5709        } catch (RemoteException e) {
5710            // may occur naturally in the race of binder death.
5711            loge("RemoteException caught trying to send a callback msg for " + nri.request);
5712        }
5713    }
5714
5715    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5716        if (oldNetwork == null) {
5717            loge("Unknown NetworkAgentInfo in handleLingerComplete");
5718            return;
5719        }
5720        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
5721        if (DBG) {
5722            if (oldNetwork.networkRequests.size() != 0) {
5723                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
5724            }
5725        }
5726        oldNetwork.asyncChannel.disconnect();
5727    }
5728
5729    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
5730        if (newNetwork == null) {
5731            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
5732            return;
5733        }
5734        boolean keep = newNetwork.isVPN();
5735        boolean isNewDefault = false;
5736        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
5737        // check if any NetworkRequest wants this NetworkAgent
5738        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
5739        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
5740        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5741            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
5742            if (newNetwork == currentNetwork) {
5743                if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" +
5744                              " request " + nri.request.requestId + ". No change.");
5745                keep = true;
5746                continue;
5747            }
5748
5749            // check if it satisfies the NetworkCapabilities
5750            if (VDBG) log("  checking if request is satisfied: " + nri.request);
5751            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
5752                    newNetwork.networkCapabilities)) {
5753                // next check if it's better than any current network we're using for
5754                // this request
5755                if (VDBG) {
5756                    log("currentScore = " +
5757                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
5758                            ", newScore = " + newNetwork.currentScore);
5759                }
5760                if (currentNetwork == null ||
5761                        currentNetwork.currentScore < newNetwork.currentScore) {
5762                    if (currentNetwork != null) {
5763                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
5764                        currentNetwork.networkRequests.remove(nri.request.requestId);
5765                        currentNetwork.networkLingered.add(nri.request);
5766                        affectedNetworks.add(currentNetwork);
5767                    } else {
5768                        if (VDBG) log("   accepting network in place of null");
5769                    }
5770                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
5771                    newNetwork.addRequest(nri.request);
5772                    int legacyType = nri.request.legacyType;
5773                    if (legacyType != TYPE_NONE) {
5774                        mLegacyTypeTracker.add(legacyType, newNetwork);
5775                    }
5776                    keep = true;
5777                    // TODO - this could get expensive if we have alot of requests for this
5778                    // network.  Think about if there is a way to reduce this.  Push
5779                    // netid->request mapping to each factory?
5780                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
5781                    if (mDefaultRequest.requestId == nri.request.requestId) {
5782                        isNewDefault = true;
5783                        updateActiveDefaultNetwork(newNetwork);
5784                        if (newNetwork.linkProperties != null) {
5785                            setDefaultDnsSystemProperties(
5786                                    newNetwork.linkProperties.getDnsServers());
5787                        } else {
5788                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
5789                        }
5790                        mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5791                    }
5792                }
5793            }
5794        }
5795        for (NetworkAgentInfo nai : affectedNetworks) {
5796            boolean teardown = !nai.isVPN();
5797            for (int i = 0; i < nai.networkRequests.size() && teardown; i++) {
5798                NetworkRequest nr = nai.networkRequests.valueAt(i);
5799                try {
5800                if (mNetworkRequests.get(nr).isRequest) {
5801                    teardown = false;
5802                }
5803                } catch (Exception e) {
5804                    loge("Request " + nr + " not found in mNetworkRequests.");
5805                    loge("  it came from request list  of " + nai.name());
5806                }
5807            }
5808            if (teardown) {
5809                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
5810                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
5811            } else {
5812                // not going to linger, so kill the list of linger networks..  only
5813                // notify them of linger if it happens as the result of gaining another,
5814                // but if they transition and old network stays up, don't tell them of linger
5815                // or very delayed loss
5816                nai.networkLingered.clear();
5817                if (VDBG) log("Lingered for " + nai.name() + " cleared");
5818            }
5819        }
5820        if (keep) {
5821            if (isNewDefault) {
5822                if (VDBG) log("Switching to new default network: " + newNetwork);
5823                setupDataActivityTracking(newNetwork);
5824                try {
5825                    mNetd.setDefaultNetId(newNetwork.network.netId);
5826                } catch (Exception e) {
5827                    loge("Exception setting default network :" + e);
5828                }
5829                if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) {
5830                    handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
5831                }
5832                synchronized (ConnectivityService.this) {
5833                    // have a new default network, release the transition wakelock in
5834                    // a second if it's held.  The second pause is to allow apps
5835                    // to reconnect over the new network
5836                    if (mNetTransitionWakeLock.isHeld()) {
5837                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
5838                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
5839                                mNetTransitionWakeLockSerialNumber, 0),
5840                                1000);
5841                    }
5842                }
5843
5844                // this will cause us to come up initially as unconnected and switching
5845                // to connected after our normal pause unless somebody reports us as
5846                // really disconnected
5847                mDefaultInetConditionPublished = 0;
5848                mDefaultConnectionSequence++;
5849                mInetConditionChangeInFlight = false;
5850                // TODO - read the tcp buffer size config string from somewhere
5851                // updateNetworkSettings();
5852            }
5853            // notify battery stats service about this network
5854            try {
5855                BatteryStatsService.getService().noteNetworkInterfaceType(
5856                        newNetwork.linkProperties.getInterfaceName(),
5857                        newNetwork.networkInfo.getType());
5858            } catch (RemoteException e) { }
5859            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
5860        } else {
5861            if (DBG && newNetwork.networkRequests.size() != 0) {
5862                loge("tearing down network with live requests:");
5863                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
5864                    loge("  " + newNetwork.networkRequests.valueAt(i));
5865                }
5866            }
5867            if (VDBG) log("Validated network turns out to be unwanted.  Tear it down.");
5868            newNetwork.asyncChannel.disconnect();
5869        }
5870    }
5871
5872
5873    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5874        NetworkInfo.State state = newInfo.getState();
5875        NetworkInfo oldInfo = null;
5876        synchronized (networkAgent) {
5877            oldInfo = networkAgent.networkInfo;
5878            networkAgent.networkInfo = newInfo;
5879        }
5880        if (networkAgent.isVPN() && mLockdownTracker != null) {
5881            mLockdownTracker.onVpnStateChanged(newInfo);
5882        }
5883
5884        if (oldInfo != null && oldInfo.getState() == state) {
5885            if (VDBG) log("ignoring duplicate network state non-change");
5886            return;
5887        }
5888        if (DBG) {
5889            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5890                    (oldInfo == null ? "null" : oldInfo.getState()) +
5891                    " to " + state);
5892        }
5893
5894        if (state == NetworkInfo.State.CONNECTED) {
5895            try {
5896                // This is likely caused by the fact that this network already
5897                // exists. An example is when a network goes from CONNECTED to
5898                // CONNECTING and back (like wifi on DHCP renew).
5899                // TODO: keep track of which networks we've created, or ask netd
5900                // to tell us whether we've already created this network or not.
5901                if (networkAgent.isVPN()) {
5902                    mNetd.createVirtualNetwork(networkAgent.network.netId,
5903                            !networkAgent.linkProperties.getDnsServers().isEmpty());
5904                } else {
5905                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
5906                }
5907            } catch (Exception e) {
5908                loge("Error creating network " + networkAgent.network.netId + ": "
5909                        + e.getMessage());
5910                return;
5911            }
5912
5913            updateLinkProperties(networkAgent, null);
5914            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
5915            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
5916            if (networkAgent.isVPN()) {
5917                // Temporarily disable the default proxy (not global).
5918                synchronized (mProxyLock) {
5919                    if (!mDefaultProxyDisabled) {
5920                        mDefaultProxyDisabled = true;
5921                        if (mGlobalProxy == null && mDefaultProxy != null) {
5922                            sendProxyBroadcast(null);
5923                        }
5924                    }
5925                }
5926                // TODO: support proxy per network.
5927            }
5928        } else if (state == NetworkInfo.State.DISCONNECTED ||
5929                state == NetworkInfo.State.SUSPENDED) {
5930            networkAgent.asyncChannel.disconnect();
5931            if (networkAgent.isVPN()) {
5932                synchronized (mProxyLock) {
5933                    if (mDefaultProxyDisabled) {
5934                        mDefaultProxyDisabled = false;
5935                        if (mGlobalProxy == null && mDefaultProxy != null) {
5936                            sendProxyBroadcast(mDefaultProxy);
5937                        }
5938                    }
5939                }
5940            }
5941        }
5942    }
5943
5944    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
5945        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
5946
5947        nai.currentScore = score;
5948
5949        // TODO - This will not do the right thing if this network is lowering
5950        // its score and has requests that can be served by other
5951        // currently-active networks, or if the network is increasing its
5952        // score and other networks have requests that can be better served
5953        // by this network.
5954        //
5955        // Really we want to see if any of our requests migrate to other
5956        // active/lingered networks and if any other requests migrate to us (depending
5957        // on increasing/decreasing currentScore.  That's a bit of work and probably our
5958        // score checking/network allocation code needs to be modularized so we can understand
5959        // (see handleConnectionValided for an example).
5960        //
5961        // As a first order approx, lets just advertise the new score to factories.  If
5962        // somebody can beat it they will nominate a network and our normal net replacement
5963        // code will fire.
5964        for (int i = 0; i < nai.networkRequests.size(); i++) {
5965            NetworkRequest nr = nai.networkRequests.valueAt(i);
5966            sendUpdatedScoreToFactories(nr, score);
5967        }
5968    }
5969
5970    // notify only this one new request of the current state
5971    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5972        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5973        // TODO - read state from monitor to decide what to send.
5974//        if (nai.networkMonitor.isLingering()) {
5975//            notifyType = NetworkCallbacks.LOSING;
5976//        } else if (nai.networkMonitor.isEvaluating()) {
5977//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5978//        }
5979        callCallbackForRequest(nri, nai, notifyType);
5980    }
5981
5982    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
5983        if (connected) {
5984            NetworkInfo info = new NetworkInfo(nai.networkInfo);
5985            info.setType(type);
5986            sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
5987        } else {
5988            NetworkInfo info = new NetworkInfo(nai.networkInfo);
5989            info.setType(type);
5990            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5991            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5992            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5993            if (info.isFailover()) {
5994                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5995                nai.networkInfo.setFailover(false);
5996            }
5997            if (info.getReason() != null) {
5998                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5999            }
6000            if (info.getExtraInfo() != null) {
6001                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6002            }
6003            NetworkAgentInfo newDefaultAgent = null;
6004            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
6005                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
6006                if (newDefaultAgent != null) {
6007                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6008                            newDefaultAgent.networkInfo);
6009                } else {
6010                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6011                }
6012            }
6013            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6014                    mDefaultInetConditionPublished);
6015            final Intent immediateIntent = new Intent(intent);
6016            immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
6017            sendStickyBroadcast(immediateIntent);
6018            sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
6019            if (newDefaultAgent != null) {
6020                sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
6021                getConnectivityChangeDelay());
6022            }
6023        }
6024    }
6025
6026    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6027        if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name());
6028        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
6029            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
6030            NetworkRequestInfo nri = mNetworkRequests.get(nr);
6031            if (VDBG) log(" sending notification for " + nr);
6032            callCallbackForRequest(nri, networkAgent, notifyType);
6033        }
6034    }
6035
6036    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
6037        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6038        if (nai != null) {
6039            synchronized (nai) {
6040                return new LinkProperties(nai.linkProperties);
6041            }
6042        }
6043        return new LinkProperties();
6044    }
6045
6046    private NetworkInfo getNetworkInfoForType(int networkType) {
6047        if (!mLegacyTypeTracker.isTypeSupported(networkType))
6048            return null;
6049
6050        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6051        if (nai != null) {
6052            NetworkInfo result = new NetworkInfo(nai.networkInfo);
6053            result.setType(networkType);
6054            return result;
6055        } else {
6056           return new NetworkInfo(networkType, 0, "Unknown", "");
6057        }
6058    }
6059
6060    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
6061        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6062        if (nai != null) {
6063            synchronized (nai) {
6064                return new NetworkCapabilities(nai.networkCapabilities);
6065            }
6066        }
6067        return new NetworkCapabilities();
6068    }
6069}
6070