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