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