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