ConnectivityService.java revision 620a5466ce5f401aafa6a438383016640ec51d1a
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    // Called when we lose the default network and have no replacement yet.
3630    // This will automatically be cleared after X seconds or a new default network
3631    // becomes CONNECTED, whichever happens first.  The timer is started by the
3632    // first caller and not restarted by subsequent callers.
3633    private void requestNetworkTransitionWakelock(String forWhom) {
3634        int serialNum = 0;
3635        synchronized (this) {
3636            if (mNetTransitionWakeLock.isHeld()) return;
3637            serialNum = ++mNetTransitionWakeLockSerialNumber;
3638            mNetTransitionWakeLock.acquire();
3639            mNetTransitionWakeLockCausedBy = forWhom;
3640        }
3641        mHandler.sendMessageDelayed(mHandler.obtainMessage(
3642                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
3643                mNetTransitionWakeLockTimeout);
3644        return;
3645    }
3646
3647    // 100 percent is full good, 0 is full bad.
3648    public void reportInetCondition(int networkType, int percentage) {
3649        if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3650        mContext.enforceCallingOrSelfPermission(
3651                android.Manifest.permission.STATUS_BAR,
3652                "ConnectivityService");
3653
3654        if (DBG) {
3655            int pid = getCallingPid();
3656            int uid = getCallingUid();
3657            String s = pid + "(" + uid + ") reports inet is " +
3658                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3659                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3660            mInetLog.add(s);
3661            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3662                mInetLog.remove(0);
3663            }
3664        }
3665        mHandler.sendMessage(mHandler.obtainMessage(
3666            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3667    }
3668
3669    public void reportBadNetwork(Network network) {
3670        //TODO
3671    }
3672
3673    private void handleInetConditionChange(int netType, int condition) {
3674        if (mActiveDefaultNetwork == -1) {
3675            if (DBG) log("handleInetConditionChange: no active default network - ignore");
3676            return;
3677        }
3678        if (mActiveDefaultNetwork != netType) {
3679            if (DBG) log("handleInetConditionChange: net=" + netType +
3680                            " != default=" + mActiveDefaultNetwork + " - ignore");
3681            return;
3682        }
3683        if (VDBG) {
3684            log("handleInetConditionChange: net=" +
3685                    netType + ", condition=" + condition +
3686                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3687        }
3688        mDefaultInetCondition = condition;
3689        int delay;
3690        if (mInetConditionChangeInFlight == false) {
3691            if (VDBG) log("handleInetConditionChange: starting a change hold");
3692            // setup a new hold to debounce this
3693            if (mDefaultInetCondition > 50) {
3694                delay = Settings.Global.getInt(mContext.getContentResolver(),
3695                        Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3696            } else {
3697                delay = Settings.Global.getInt(mContext.getContentResolver(),
3698                        Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3699            }
3700            mInetConditionChangeInFlight = true;
3701            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3702                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3703        } else {
3704            // we've set the new condition, when this hold ends that will get picked up
3705            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3706        }
3707    }
3708
3709    private void handleInetConditionHoldEnd(int netType, int sequence) {
3710        if (DBG) {
3711            log("handleInetConditionHoldEnd: net=" + netType +
3712                    ", condition=" + mDefaultInetCondition +
3713                    ", published condition=" + mDefaultInetConditionPublished);
3714        }
3715        mInetConditionChangeInFlight = false;
3716
3717        if (mActiveDefaultNetwork == -1) {
3718            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3719            return;
3720        }
3721        if (mDefaultConnectionSequence != sequence) {
3722            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3723            return;
3724        }
3725        // TODO: Figure out why this optimization sometimes causes a
3726        //       change in mDefaultInetCondition to be missed and the
3727        //       UI to not be updated.
3728        //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3729        //    if (DBG) log("no change in condition - aborting");
3730        //    return;
3731        //}
3732        NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork);
3733        if (networkInfo.isConnected() == false) {
3734            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3735            return;
3736        }
3737        mDefaultInetConditionPublished = mDefaultInetCondition;
3738        sendInetConditionBroadcast(networkInfo);
3739        return;
3740    }
3741
3742    public ProxyInfo getProxy() {
3743        // this information is already available as a world read/writable jvm property
3744        // so this API change wouldn't have a benifit.  It also breaks the passing
3745        // of proxy info to all the JVMs.
3746        // enforceAccessPermission();
3747        synchronized (mProxyLock) {
3748            ProxyInfo ret = mGlobalProxy;
3749            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3750            return ret;
3751        }
3752    }
3753
3754    public void setGlobalProxy(ProxyInfo proxyProperties) {
3755        enforceConnectivityInternalPermission();
3756
3757        synchronized (mProxyLock) {
3758            if (proxyProperties == mGlobalProxy) return;
3759            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3760            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3761
3762            String host = "";
3763            int port = 0;
3764            String exclList = "";
3765            String pacFileUrl = "";
3766            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3767                    (proxyProperties.getPacFileUrl() != null))) {
3768                if (!proxyProperties.isValid()) {
3769                    if (DBG)
3770                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3771                    return;
3772                }
3773                mGlobalProxy = new ProxyInfo(proxyProperties);
3774                host = mGlobalProxy.getHost();
3775                port = mGlobalProxy.getPort();
3776                exclList = mGlobalProxy.getExclusionListAsString();
3777                if (proxyProperties.getPacFileUrl() != null) {
3778                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
3779                }
3780            } else {
3781                mGlobalProxy = null;
3782            }
3783            ContentResolver res = mContext.getContentResolver();
3784            final long token = Binder.clearCallingIdentity();
3785            try {
3786                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3787                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3788                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3789                        exclList);
3790                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3791            } finally {
3792                Binder.restoreCallingIdentity(token);
3793            }
3794        }
3795
3796        if (mGlobalProxy == null) {
3797            proxyProperties = mDefaultProxy;
3798        }
3799        sendProxyBroadcast(proxyProperties);
3800    }
3801
3802    private void loadGlobalProxy() {
3803        ContentResolver res = mContext.getContentResolver();
3804        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3805        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3806        String exclList = Settings.Global.getString(res,
3807                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3808        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3809        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3810            ProxyInfo proxyProperties;
3811            if (!TextUtils.isEmpty(pacFileUrl)) {
3812                proxyProperties = new ProxyInfo(pacFileUrl);
3813            } else {
3814                proxyProperties = new ProxyInfo(host, port, exclList);
3815            }
3816            if (!proxyProperties.isValid()) {
3817                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3818                return;
3819            }
3820
3821            synchronized (mProxyLock) {
3822                mGlobalProxy = proxyProperties;
3823            }
3824        }
3825    }
3826
3827    public ProxyInfo getGlobalProxy() {
3828        // this information is already available as a world read/writable jvm property
3829        // so this API change wouldn't have a benifit.  It also breaks the passing
3830        // of proxy info to all the JVMs.
3831        // enforceAccessPermission();
3832        synchronized (mProxyLock) {
3833            return mGlobalProxy;
3834        }
3835    }
3836
3837    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3838        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3839                && (proxy.getPacFileUrl() == null)) {
3840            proxy = null;
3841        }
3842        synchronized (mProxyLock) {
3843            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3844            if (mDefaultProxy == proxy) return; // catches repeated nulls
3845            if (proxy != null &&  !proxy.isValid()) {
3846                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3847                return;
3848            }
3849
3850            // This call could be coming from the PacManager, containing the port of the local
3851            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3852            // global (to get the correct local port), and send a broadcast.
3853            // TODO: Switch PacManager to have its own message to send back rather than
3854            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3855            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
3856                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3857                mGlobalProxy = proxy;
3858                sendProxyBroadcast(mGlobalProxy);
3859                return;
3860            }
3861            mDefaultProxy = proxy;
3862
3863            if (mGlobalProxy != null) return;
3864            if (!mDefaultProxyDisabled) {
3865                sendProxyBroadcast(proxy);
3866            }
3867        }
3868    }
3869
3870    private void handleDeprecatedGlobalHttpProxy() {
3871        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3872                Settings.Global.HTTP_PROXY);
3873        if (!TextUtils.isEmpty(proxy)) {
3874            String data[] = proxy.split(":");
3875            if (data.length == 0) {
3876                return;
3877            }
3878
3879            String proxyHost =  data[0];
3880            int proxyPort = 8080;
3881            if (data.length > 1) {
3882                try {
3883                    proxyPort = Integer.parseInt(data[1]);
3884                } catch (NumberFormatException e) {
3885                    return;
3886                }
3887            }
3888            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3889            setGlobalProxy(p);
3890        }
3891    }
3892
3893    private void sendProxyBroadcast(ProxyInfo proxy) {
3894        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3895        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3896        if (DBG) log("sending Proxy Broadcast for " + proxy);
3897        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3898        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3899            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3900        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3901        final long ident = Binder.clearCallingIdentity();
3902        try {
3903            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3904        } finally {
3905            Binder.restoreCallingIdentity(ident);
3906        }
3907    }
3908
3909    private static class SettingsObserver extends ContentObserver {
3910        private int mWhat;
3911        private Handler mHandler;
3912        SettingsObserver(Handler handler, int what) {
3913            super(handler);
3914            mHandler = handler;
3915            mWhat = what;
3916        }
3917
3918        void observe(Context context) {
3919            ContentResolver resolver = context.getContentResolver();
3920            resolver.registerContentObserver(Settings.Global.getUriFor(
3921                    Settings.Global.HTTP_PROXY), false, this);
3922        }
3923
3924        @Override
3925        public void onChange(boolean selfChange) {
3926            mHandler.obtainMessage(mWhat).sendToTarget();
3927        }
3928    }
3929
3930    private static void log(String s) {
3931        Slog.d(TAG, s);
3932    }
3933
3934    private static void loge(String s) {
3935        Slog.e(TAG, s);
3936    }
3937
3938    int convertFeatureToNetworkType(int networkType, String feature) {
3939        int usedNetworkType = networkType;
3940
3941        if(networkType == ConnectivityManager.TYPE_MOBILE) {
3942            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3943                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3944            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3945                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3946            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3947                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3948                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3949            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3950                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3951            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3952                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3953            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3954                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3955            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3956                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3957            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) {
3958                usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY;
3959            } else {
3960                Slog.e(TAG, "Can't match any mobile netTracker!");
3961            }
3962        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3963            if (TextUtils.equals(feature, "p2p")) {
3964                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3965            } else {
3966                Slog.e(TAG, "Can't match any wifi netTracker!");
3967            }
3968        } else {
3969            Slog.e(TAG, "Unexpected network type");
3970        }
3971        return usedNetworkType;
3972    }
3973
3974    private static <T> T checkNotNull(T value, String message) {
3975        if (value == null) {
3976            throw new NullPointerException(message);
3977        }
3978        return value;
3979    }
3980
3981    /**
3982     * Protect a socket from VPN routing rules. This method is used by
3983     * VpnBuilder and not available in ConnectivityManager. Permissions
3984     * are checked in Vpn class.
3985     * @hide
3986     */
3987    @Override
3988    public boolean protectVpn(ParcelFileDescriptor socket) {
3989        throwIfLockdownEnabled();
3990        try {
3991            int type = mActiveDefaultNetwork;
3992            int user = UserHandle.getUserId(Binder.getCallingUid());
3993            if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3994                synchronized(mVpns) {
3995                    mVpns.get(user).protect(socket);
3996                }
3997                return true;
3998            }
3999        } catch (Exception e) {
4000            // ignore
4001        } finally {
4002            try {
4003                socket.close();
4004            } catch (Exception e) {
4005                // ignore
4006            }
4007        }
4008        return false;
4009    }
4010
4011    /**
4012     * Prepare for a VPN application. This method is used by VpnDialogs
4013     * and not available in ConnectivityManager. Permissions are checked
4014     * in Vpn class.
4015     * @hide
4016     */
4017    @Override
4018    public boolean prepareVpn(String oldPackage, String newPackage) {
4019        throwIfLockdownEnabled();
4020        int user = UserHandle.getUserId(Binder.getCallingUid());
4021        synchronized(mVpns) {
4022            return mVpns.get(user).prepare(oldPackage, newPackage);
4023        }
4024    }
4025
4026    @Override
4027    public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
4028        enforceMarkNetworkSocketPermission();
4029        final long token = Binder.clearCallingIdentity();
4030        try {
4031            int mark = mNetd.getMarkForUid(uid);
4032            // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
4033            if (mark == -1) {
4034                mark = 0;
4035            }
4036            NetworkUtils.markSocket(socket.getFd(), mark);
4037        } catch (RemoteException e) {
4038        } finally {
4039            Binder.restoreCallingIdentity(token);
4040        }
4041    }
4042
4043    /**
4044     * Configure a TUN interface and return its file descriptor. Parameters
4045     * are encoded and opaque to this class. This method is used by VpnBuilder
4046     * and not available in ConnectivityManager. Permissions are checked in
4047     * Vpn class.
4048     * @hide
4049     */
4050    @Override
4051    public ParcelFileDescriptor establishVpn(VpnConfig config) {
4052        throwIfLockdownEnabled();
4053        int user = UserHandle.getUserId(Binder.getCallingUid());
4054        synchronized(mVpns) {
4055            return mVpns.get(user).establish(config);
4056        }
4057    }
4058
4059    /**
4060     * Start legacy VPN, controlling native daemons as needed. Creates a
4061     * secondary thread to perform connection work, returning quickly.
4062     */
4063    @Override
4064    public void startLegacyVpn(VpnProfile profile) {
4065        throwIfLockdownEnabled();
4066        final LinkProperties egress = getActiveLinkProperties();
4067        if (egress == null) {
4068            throw new IllegalStateException("Missing active network connection");
4069        }
4070        int user = UserHandle.getUserId(Binder.getCallingUid());
4071        synchronized(mVpns) {
4072            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4073        }
4074    }
4075
4076    /**
4077     * Return the information of the ongoing legacy VPN. This method is used
4078     * by VpnSettings and not available in ConnectivityManager. Permissions
4079     * are checked in Vpn class.
4080     * @hide
4081     */
4082    @Override
4083    public LegacyVpnInfo getLegacyVpnInfo() {
4084        throwIfLockdownEnabled();
4085        int user = UserHandle.getUserId(Binder.getCallingUid());
4086        synchronized(mVpns) {
4087            return mVpns.get(user).getLegacyVpnInfo();
4088        }
4089    }
4090
4091    /**
4092     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
4093     * not available in ConnectivityManager.
4094     * Permissions are checked in Vpn class.
4095     * @hide
4096     */
4097    @Override
4098    public VpnConfig getVpnConfig() {
4099        int user = UserHandle.getUserId(Binder.getCallingUid());
4100        synchronized(mVpns) {
4101            return mVpns.get(user).getVpnConfig();
4102        }
4103    }
4104
4105    /**
4106     * Callback for VPN subsystem. Currently VPN is not adapted to the service
4107     * through NetworkStateTracker since it works differently. For example, it
4108     * needs to override DNS servers but never takes the default routes. It
4109     * relies on another data network, and it could keep existing connections
4110     * alive after reconnecting, switching between networks, or even resuming
4111     * from deep sleep. Calls from applications should be done synchronously
4112     * to avoid race conditions. As these are all hidden APIs, refactoring can
4113     * be done whenever a better abstraction is developed.
4114     */
4115    public class VpnCallback {
4116        private VpnCallback() {
4117        }
4118
4119        public void onStateChanged(NetworkInfo info) {
4120            mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
4121        }
4122
4123        public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
4124            if (dnsServers == null) {
4125                restore();
4126                return;
4127            }
4128
4129            // Convert DNS servers into addresses.
4130            List<InetAddress> addresses = new ArrayList<InetAddress>();
4131            for (String address : dnsServers) {
4132                // Double check the addresses and remove invalid ones.
4133                try {
4134                    addresses.add(InetAddress.parseNumericAddress(address));
4135                } catch (Exception e) {
4136                    // ignore
4137                }
4138            }
4139            if (addresses.isEmpty()) {
4140                restore();
4141                return;
4142            }
4143
4144            // Concatenate search domains into a string.
4145            StringBuilder buffer = new StringBuilder();
4146            if (searchDomains != null) {
4147                for (String domain : searchDomains) {
4148                    buffer.append(domain).append(' ');
4149                }
4150            }
4151            String domains = buffer.toString().trim();
4152
4153            // Apply DNS changes.
4154            synchronized (mDnsLock) {
4155                // TODO: Re-enable this when the netId of the VPN is known.
4156                // updateDnsLocked("VPN", netId, addresses, domains);
4157            }
4158
4159            // Temporarily disable the default proxy (not global).
4160            synchronized (mProxyLock) {
4161                mDefaultProxyDisabled = true;
4162                if (mGlobalProxy == null && mDefaultProxy != null) {
4163                    sendProxyBroadcast(null);
4164                }
4165            }
4166
4167            // TODO: support proxy per network.
4168        }
4169
4170        public void restore() {
4171            synchronized (mProxyLock) {
4172                mDefaultProxyDisabled = false;
4173                if (mGlobalProxy == null && mDefaultProxy != null) {
4174                    sendProxyBroadcast(mDefaultProxy);
4175                }
4176            }
4177        }
4178
4179        public void protect(ParcelFileDescriptor socket) {
4180            try {
4181                final int mark = mNetd.getMarkForProtect();
4182                NetworkUtils.markSocket(socket.getFd(), mark);
4183            } catch (RemoteException e) {
4184            }
4185        }
4186
4187        public void setRoutes(String interfaze, List<RouteInfo> routes) {
4188            for (RouteInfo route : routes) {
4189                try {
4190                    mNetd.setMarkedForwardingRoute(interfaze, route);
4191                } catch (RemoteException e) {
4192                }
4193            }
4194        }
4195
4196        public void setMarkedForwarding(String interfaze) {
4197            try {
4198                mNetd.setMarkedForwarding(interfaze);
4199            } catch (RemoteException e) {
4200            }
4201        }
4202
4203        public void clearMarkedForwarding(String interfaze) {
4204            try {
4205                mNetd.clearMarkedForwarding(interfaze);
4206            } catch (RemoteException e) {
4207            }
4208        }
4209
4210        public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
4211            int uidStart = uid * UserHandle.PER_USER_RANGE;
4212            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
4213            addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
4214        }
4215
4216        public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
4217            int uidStart = uid * UserHandle.PER_USER_RANGE;
4218            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
4219            clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
4220        }
4221
4222        public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
4223                boolean forwardDns) {
4224            // TODO: Re-enable this when the netId of the VPN is known.
4225            // try {
4226            //     mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns);
4227            // } catch (RemoteException e) {
4228            // }
4229
4230        }
4231
4232        public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
4233                boolean forwardDns) {
4234            // TODO: Re-enable this when the netId of the VPN is known.
4235            // try {
4236            //     mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
4237            // } catch (RemoteException e) {
4238            // }
4239
4240        }
4241    }
4242
4243    @Override
4244    public boolean updateLockdownVpn() {
4245        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4246            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4247            return false;
4248        }
4249
4250        // Tear down existing lockdown if profile was removed
4251        mLockdownEnabled = LockdownVpnTracker.isEnabled();
4252        if (mLockdownEnabled) {
4253            if (!mKeyStore.isUnlocked()) {
4254                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
4255                return false;
4256            }
4257
4258            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
4259            final VpnProfile profile = VpnProfile.decode(
4260                    profileName, mKeyStore.get(Credentials.VPN + profileName));
4261            int user = UserHandle.getUserId(Binder.getCallingUid());
4262            synchronized(mVpns) {
4263                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
4264                            profile));
4265            }
4266        } else {
4267            setLockdownTracker(null);
4268        }
4269
4270        return true;
4271    }
4272
4273    /**
4274     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4275     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4276     */
4277    private void setLockdownTracker(LockdownVpnTracker tracker) {
4278        // Shutdown any existing tracker
4279        final LockdownVpnTracker existing = mLockdownTracker;
4280        mLockdownTracker = null;
4281        if (existing != null) {
4282            existing.shutdown();
4283        }
4284
4285        try {
4286            if (tracker != null) {
4287                mNetd.setFirewallEnabled(true);
4288                mNetd.setFirewallInterfaceRule("lo", true);
4289                mLockdownTracker = tracker;
4290                mLockdownTracker.init();
4291            } else {
4292                mNetd.setFirewallEnabled(false);
4293            }
4294        } catch (RemoteException e) {
4295            // ignored; NMS lives inside system_server
4296        }
4297    }
4298
4299    private void throwIfLockdownEnabled() {
4300        if (mLockdownEnabled) {
4301            throw new IllegalStateException("Unavailable in lockdown mode");
4302        }
4303    }
4304
4305    public void supplyMessenger(int networkType, Messenger messenger) {
4306        enforceConnectivityInternalPermission();
4307
4308        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
4309            mNetTrackers[networkType].supplyMessenger(messenger);
4310        }
4311    }
4312
4313    public int findConnectionTypeForIface(String iface) {
4314        enforceConnectivityInternalPermission();
4315
4316        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
4317        for (NetworkStateTracker tracker : mNetTrackers) {
4318            if (tracker != null) {
4319                LinkProperties lp = tracker.getLinkProperties();
4320                if (lp != null && iface.equals(lp.getInterfaceName())) {
4321                    return tracker.getNetworkInfo().getType();
4322                }
4323            }
4324        }
4325        return ConnectivityManager.TYPE_NONE;
4326    }
4327
4328    /**
4329     * Have mobile data fail fast if enabled.
4330     *
4331     * @param enabled DctConstants.ENABLED/DISABLED
4332     */
4333    private void setEnableFailFastMobileData(int enabled) {
4334        int tag;
4335
4336        if (enabled == DctConstants.ENABLED) {
4337            tag = mEnableFailFastMobileDataTag.incrementAndGet();
4338        } else {
4339            tag = mEnableFailFastMobileDataTag.get();
4340        }
4341        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
4342                         enabled));
4343    }
4344
4345    private boolean isMobileDataStateTrackerReady() {
4346        MobileDataStateTracker mdst =
4347                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4348        return (mdst != null) && (mdst.isReady());
4349    }
4350
4351    /**
4352     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
4353     */
4354
4355    /**
4356     * No connection was possible to the network.
4357     * This is NOT a warm sim.
4358     */
4359    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
4360
4361    /**
4362     * A connection was made to the internet, all is well.
4363     * This is NOT a warm sim.
4364     */
4365    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
4366
4367    /**
4368     * A connection was made but no dns server was available to resolve a name to address.
4369     * This is NOT a warm sim since provisioning network is supported.
4370     */
4371    private static final int CMP_RESULT_CODE_NO_DNS = 2;
4372
4373    /**
4374     * A connection was made but could not open a TCP connection.
4375     * This is NOT a warm sim since provisioning network is supported.
4376     */
4377    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
4378
4379    /**
4380     * A connection was made but there was a redirection, we appear to be in walled garden.
4381     * This is an indication of a warm sim on a mobile network such as T-Mobile.
4382     */
4383    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
4384
4385    /**
4386     * The mobile network is a provisioning network.
4387     * This is an indication of a warm sim on a mobile network such as AT&T.
4388     */
4389    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
4390
4391    /**
4392     * The mobile network is provisioning
4393     */
4394    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
4395
4396    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
4397    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
4398
4399    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
4400
4401    @Override
4402    public int checkMobileProvisioning(int suggestedTimeOutMs) {
4403        int timeOutMs = -1;
4404        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4405        enforceConnectivityInternalPermission();
4406
4407        final long token = Binder.clearCallingIdentity();
4408        try {
4409            timeOutMs = suggestedTimeOutMs;
4410            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4411                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4412            }
4413
4414            // Check that mobile networks are supported
4415            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4416                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4417                if (DBG) log("checkMobileProvisioning: X no mobile network");
4418                return timeOutMs;
4419            }
4420
4421            // If we're already checking don't do it again
4422            // TODO: Add a queue of results...
4423            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4424                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4425                return timeOutMs;
4426            }
4427
4428            // Start off with mobile notification off
4429            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4430
4431            CheckMp checkMp = new CheckMp(mContext, this);
4432            CheckMp.CallBack cb = new CheckMp.CallBack() {
4433                @Override
4434                void onComplete(Integer result) {
4435                    if (DBG) log("CheckMp.onComplete: result=" + result);
4436                    NetworkInfo ni =
4437                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4438                    switch(result) {
4439                        case CMP_RESULT_CODE_CONNECTABLE:
4440                        case CMP_RESULT_CODE_NO_CONNECTION:
4441                        case CMP_RESULT_CODE_NO_DNS:
4442                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
4443                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
4444                            break;
4445                        }
4446                        case CMP_RESULT_CODE_REDIRECTED: {
4447                            if (DBG) log("CheckMp.onComplete: warm sim");
4448                            String url = getMobileProvisioningUrl();
4449                            if (TextUtils.isEmpty(url)) {
4450                                url = getMobileRedirectedProvisioningUrl();
4451                            }
4452                            if (TextUtils.isEmpty(url) == false) {
4453                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4454                                setProvNotificationVisible(true,
4455                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4456                                        url);
4457                            } else {
4458                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
4459                            }
4460                            break;
4461                        }
4462                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
4463                            String url = getMobileProvisioningUrl();
4464                            if (TextUtils.isEmpty(url) == false) {
4465                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4466                                setProvNotificationVisible(true,
4467                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4468                                        url);
4469                                // Mark that we've got a provisioning network and
4470                                // Disable Mobile Data until user actually starts provisioning.
4471                                mIsProvisioningNetwork.set(true);
4472                                MobileDataStateTracker mdst = (MobileDataStateTracker)
4473                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4474
4475                                // Disable radio until user starts provisioning
4476                                mdst.setRadio(false);
4477                            } else {
4478                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
4479                            }
4480                            break;
4481                        }
4482                        case CMP_RESULT_CODE_IS_PROVISIONING: {
4483                            // FIXME: Need to know when provisioning is done. Probably we can
4484                            // check the completion status if successful we're done if we
4485                            // "timedout" or still connected to provisioning APN turn off data?
4486                            if (DBG) log("CheckMp.onComplete: provisioning started");
4487                            mIsStartingProvisioning.set(false);
4488                            break;
4489                        }
4490                        default: {
4491                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
4492                            break;
4493                        }
4494                    }
4495                    mIsCheckingMobileProvisioning.set(false);
4496                }
4497            };
4498            CheckMp.Params params =
4499                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
4500            if (DBG) log("checkMobileProvisioning: params=" + params);
4501            // TODO: Reenable when calls to the now defunct
4502            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
4503            //       This code should be moved to the Telephony code.
4504            // checkMp.execute(params);
4505        } finally {
4506            Binder.restoreCallingIdentity(token);
4507            if (DBG) log("checkMobileProvisioning: X");
4508        }
4509        return timeOutMs;
4510    }
4511
4512    static class CheckMp extends
4513            AsyncTask<CheckMp.Params, Void, Integer> {
4514        private static final String CHECKMP_TAG = "CheckMp";
4515
4516        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4517        private static boolean mTestingFailures;
4518
4519        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4520        private static final int MAX_LOOPS = 4;
4521
4522        // Number of milli-seconds to complete all of the retires
4523        public static final int MAX_TIMEOUT_MS =  60000;
4524
4525        // The socket should retry only 5 seconds, the default is longer
4526        private static final int SOCKET_TIMEOUT_MS = 5000;
4527
4528        // Sleep time for network errors
4529        private static final int NET_ERROR_SLEEP_SEC = 3;
4530
4531        // Sleep time for network route establishment
4532        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4533
4534        // Short sleep time for polling :(
4535        private static final int POLLING_SLEEP_SEC = 1;
4536
4537        private Context mContext;
4538        private ConnectivityService mCs;
4539        private TelephonyManager mTm;
4540        private Params mParams;
4541
4542        /**
4543         * Parameters for AsyncTask.execute
4544         */
4545        static class Params {
4546            private String mUrl;
4547            private long mTimeOutMs;
4548            private CallBack mCb;
4549
4550            Params(String url, long timeOutMs, CallBack cb) {
4551                mUrl = url;
4552                mTimeOutMs = timeOutMs;
4553                mCb = cb;
4554            }
4555
4556            @Override
4557            public String toString() {
4558                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4559            }
4560        }
4561
4562        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4563        // issued by name or ip address, for Google its by name so when we construct
4564        // this HostnameVerifier we'll pass the original Uri and use it to verify
4565        // the host. If the host name in the original uril fails we'll test the
4566        // hostname parameter just incase things change.
4567        static class CheckMpHostnameVerifier implements HostnameVerifier {
4568            Uri mOrgUri;
4569
4570            CheckMpHostnameVerifier(Uri orgUri) {
4571                mOrgUri = orgUri;
4572            }
4573
4574            @Override
4575            public boolean verify(String hostname, SSLSession session) {
4576                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4577                String orgUriHost = mOrgUri.getHost();
4578                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4579                if (DBG) {
4580                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4581                        + " orgUriHost=" + orgUriHost);
4582                }
4583                return retVal;
4584            }
4585        }
4586
4587        /**
4588         * The call back object passed in Params. onComplete will be called
4589         * on the main thread.
4590         */
4591        abstract static class CallBack {
4592            // Called on the main thread.
4593            abstract void onComplete(Integer result);
4594        }
4595
4596        public CheckMp(Context context, ConnectivityService cs) {
4597            if (Build.IS_DEBUGGABLE) {
4598                mTestingFailures =
4599                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4600            } else {
4601                mTestingFailures = false;
4602            }
4603
4604            mContext = context;
4605            mCs = cs;
4606
4607            // Setup access to TelephonyService we'll be using.
4608            mTm = (TelephonyManager) mContext.getSystemService(
4609                    Context.TELEPHONY_SERVICE);
4610        }
4611
4612        /**
4613         * Get the default url to use for the test.
4614         */
4615        public String getDefaultUrl() {
4616            // See http://go/clientsdns for usage approval
4617            String server = Settings.Global.getString(mContext.getContentResolver(),
4618                    Settings.Global.CAPTIVE_PORTAL_SERVER);
4619            if (server == null) {
4620                server = "clients3.google.com";
4621            }
4622            return "http://" + server + "/generate_204";
4623        }
4624
4625        /**
4626         * Detect if its possible to connect to the http url. DNS based detection techniques
4627         * do not work at all hotspots. The best way to check is to perform a request to
4628         * a known address that fetches the data we expect.
4629         */
4630        private synchronized Integer isMobileOk(Params params) {
4631            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
4632            Uri orgUri = Uri.parse(params.mUrl);
4633            Random rand = new Random();
4634            mParams = params;
4635
4636            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4637                result = CMP_RESULT_CODE_NO_CONNECTION;
4638                log("isMobileOk: X not mobile capable result=" + result);
4639                return result;
4640            }
4641
4642            if (mCs.mIsStartingProvisioning.get()) {
4643                result = CMP_RESULT_CODE_IS_PROVISIONING;
4644                log("isMobileOk: X is provisioning result=" + result);
4645                return result;
4646            }
4647
4648            // See if we've already determined we've got a provisioning connection,
4649            // if so we don't need to do anything active.
4650            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4651                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4652            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4653            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4654
4655            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4656                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4657            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4658            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4659
4660            if (isDefaultProvisioning || isHipriProvisioning) {
4661                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4662                log("isMobileOk: X default || hipri is provisioning result=" + result);
4663                return result;
4664            }
4665
4666            try {
4667                // Continue trying to connect until time has run out
4668                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
4669
4670                if (!mCs.isMobileDataStateTrackerReady()) {
4671                    // Wait for MobileDataStateTracker to be ready.
4672                    if (DBG) log("isMobileOk: mdst is not ready");
4673                    while(SystemClock.elapsedRealtime() < endTime) {
4674                        if (mCs.isMobileDataStateTrackerReady()) {
4675                            // Enable fail fast as we'll do retries here and use a
4676                            // hipri connection so the default connection stays active.
4677                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4678                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4679                            break;
4680                        }
4681                        sleep(POLLING_SLEEP_SEC);
4682                    }
4683                }
4684
4685                log("isMobileOk: start hipri url=" + params.mUrl);
4686
4687                // First wait until we can start using hipri
4688                Binder binder = new Binder();
4689                while(SystemClock.elapsedRealtime() < endTime) {
4690                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4691                            Phone.FEATURE_ENABLE_HIPRI, binder);
4692                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4693                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4694                            log("isMobileOk: hipri started");
4695                            break;
4696                    }
4697                    if (VDBG) log("isMobileOk: hipri not started yet");
4698                    result = CMP_RESULT_CODE_NO_CONNECTION;
4699                    sleep(POLLING_SLEEP_SEC);
4700                }
4701
4702                // Continue trying to connect until time has run out
4703                while(SystemClock.elapsedRealtime() < endTime) {
4704                    try {
4705                        // Wait for hipri to connect.
4706                        // TODO: Don't poll and handle situation where hipri fails
4707                        // because default is retrying. See b/9569540
4708                        NetworkInfo.State state = mCs
4709                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4710                        if (state != NetworkInfo.State.CONNECTED) {
4711                            if (true/*VDBG*/) {
4712                                log("isMobileOk: not connected ni=" +
4713                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4714                            }
4715                            sleep(POLLING_SLEEP_SEC);
4716                            result = CMP_RESULT_CODE_NO_CONNECTION;
4717                            continue;
4718                        }
4719
4720                        // Hipri has started check if this is a provisioning url
4721                        MobileDataStateTracker mdst = (MobileDataStateTracker)
4722                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4723                        if (mdst.isProvisioningNetwork()) {
4724                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4725                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
4726                            return result;
4727                        } else {
4728                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4729                        }
4730
4731                        // Get of the addresses associated with the url host. We need to use the
4732                        // address otherwise HttpURLConnection object will use the name to get
4733                        // the addresses and will try every address but that will bypass the
4734                        // route to host we setup and the connection could succeed as the default
4735                        // interface might be connected to the internet via wifi or other interface.
4736                        InetAddress[] addresses;
4737                        try {
4738                            addresses = InetAddress.getAllByName(orgUri.getHost());
4739                        } catch (UnknownHostException e) {
4740                            result = CMP_RESULT_CODE_NO_DNS;
4741                            log("isMobileOk: X UnknownHostException result=" + result);
4742                            return result;
4743                        }
4744                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4745
4746                        // Get the type of addresses supported by this link
4747                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
4748                                ConnectivityManager.TYPE_MOBILE_HIPRI);
4749                        boolean linkHasIpv4 = lp.hasIPv4Address();
4750                        boolean linkHasIpv6 = lp.hasGlobalIPv6Address();
4751                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4752                                + " linkHasIpv6=" + linkHasIpv6);
4753
4754                        final ArrayList<InetAddress> validAddresses =
4755                                new ArrayList<InetAddress>(addresses.length);
4756
4757                        for (InetAddress addr : addresses) {
4758                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4759                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
4760                                validAddresses.add(addr);
4761                            }
4762                        }
4763
4764                        if (validAddresses.size() == 0) {
4765                            return CMP_RESULT_CODE_NO_CONNECTION;
4766                        }
4767
4768                        int addrTried = 0;
4769                        while (true) {
4770                            // Loop through at most MAX_LOOPS valid addresses or until
4771                            // we run out of time
4772                            if (addrTried++ >= MAX_LOOPS) {
4773                                log("isMobileOk: too many loops tried - giving up");
4774                                break;
4775                            }
4776                            if (SystemClock.elapsedRealtime() >= endTime) {
4777                                log("isMobileOk: spend too much time - giving up");
4778                                break;
4779                            }
4780
4781                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
4782                                    validAddresses.size()));
4783
4784                            // Make a route to host so we check the specific interface.
4785                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4786                                    hostAddr.getAddress(), null)) {
4787                                // Wait a short time to be sure the route is established ??
4788                                log("isMobileOk:"
4789                                        + " wait to establish route to hostAddr=" + hostAddr);
4790                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
4791                            } else {
4792                                log("isMobileOk:"
4793                                        + " could not establish route to hostAddr=" + hostAddr);
4794                                // Wait a short time before the next attempt
4795                                sleep(NET_ERROR_SLEEP_SEC);
4796                                continue;
4797                            }
4798
4799                            // Rewrite the url to have numeric address to use the specific route
4800                            // using http for half the attempts and https for the other half.
4801                            // Doing https first and http second as on a redirected walled garden
4802                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
4803                            // handshake timed out" which we declare as
4804                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4805                            // having http second we will be using logic used for some time.
4806                            URL newUrl;
4807                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4808                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
4809                                        orgUri.getPath());
4810                            log("isMobileOk: newUrl=" + newUrl);
4811
4812                            HttpURLConnection urlConn = null;
4813                            try {
4814                                // Open the connection set the request headers and get the response
4815                                urlConn = (HttpURLConnection)newUrl.openConnection(
4816                                        java.net.Proxy.NO_PROXY);
4817                                if (scheme.equals("https")) {
4818                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
4819                                            new CheckMpHostnameVerifier(orgUri));
4820                                }
4821                                urlConn.setInstanceFollowRedirects(false);
4822                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4823                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4824                                urlConn.setUseCaches(false);
4825                                urlConn.setAllowUserInteraction(false);
4826                                // Set the "Connection" to "Close" as by default "Keep-Alive"
4827                                // is used which is useless in this case.
4828                                urlConn.setRequestProperty("Connection", "close");
4829                                int responseCode = urlConn.getResponseCode();
4830
4831                                // For debug display the headers
4832                                Map<String, List<String>> headers = urlConn.getHeaderFields();
4833                                log("isMobileOk: headers=" + headers);
4834
4835                                // Close the connection
4836                                urlConn.disconnect();
4837                                urlConn = null;
4838
4839                                if (mTestingFailures) {
4840                                    // Pretend no connection, this tests using http and https
4841                                    result = CMP_RESULT_CODE_NO_CONNECTION;
4842                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
4843                                    continue;
4844                                }
4845
4846                                if (responseCode == 204) {
4847                                    // Return
4848                                    result = CMP_RESULT_CODE_CONNECTABLE;
4849                                    log("isMobileOk: X got expected responseCode=" + responseCode
4850                                            + " result=" + result);
4851                                    return result;
4852                                } else {
4853                                    // Retry to be sure this was redirected, we've gotten
4854                                    // occasions where a server returned 200 even though
4855                                    // the device didn't have a "warm" sim.
4856                                    log("isMobileOk: not expected responseCode=" + responseCode);
4857                                    // TODO - it would be nice in the single-address case to do
4858                                    // another DNS resolve here, but flushing the cache is a bit
4859                                    // heavy-handed.
4860                                    result = CMP_RESULT_CODE_REDIRECTED;
4861                                }
4862                            } catch (Exception e) {
4863                                log("isMobileOk: HttpURLConnection Exception" + e);
4864                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4865                                if (urlConn != null) {
4866                                    urlConn.disconnect();
4867                                    urlConn = null;
4868                                }
4869                                sleep(NET_ERROR_SLEEP_SEC);
4870                                continue;
4871                            }
4872                        }
4873                        log("isMobileOk: X loops|timed out result=" + result);
4874                        return result;
4875                    } catch (Exception e) {
4876                        log("isMobileOk: Exception e=" + e);
4877                        continue;
4878                    }
4879                }
4880                log("isMobileOk: timed out");
4881            } finally {
4882                log("isMobileOk: F stop hipri");
4883                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4884                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4885                        Phone.FEATURE_ENABLE_HIPRI);
4886
4887                // Wait for hipri to disconnect.
4888                long endTime = SystemClock.elapsedRealtime() + 5000;
4889
4890                while(SystemClock.elapsedRealtime() < endTime) {
4891                    NetworkInfo.State state = mCs
4892                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4893                    if (state != NetworkInfo.State.DISCONNECTED) {
4894                        if (VDBG) {
4895                            log("isMobileOk: connected ni=" +
4896                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4897                        }
4898                        sleep(POLLING_SLEEP_SEC);
4899                        continue;
4900                    }
4901                }
4902
4903                log("isMobileOk: X result=" + result);
4904            }
4905            return result;
4906        }
4907
4908        @Override
4909        protected Integer doInBackground(Params... params) {
4910            return isMobileOk(params[0]);
4911        }
4912
4913        @Override
4914        protected void onPostExecute(Integer result) {
4915            log("onPostExecute: result=" + result);
4916            if ((mParams != null) && (mParams.mCb != null)) {
4917                mParams.mCb.onComplete(result);
4918            }
4919        }
4920
4921        private String inetAddressesToString(InetAddress[] addresses) {
4922            StringBuffer sb = new StringBuffer();
4923            boolean firstTime = true;
4924            for(InetAddress addr : addresses) {
4925                if (firstTime) {
4926                    firstTime = false;
4927                } else {
4928                    sb.append(",");
4929                }
4930                sb.append(addr);
4931            }
4932            return sb.toString();
4933        }
4934
4935        private void printNetworkInfo() {
4936            boolean hasIccCard = mTm.hasIccCard();
4937            int simState = mTm.getSimState();
4938            log("hasIccCard=" + hasIccCard
4939                    + " simState=" + simState);
4940            NetworkInfo[] ni = mCs.getAllNetworkInfo();
4941            if (ni != null) {
4942                log("ni.length=" + ni.length);
4943                for (NetworkInfo netInfo: ni) {
4944                    log("netInfo=" + netInfo.toString());
4945                }
4946            } else {
4947                log("no network info ni=null");
4948            }
4949        }
4950
4951        /**
4952         * Sleep for a few seconds then return.
4953         * @param seconds
4954         */
4955        private static void sleep(int seconds) {
4956            long stopTime = System.nanoTime() + (seconds * 1000000000);
4957            long sleepTime;
4958            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
4959                try {
4960                    Thread.sleep(sleepTime / 1000000);
4961                } catch (InterruptedException ignored) {
4962                }
4963            }
4964        }
4965
4966        private static void log(String s) {
4967            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4968        }
4969    }
4970
4971    // TODO: Move to ConnectivityManager and make public?
4972    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4973            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
4974
4975    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4976        @Override
4977        public void onReceive(Context context, Intent intent) {
4978            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4979                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4980            }
4981        }
4982    };
4983
4984    private void handleMobileProvisioningAction(String url) {
4985        // Mark notification as not visible
4986        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4987
4988        // Check airplane mode
4989        boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(),
4990                Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
4991        // If provisioning network and not in airplane mode handle as a special case,
4992        // otherwise launch browser with the intent directly.
4993        if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) {
4994            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
4995            mIsProvisioningNetwork.set(false);
4996//            mIsStartingProvisioning.set(true);
4997//            MobileDataStateTracker mdst = (MobileDataStateTracker)
4998//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4999            // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here
5000//            mdst.setRadio(true);
5001//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
5002//            mdst.enableMobileProvisioning(url);
5003        } else {
5004            if (DBG) log("handleMobileProvisioningAction: not prov network");
5005            mIsProvisioningNetwork.set(false);
5006            // Check for  apps that can handle provisioning first
5007            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
5008            provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
5009                    + mTelephonyManager.getSimOperator());
5010            if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
5011                    != null) {
5012                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
5013                        Intent.FLAG_ACTIVITY_NEW_TASK);
5014                mContext.startActivity(provisioningIntent);
5015            } else {
5016                // If no apps exist, use standard URL ACTION_VIEW method
5017                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
5018                        Intent.CATEGORY_APP_BROWSER);
5019                newIntent.setData(Uri.parse(url));
5020                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
5021                        Intent.FLAG_ACTIVITY_NEW_TASK);
5022                try {
5023                    mContext.startActivity(newIntent);
5024                } catch (ActivityNotFoundException e) {
5025                    loge("handleMobileProvisioningAction: startActivity failed" + e);
5026                }
5027            }
5028        }
5029    }
5030
5031    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
5032    private volatile boolean mIsNotificationVisible = false;
5033
5034    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
5035            String url) {
5036        if (DBG) {
5037            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
5038                + " extraInfo=" + extraInfo + " url=" + url);
5039        }
5040
5041        Resources r = Resources.getSystem();
5042        NotificationManager notificationManager = (NotificationManager) mContext
5043            .getSystemService(Context.NOTIFICATION_SERVICE);
5044
5045        if (visible) {
5046            CharSequence title;
5047            CharSequence details;
5048            int icon;
5049            Intent intent;
5050            Notification notification = new Notification();
5051            switch (networkType) {
5052                case ConnectivityManager.TYPE_WIFI:
5053                    title = r.getString(R.string.wifi_available_sign_in, 0);
5054                    details = r.getString(R.string.network_available_sign_in_detailed,
5055                            extraInfo);
5056                    icon = R.drawable.stat_notify_wifi_in_range;
5057                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
5058                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
5059                            Intent.FLAG_ACTIVITY_NEW_TASK);
5060                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
5061                    break;
5062                case ConnectivityManager.TYPE_MOBILE:
5063                case ConnectivityManager.TYPE_MOBILE_HIPRI:
5064                    title = r.getString(R.string.network_available_sign_in, 0);
5065                    // TODO: Change this to pull from NetworkInfo once a printable
5066                    // name has been added to it
5067                    details = mTelephonyManager.getNetworkOperatorName();
5068                    icon = R.drawable.stat_notify_rssi_in_range;
5069                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
5070                    intent.putExtra("EXTRA_URL", url);
5071                    intent.setFlags(0);
5072                    notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
5073                    break;
5074                default:
5075                    title = r.getString(R.string.network_available_sign_in, 0);
5076                    details = r.getString(R.string.network_available_sign_in_detailed,
5077                            extraInfo);
5078                    icon = R.drawable.stat_notify_rssi_in_range;
5079                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
5080                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
5081                            Intent.FLAG_ACTIVITY_NEW_TASK);
5082                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
5083                    break;
5084            }
5085
5086            notification.when = 0;
5087            notification.icon = icon;
5088            notification.flags = Notification.FLAG_AUTO_CANCEL;
5089            notification.tickerText = title;
5090            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
5091
5092            try {
5093                notificationManager.notify(NOTIFICATION_ID, networkType, notification);
5094            } catch (NullPointerException npe) {
5095                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
5096                npe.printStackTrace();
5097            }
5098        } else {
5099            try {
5100                notificationManager.cancel(NOTIFICATION_ID, networkType);
5101            } catch (NullPointerException npe) {
5102                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
5103                npe.printStackTrace();
5104            }
5105        }
5106        mIsNotificationVisible = visible;
5107    }
5108
5109    /** Location to an updatable file listing carrier provisioning urls.
5110     *  An example:
5111     *
5112     * <?xml version="1.0" encoding="utf-8"?>
5113     *  <provisioningUrls>
5114     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
5115     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
5116     *  </provisioningUrls>
5117     */
5118    private static final String PROVISIONING_URL_PATH =
5119            "/data/misc/radio/provisioning_urls.xml";
5120    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
5121
5122    /** XML tag for root element. */
5123    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
5124    /** XML tag for individual url */
5125    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
5126    /** XML tag for redirected url */
5127    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
5128    /** XML attribute for mcc */
5129    private static final String ATTR_MCC = "mcc";
5130    /** XML attribute for mnc */
5131    private static final String ATTR_MNC = "mnc";
5132
5133    private static final int REDIRECTED_PROVISIONING = 1;
5134    private static final int PROVISIONING = 2;
5135
5136    private String getProvisioningUrlBaseFromFile(int type) {
5137        FileReader fileReader = null;
5138        XmlPullParser parser = null;
5139        Configuration config = mContext.getResources().getConfiguration();
5140        String tagType;
5141
5142        switch (type) {
5143            case PROVISIONING:
5144                tagType = TAG_PROVISIONING_URL;
5145                break;
5146            case REDIRECTED_PROVISIONING:
5147                tagType = TAG_REDIRECTED_URL;
5148                break;
5149            default:
5150                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
5151                        type);
5152        }
5153
5154        try {
5155            fileReader = new FileReader(mProvisioningUrlFile);
5156            parser = Xml.newPullParser();
5157            parser.setInput(fileReader);
5158            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
5159
5160            while (true) {
5161                XmlUtils.nextElement(parser);
5162
5163                String element = parser.getName();
5164                if (element == null) break;
5165
5166                if (element.equals(tagType)) {
5167                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
5168                    try {
5169                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
5170                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
5171                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
5172                                parser.next();
5173                                if (parser.getEventType() == XmlPullParser.TEXT) {
5174                                    return parser.getText();
5175                                }
5176                            }
5177                        }
5178                    } catch (NumberFormatException e) {
5179                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
5180                    }
5181                }
5182            }
5183            return null;
5184        } catch (FileNotFoundException e) {
5185            loge("Carrier Provisioning Urls file not found");
5186        } catch (XmlPullParserException e) {
5187            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
5188        } catch (IOException e) {
5189            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
5190        } finally {
5191            if (fileReader != null) {
5192                try {
5193                    fileReader.close();
5194                } catch (IOException e) {}
5195            }
5196        }
5197        return null;
5198    }
5199
5200    @Override
5201    public String getMobileRedirectedProvisioningUrl() {
5202        enforceConnectivityInternalPermission();
5203        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
5204        if (TextUtils.isEmpty(url)) {
5205            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
5206        }
5207        return url;
5208    }
5209
5210    @Override
5211    public String getMobileProvisioningUrl() {
5212        enforceConnectivityInternalPermission();
5213        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
5214        if (TextUtils.isEmpty(url)) {
5215            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
5216            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
5217        } else {
5218            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
5219        }
5220        // populate the iccid, imei and phone number in the provisioning url.
5221        if (!TextUtils.isEmpty(url)) {
5222            String phoneNumber = mTelephonyManager.getLine1Number();
5223            if (TextUtils.isEmpty(phoneNumber)) {
5224                phoneNumber = "0000000000";
5225            }
5226            url = String.format(url,
5227                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
5228                    mTelephonyManager.getDeviceId() /* IMEI */,
5229                    phoneNumber /* Phone numer */);
5230        }
5231
5232        return url;
5233    }
5234
5235    @Override
5236    public void setProvisioningNotificationVisible(boolean visible, int networkType,
5237            String extraInfo, String url) {
5238        enforceConnectivityInternalPermission();
5239        setProvNotificationVisible(visible, networkType, extraInfo, url);
5240    }
5241
5242    @Override
5243    public void setAirplaneMode(boolean enable) {
5244        enforceConnectivityInternalPermission();
5245        final long ident = Binder.clearCallingIdentity();
5246        try {
5247            final ContentResolver cr = mContext.getContentResolver();
5248            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
5249            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5250            intent.putExtra("state", enable);
5251            mContext.sendBroadcast(intent);
5252        } finally {
5253            Binder.restoreCallingIdentity(ident);
5254        }
5255    }
5256
5257    private void onUserStart(int userId) {
5258        synchronized(mVpns) {
5259            Vpn userVpn = mVpns.get(userId);
5260            if (userVpn != null) {
5261                loge("Starting user already has a VPN");
5262                return;
5263            }
5264            userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
5265            mVpns.put(userId, userVpn);
5266            userVpn.startMonitoring(mContext, mTrackerHandler);
5267        }
5268    }
5269
5270    private void onUserStop(int userId) {
5271        synchronized(mVpns) {
5272            Vpn userVpn = mVpns.get(userId);
5273            if (userVpn == null) {
5274                loge("Stopping user has no VPN");
5275                return;
5276            }
5277            mVpns.delete(userId);
5278        }
5279    }
5280
5281    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5282        @Override
5283        public void onReceive(Context context, Intent intent) {
5284            final String action = intent.getAction();
5285            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
5286            if (userId == UserHandle.USER_NULL) return;
5287
5288            if (Intent.ACTION_USER_STARTING.equals(action)) {
5289                onUserStart(userId);
5290            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
5291                onUserStop(userId);
5292            }
5293        }
5294    };
5295
5296    @Override
5297    public LinkQualityInfo getLinkQualityInfo(int networkType) {
5298        enforceAccessPermission();
5299        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
5300            return mNetTrackers[networkType].getLinkQualityInfo();
5301        } else {
5302            return null;
5303        }
5304    }
5305
5306    @Override
5307    public LinkQualityInfo getActiveLinkQualityInfo() {
5308        enforceAccessPermission();
5309        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
5310                mNetTrackers[mActiveDefaultNetwork] != null) {
5311            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
5312        } else {
5313            return null;
5314        }
5315    }
5316
5317    @Override
5318    public LinkQualityInfo[] getAllLinkQualityInfo() {
5319        enforceAccessPermission();
5320        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
5321        for (NetworkStateTracker tracker : mNetTrackers) {
5322            if (tracker != null) {
5323                LinkQualityInfo li = tracker.getLinkQualityInfo();
5324                if (li != null) {
5325                    result.add(li);
5326                }
5327            }
5328        }
5329
5330        return result.toArray(new LinkQualityInfo[result.size()]);
5331    }
5332
5333    /* Infrastructure for network sampling */
5334
5335    private void handleNetworkSamplingTimeout() {
5336
5337        log("Sampling interval elapsed, updating statistics ..");
5338
5339        // initialize list of interfaces ..
5340        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
5341                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
5342        for (NetworkStateTracker tracker : mNetTrackers) {
5343            if (tracker != null) {
5344                String ifaceName = tracker.getNetworkInterfaceName();
5345                if (ifaceName != null) {
5346                    mapIfaceToSample.put(ifaceName, null);
5347                }
5348            }
5349        }
5350
5351        // Read samples for all interfaces
5352        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
5353
5354        // process samples for all networks
5355        for (NetworkStateTracker tracker : mNetTrackers) {
5356            if (tracker != null) {
5357                String ifaceName = tracker.getNetworkInterfaceName();
5358                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
5359                if (ss != null) {
5360                    // end the previous sampling cycle
5361                    tracker.stopSampling(ss);
5362                    // start a new sampling cycle ..
5363                    tracker.startSampling(ss);
5364                }
5365            }
5366        }
5367
5368        log("Done.");
5369
5370        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
5371                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
5372                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
5373
5374        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
5375
5376        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
5377    }
5378
5379    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
5380        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
5381        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
5382    }
5383
5384    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
5385            new HashMap<Messenger, NetworkFactoryInfo>();
5386    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
5387            new HashMap<NetworkRequest, NetworkRequestInfo>();
5388
5389    private static class NetworkFactoryInfo {
5390        public final String name;
5391        public final Messenger messenger;
5392        public final AsyncChannel asyncChannel;
5393
5394        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
5395            this.name = name;
5396            this.messenger = messenger;
5397            this.asyncChannel = asyncChannel;
5398        }
5399    }
5400
5401    private class NetworkRequestInfo implements IBinder.DeathRecipient {
5402        static final boolean REQUEST = true;
5403        static final boolean LISTEN = false;
5404
5405        final NetworkRequest request;
5406        IBinder mBinder;
5407        final int mPid;
5408        final int mUid;
5409        final Messenger messenger;
5410        final boolean isRequest;
5411
5412        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
5413            super();
5414            messenger = m;
5415            request = r;
5416            mBinder = binder;
5417            mPid = getCallingPid();
5418            mUid = getCallingUid();
5419            this.isRequest = isRequest;
5420
5421            try {
5422                mBinder.linkToDeath(this, 0);
5423            } catch (RemoteException e) {
5424                binderDied();
5425            }
5426        }
5427
5428        void unlinkDeathRecipient() {
5429            mBinder.unlinkToDeath(this, 0);
5430        }
5431
5432        public void binderDied() {
5433            log("ConnectivityService NetworkRequestInfo binderDied(" +
5434                    request + ", " + mBinder + ")");
5435            releaseNetworkRequest(request);
5436        }
5437
5438        public String toString() {
5439            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
5440                    mPid + " for " + request;
5441        }
5442    }
5443
5444    @Override
5445    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
5446            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
5447        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
5448                == false) {
5449            enforceConnectivityInternalPermission();
5450        } else {
5451            enforceChangePermission();
5452        }
5453
5454        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
5455            throw new IllegalArgumentException("Bad timeout specified");
5456        }
5457        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5458                networkCapabilities), legacyType, nextNetworkRequestId());
5459        if (DBG) log("requestNetwork for " + networkRequest);
5460        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5461                NetworkRequestInfo.REQUEST);
5462
5463        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5464        if (timeoutMs > 0) {
5465            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5466                    nri), timeoutMs);
5467        }
5468        return networkRequest;
5469    }
5470
5471    @Override
5472    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5473            PendingIntent operation) {
5474        // TODO
5475        return null;
5476    }
5477
5478    @Override
5479    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5480            Messenger messenger, IBinder binder) {
5481        enforceAccessPermission();
5482
5483        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5484                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
5485        if (DBG) log("listenForNetwork for " + networkRequest);
5486        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5487                NetworkRequestInfo.LISTEN);
5488
5489        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5490        return networkRequest;
5491    }
5492
5493    @Override
5494    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5495            PendingIntent operation) {
5496    }
5497
5498    @Override
5499    public void releaseNetworkRequest(NetworkRequest networkRequest) {
5500        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
5501                0, networkRequest));
5502    }
5503
5504    @Override
5505    public void registerNetworkFactory(Messenger messenger, String name) {
5506        enforceConnectivityInternalPermission();
5507        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
5508        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
5509    }
5510
5511    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
5512        if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name);
5513        mNetworkFactoryInfos.put(nfi.messenger, nfi);
5514        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5515    }
5516
5517    @Override
5518    public void unregisterNetworkFactory(Messenger messenger) {
5519        enforceConnectivityInternalPermission();
5520        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5521    }
5522
5523    private void handleUnregisterNetworkFactory(Messenger messenger) {
5524        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5525        if (nfi == null) {
5526            if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory");
5527            return;
5528        }
5529        if (VDBG) log("unregisterNetworkFactory for " + nfi.name);
5530    }
5531
5532    /**
5533     * NetworkAgentInfo supporting a request by requestId.
5534     * These have already been vetted (their Capabilities satisfy the request)
5535     * and the are the highest scored network available.
5536     * the are keyed off the Requests requestId.
5537     */
5538    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
5539            new SparseArray<NetworkAgentInfo>();
5540
5541    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
5542            new SparseArray<NetworkAgentInfo>();
5543
5544    // NetworkAgentInfo keyed off its connecting messenger
5545    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
5546    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
5547            new HashMap<Messenger, NetworkAgentInfo>();
5548
5549    private final NetworkRequest mDefaultRequest;
5550
5551    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5552            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5553            int currentScore) {
5554        enforceConnectivityInternalPermission();
5555
5556        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(),
5557            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
5558            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler);
5559        if (VDBG) log("registerNetworkAgent " + nai);
5560        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
5561    }
5562
5563    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
5564        if (VDBG) log("Got NetworkAgent Messenger");
5565        mNetworkAgentInfos.put(na.messenger, na);
5566        mNetworkForNetId.put(na.network.netId, na);
5567        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
5568        NetworkInfo networkInfo = na.networkInfo;
5569        na.networkInfo = null;
5570        updateNetworkInfo(na, networkInfo);
5571    }
5572
5573    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
5574        LinkProperties newLp = networkAgent.linkProperties;
5575        int netId = networkAgent.network.netId;
5576
5577        updateInterfaces(newLp, oldLp, netId);
5578        updateMtu(newLp, oldLp);
5579        // TODO - figure out what to do for clat
5580//        for (LinkProperties lp : newLp.getStackedLinks()) {
5581//            updateMtu(lp, null);
5582//        }
5583        updateRoutes(newLp, oldLp, netId);
5584        updateDnses(newLp, oldLp, netId);
5585        updateClat(newLp, oldLp, networkAgent);
5586    }
5587
5588    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
5589        // Update 464xlat state.
5590        if (mClat.requiresClat(na)) {
5591
5592            // If the connection was previously using clat, but is not using it now, stop the clat
5593            // daemon. Normally, this happens automatically when the connection disconnects, but if
5594            // the disconnect is not reported, or if the connection's LinkProperties changed for
5595            // some other reason (e.g., handoff changes the IP addresses on the link), it would
5596            // still be running. If it's not running, then stopping it is a no-op.
5597            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
5598                mClat.stopClat();
5599            }
5600            // If the link requires clat to be running, then start the daemon now.
5601            if (na.networkInfo.isConnected()) {
5602                mClat.startClat(na);
5603            } else {
5604                mClat.stopClat();
5605            }
5606        }
5607    }
5608
5609    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
5610        CompareResult<String> interfaceDiff = new CompareResult<String>();
5611        if (oldLp != null) {
5612            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
5613        } else if (newLp != null) {
5614            interfaceDiff.added = newLp.getAllInterfaceNames();
5615        }
5616        for (String iface : interfaceDiff.added) {
5617            try {
5618                mNetd.addInterfaceToNetwork(iface, netId);
5619            } catch (Exception e) {
5620                loge("Exception adding interface: " + e);
5621            }
5622        }
5623        for (String iface : interfaceDiff.removed) {
5624            try {
5625                mNetd.removeInterfaceFromNetwork(iface, netId);
5626            } catch (Exception e) {
5627                loge("Exception removing interface: " + e);
5628            }
5629        }
5630    }
5631
5632    private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
5633        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
5634        if (oldLp != null) {
5635            routeDiff = oldLp.compareAllRoutes(newLp);
5636        } else if (newLp != null) {
5637            routeDiff.added = newLp.getAllRoutes();
5638        }
5639
5640        // add routes before removing old in case it helps with continuous connectivity
5641
5642        // do this twice, adding non-nexthop routes first, then routes they are dependent on
5643        for (RouteInfo route : routeDiff.added) {
5644            if (route.hasGateway()) continue;
5645            try {
5646                mNetd.addRoute(netId, route);
5647            } catch (Exception e) {
5648                loge("Exception in addRoute for non-gateway: " + e);
5649            }
5650        }
5651        for (RouteInfo route : routeDiff.added) {
5652            if (route.hasGateway() == false) continue;
5653            try {
5654                mNetd.addRoute(netId, route);
5655            } catch (Exception e) {
5656                loge("Exception in addRoute for gateway: " + e);
5657            }
5658        }
5659
5660        for (RouteInfo route : routeDiff.removed) {
5661            try {
5662                mNetd.removeRoute(netId, route);
5663            } catch (Exception e) {
5664                loge("Exception in removeRoute: " + e);
5665            }
5666        }
5667    }
5668    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5669        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
5670            Collection<InetAddress> dnses = newLp.getDnsServers();
5671            if (dnses.size() == 0 && mDefaultDns != null) {
5672                dnses = new ArrayList();
5673                dnses.add(mDefaultDns);
5674                if (DBG) {
5675                    loge("no dns provided for netId " + netId + ", so using defaults");
5676                }
5677            }
5678            try {
5679                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
5680                    newLp.getDomains());
5681            } catch (Exception e) {
5682                loge("Exception in setDnsServersForNetwork: " + e);
5683            }
5684            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
5685            if (defaultNai != null && defaultNai.network.netId == netId) {
5686                setDefaultDnsSystemProperties(dnses);
5687            }
5688        }
5689    }
5690
5691    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
5692        int last = 0;
5693        for (InetAddress dns : dnses) {
5694            ++last;
5695            String key = "net.dns" + last;
5696            String value = dns.getHostAddress();
5697            SystemProperties.set(key, value);
5698        }
5699        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
5700            String key = "net.dns" + i;
5701            SystemProperties.set(key, "");
5702        }
5703        mNumDnsEntries = last;
5704    }
5705
5706
5707    private void updateCapabilities(NetworkAgentInfo networkAgent,
5708            NetworkCapabilities networkCapabilities) {
5709        // TODO - what else here?  Verify still satisfies everybody?
5710        // Check if satisfies somebody new?  call callbacks?
5711        networkAgent.networkCapabilities = networkCapabilities;
5712    }
5713
5714    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5715        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5716        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
5717            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5718                    networkRequest);
5719        }
5720    }
5721
5722    private void callCallbackForRequest(NetworkRequestInfo nri,
5723            NetworkAgentInfo networkAgent, int notificationType) {
5724        if (nri.messenger == null) return;  // Default request has no msgr
5725        Object o;
5726        int a1 = 0;
5727        int a2 = 0;
5728        switch (notificationType) {
5729            case ConnectivityManager.CALLBACK_LOSING:
5730                a1 = 30 * 1000; // TODO - read this from NetworkMonitor
5731                // fall through
5732            case ConnectivityManager.CALLBACK_PRECHECK:
5733            case ConnectivityManager.CALLBACK_AVAILABLE:
5734            case ConnectivityManager.CALLBACK_LOST:
5735            case ConnectivityManager.CALLBACK_CAP_CHANGED:
5736            case ConnectivityManager.CALLBACK_IP_CHANGED: {
5737                o = new NetworkRequest(nri.request);
5738                a2 = networkAgent.network.netId;
5739                break;
5740            }
5741            case ConnectivityManager.CALLBACK_UNAVAIL:
5742            case ConnectivityManager.CALLBACK_RELEASED: {
5743                o = new NetworkRequest(nri.request);
5744                break;
5745            }
5746            default: {
5747                loge("Unknown notificationType " + notificationType);
5748                return;
5749            }
5750        }
5751        Message msg = Message.obtain();
5752        msg.arg1 = a1;
5753        msg.arg2 = a2;
5754        msg.obj = o;
5755        msg.what = notificationType;
5756        try {
5757            if (VDBG) log("sending notification " + notificationType + " for " + nri.request);
5758            nri.messenger.send(msg);
5759        } catch (RemoteException e) {
5760            // may occur naturally in the race of binder death.
5761            loge("RemoteException caught trying to send a callback msg for " + nri.request);
5762        }
5763    }
5764
5765    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5766        if (oldNetwork == null) {
5767            loge("Unknown NetworkAgentInfo in handleLingerComplete");
5768            return;
5769        }
5770        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
5771        if (DBG) {
5772            if (oldNetwork.networkRequests.size() != 0) {
5773                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
5774            }
5775        }
5776        oldNetwork.asyncChannel.disconnect();
5777    }
5778
5779    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
5780        if (newNetwork == null) {
5781            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
5782            return;
5783        }
5784        boolean keep = false;
5785        boolean isNewDefault = false;
5786        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
5787        // check if any NetworkRequest wants this NetworkAgent
5788        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
5789        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
5790        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5791            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
5792            if (newNetwork == currentNetwork) {
5793                if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" +
5794                              " request " + nri.request.requestId + ". No change.");
5795                keep = true;
5796                continue;
5797            }
5798
5799            // check if it satisfies the NetworkCapabilities
5800            if (VDBG) log("  checking if request is satisfied: " + nri.request);
5801            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
5802                    newNetwork.networkCapabilities)) {
5803                // next check if it's better than any current network we're using for
5804                // this request
5805                if (VDBG) {
5806                    log("currentScore = " +
5807                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
5808                            ", newScore = " + newNetwork.currentScore);
5809                }
5810                if (currentNetwork == null ||
5811                        currentNetwork.currentScore < newNetwork.currentScore) {
5812                    if (currentNetwork != null) {
5813                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
5814                        currentNetwork.networkRequests.remove(nri.request.requestId);
5815                        currentNetwork.networkLingered.add(nri.request);
5816                        affectedNetworks.add(currentNetwork);
5817                    } else {
5818                        if (VDBG) log("   accepting network in place of null");
5819                    }
5820                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
5821                    newNetwork.addRequest(nri.request);
5822                    int legacyType = nri.request.legacyType;
5823                    if (legacyType != TYPE_NONE) {
5824                        mLegacyTypeTracker.add(legacyType, newNetwork);
5825                    }
5826                    keep = true;
5827                    // TODO - this could get expensive if we have alot of requests for this
5828                    // network.  Think about if there is a way to reduce this.  Push
5829                    // netid->request mapping to each factory?
5830                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
5831                    if (mDefaultRequest.requestId == nri.request.requestId) {
5832                        isNewDefault = true;
5833                        updateActiveDefaultNetwork(newNetwork);
5834                        if (newNetwork.linkProperties != null) {
5835                            setDefaultDnsSystemProperties(
5836                                    newNetwork.linkProperties.getDnsServers());
5837                        } else {
5838                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
5839                        }
5840                        mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5841                    }
5842                }
5843            }
5844        }
5845        for (NetworkAgentInfo nai : affectedNetworks) {
5846            boolean teardown = true;
5847            for (int i = 0; i < nai.networkRequests.size(); i++) {
5848                NetworkRequest nr = nai.networkRequests.valueAt(i);
5849                try {
5850                if (mNetworkRequests.get(nr).isRequest) {
5851                    teardown = false;
5852                }
5853                } catch (Exception e) {
5854                    loge("Request " + nr + " not found in mNetworkRequests.");
5855                    loge("  it came from request list  of " + nai.name());
5856                }
5857            }
5858            if (teardown) {
5859                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
5860                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
5861            } else {
5862                // not going to linger, so kill the list of linger networks..  only
5863                // notify them of linger if it happens as the result of gaining another,
5864                // but if they transition and old network stays up, don't tell them of linger
5865                // or very delayed loss
5866                nai.networkLingered.clear();
5867                if (VDBG) log("Lingered for " + nai.name() + " cleared");
5868            }
5869        }
5870        if (keep) {
5871            if (isNewDefault) {
5872                if (VDBG) log("Switching to new default network: " + newNetwork);
5873                setupDataActivityTracking(newNetwork);
5874                try {
5875                    mNetd.setDefaultNetId(newNetwork.network.netId);
5876                } catch (Exception e) {
5877                    loge("Exception setting default network :" + e);
5878                }
5879                if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) {
5880                    handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
5881                }
5882                synchronized (ConnectivityService.this) {
5883                    // have a new default network, release the transition wakelock in
5884                    // a second if it's held.  The second pause is to allow apps
5885                    // to reconnect over the new network
5886                    if (mNetTransitionWakeLock.isHeld()) {
5887                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
5888                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
5889                                mNetTransitionWakeLockSerialNumber, 0),
5890                                1000);
5891                    }
5892                }
5893
5894                // this will cause us to come up initially as unconnected and switching
5895                // to connected after our normal pause unless somebody reports us as
5896                // really disconnected
5897                mDefaultInetConditionPublished = 0;
5898                mDefaultConnectionSequence++;
5899                mInetConditionChangeInFlight = false;
5900                // TODO - read the tcp buffer size config string from somewhere
5901                // updateNetworkSettings();
5902            }
5903            // notify battery stats service about this network
5904            try {
5905                BatteryStatsService.getService().noteNetworkInterfaceType(
5906                        newNetwork.linkProperties.getInterfaceName(),
5907                        newNetwork.networkInfo.getType());
5908            } catch (RemoteException e) { }
5909            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
5910        } else {
5911            if (DBG && newNetwork.networkRequests.size() != 0) {
5912                loge("tearing down network with live requests:");
5913                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
5914                    loge("  " + newNetwork.networkRequests.valueAt(i));
5915                }
5916            }
5917            if (VDBG) log("Validated network turns out to be unwanted.  Tear it down.");
5918            newNetwork.asyncChannel.disconnect();
5919        }
5920    }
5921
5922
5923    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5924        NetworkInfo.State state = newInfo.getState();
5925        NetworkInfo oldInfo = networkAgent.networkInfo;
5926        networkAgent.networkInfo = newInfo;
5927
5928        if (oldInfo != null && oldInfo.getState() == state) {
5929            if (VDBG) log("ignoring duplicate network state non-change");
5930            return;
5931        }
5932        if (DBG) {
5933            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5934                    (oldInfo == null ? "null" : oldInfo.getState()) +
5935                    " to " + state);
5936        }
5937
5938        if (state == NetworkInfo.State.CONNECTED) {
5939            try {
5940                // This is likely caused by the fact that this network already
5941                // exists. An example is when a network goes from CONNECTED to
5942                // CONNECTING and back (like wifi on DHCP renew).
5943                // TODO: keep track of which networks we've created, or ask netd
5944                // to tell us whether we've already created this network or not.
5945                mNetd.createNetwork(networkAgent.network.netId);
5946            } catch (Exception e) {
5947                loge("Error creating network " + networkAgent.network.netId + ": "
5948                        + e.getMessage());
5949                return;
5950            }
5951
5952            updateLinkProperties(networkAgent, null);
5953            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
5954            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
5955        } else if (state == NetworkInfo.State.DISCONNECTED ||
5956                state == NetworkInfo.State.SUSPENDED) {
5957            networkAgent.asyncChannel.disconnect();
5958        }
5959    }
5960
5961    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
5962        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
5963
5964        nai.currentScore = score;
5965
5966        // TODO - This will not do the right thing if this network is lowering
5967        // its score and has requests that can be served by other
5968        // currently-active networks, or if the network is increasing its
5969        // score and other networks have requests that can be better served
5970        // by this network.
5971        //
5972        // Really we want to see if any of our requests migrate to other
5973        // active/lingered networks and if any other requests migrate to us (depending
5974        // on increasing/decreasing currentScore.  That's a bit of work and probably our
5975        // score checking/network allocation code needs to be modularized so we can understand
5976        // (see handleConnectionValided for an example).
5977        //
5978        // As a first order approx, lets just advertise the new score to factories.  If
5979        // somebody can beat it they will nominate a network and our normal net replacement
5980        // code will fire.
5981        for (int i = 0; i < nai.networkRequests.size(); i++) {
5982            NetworkRequest nr = nai.networkRequests.valueAt(i);
5983            sendUpdatedScoreToFactories(nr, score);
5984        }
5985    }
5986
5987    // notify only this one new request of the current state
5988    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5989        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5990        // TODO - read state from monitor to decide what to send.
5991//        if (nai.networkMonitor.isLingering()) {
5992//            notifyType = NetworkCallbacks.LOSING;
5993//        } else if (nai.networkMonitor.isEvaluating()) {
5994//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5995//        }
5996        callCallbackForRequest(nri, nai, notifyType);
5997    }
5998
5999    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
6000        if (connected) {
6001            NetworkInfo info = new NetworkInfo(nai.networkInfo);
6002            info.setType(type);
6003            sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
6004        } else {
6005            NetworkInfo info = new NetworkInfo(nai.networkInfo);
6006            info.setType(type);
6007            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6008            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6009            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6010            if (info.isFailover()) {
6011                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6012                nai.networkInfo.setFailover(false);
6013            }
6014            if (info.getReason() != null) {
6015                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6016            }
6017            if (info.getExtraInfo() != null) {
6018                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6019            }
6020            NetworkAgentInfo newDefaultAgent = null;
6021            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
6022                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
6023                if (newDefaultAgent != null) {
6024                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6025                            newDefaultAgent.networkInfo);
6026                } else {
6027                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6028                }
6029            }
6030            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6031                    mDefaultInetConditionPublished);
6032            final Intent immediateIntent = new Intent(intent);
6033            immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
6034            sendStickyBroadcast(immediateIntent);
6035            sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
6036            if (newDefaultAgent != null) {
6037                sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
6038                getConnectivityChangeDelay());
6039            }
6040        }
6041    }
6042
6043    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6044        if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name());
6045        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
6046            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
6047            NetworkRequestInfo nri = mNetworkRequests.get(nr);
6048            if (VDBG) log(" sending notification for " + nr);
6049            callCallbackForRequest(nri, networkAgent, notifyType);
6050        }
6051    }
6052
6053    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
6054        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6055        return (nai != null) ?
6056                new LinkProperties(nai.linkProperties) :
6057                new LinkProperties();
6058    }
6059
6060    private NetworkInfo getNetworkInfoForType(int networkType) {
6061        if (!mLegacyTypeTracker.isTypeSupported(networkType))
6062            return null;
6063
6064        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6065        if (nai != null) {
6066            NetworkInfo result = new NetworkInfo(nai.networkInfo);
6067            result.setType(networkType);
6068            return result;
6069        } else {
6070           return new NetworkInfo(networkType, 0, "Unknown", "");
6071        }
6072    }
6073
6074    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
6075        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6076        return (nai != null) ?
6077                new NetworkCapabilities(nai.networkCapabilities) :
6078                new NetworkCapabilities();
6079    }
6080}
6081