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