Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 291af5c5 authored by Lorenzo Colitti's avatar Lorenzo Colitti Committed by Android (Google) Code Review
Browse files

Merge changes from topic 'avoidbadwifi' into nyc-dr1-dev

* changes:
  Ignore loss of IPv6 provisioning when not avoiding bad Wi-Fi.
  Slightly simplify IpManager#compareProvisioning.
  Conditionally accept loss of on-link IPv6 DNS servers
  Refactor "avoid bad wifi" logic into a utility class
parents 19404c6f f11ee9f5
Loading
Loading
Loading
Loading
+25 −64
Original line number Diff line number Diff line
@@ -77,6 +77,7 @@ import android.net.Uri;
import android.net.metrics.DefaultNetworkEvent;
import android.net.metrics.IpConnectivityLog;
import android.net.metrics.NetworkEvent;
import android.net.util.AvoidBadWifiTracker;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
@@ -397,11 +398,6 @@ public class ConnectivityService extends IConnectivityManager.Stub
    private static final int EVENT_REQUEST_LINKPROPERTIES  = 32;
    private static final int EVENT_REQUEST_NETCAPABILITIES = 33;

    /**
     * Used internally to (re)configure avoid bad wifi setting.
     */
    private static final int EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI = 34;

    /** Handler thread used for both of the handlers below. */
    @VisibleForTesting
    protected final HandlerThread mHandlerThread;
@@ -495,6 +491,9 @@ public class ConnectivityService extends IConnectivityManager.Stub

    private final IpConnectivityLog mMetricsLog;

    @VisibleForTesting
    final AvoidBadWifiTracker mAvoidBadWifiTracker;

    /**
     * Implements support for the legacy "one network per network type" model.
     *
@@ -857,14 +856,8 @@ public class ConnectivityService extends IConnectivityManager.Stub
                LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
        mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);

        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
        mContext.registerReceiverAsUser(new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
            }
        }, UserHandle.ALL, intentFilter, null, null);
        updateAvoidBadWifi();
        mAvoidBadWifiTracker = createAvoidBadWifiTracker(
                mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
    }

    private NetworkRequest createInternetRequestForTransport(int transportType) {
@@ -915,12 +908,6 @@ public class ConnectivityService extends IConnectivityManager.Stub
        mSettingsObserver.observe(
                Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
                EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);

        // Watch for whether to automatically switch away from wifi networks that lose Internet
        // access.
        mSettingsObserver.observe(
                Settings.Global.getUriFor(Settings.Global.NETWORK_AVOID_BAD_WIFI),
                EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
    }

    private synchronized int nextNetworkRequestId() {
@@ -2755,36 +2742,23 @@ public class ConnectivityService extends IConnectivityManager.Stub
                PROMPT_UNVALIDATED_DELAY_MS);
    }

    private boolean mAvoidBadWifi = true;

    public boolean avoidBadWifi() {
        return mAvoidBadWifi;
        return mAvoidBadWifiTracker.currentValue();
    }

    @VisibleForTesting
    /** Whether the device or carrier configuration disables avoiding bad wifi by default. */
    public boolean configRestrictsAvoidBadWifi() {
        return mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi) == 0;
    private void rematchForAvoidBadWifiUpdate() {
        rematchAllNetworksAndRequests(null, 0);
        for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
            if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                sendUpdatedScoreToFactories(nai);
            }

    /** Whether we should display a notification when wifi becomes unvalidated. */
    public boolean shouldNotifyWifiUnvalidated() {
        return configRestrictsAvoidBadWifi() &&
                Settings.Global.getString(mContext.getContentResolver(),
                        Settings.Global.NETWORK_AVOID_BAD_WIFI) == null;
        }

    private boolean updateAvoidBadWifi() {
        boolean settingAvoidBadWifi = "1".equals(Settings.Global.getString(
                mContext.getContentResolver(), Settings.Global.NETWORK_AVOID_BAD_WIFI));

        boolean prev = mAvoidBadWifi;
        mAvoidBadWifi = settingAvoidBadWifi || !configRestrictsAvoidBadWifi();
        return mAvoidBadWifi != prev;
    }

    // TODO: Evaluate whether this is of interest to other consumers of
    // AvoidBadWifiTracker and worth moving out of here.
    private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
        boolean configRestrict = configRestrictsAvoidBadWifi();
        final boolean configRestrict = mAvoidBadWifiTracker.configRestrictsAvoidBadWifi();
        if (!configRestrict) {
            pw.println("Bad Wi-Fi avoidance: unrestricted");
            return;
@@ -2794,8 +2768,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
        pw.increaseIndent();
        pw.println("Config restrict:   " + configRestrict);

        String value = Settings.Global.getString(
                mContext.getContentResolver(), Settings.Global.NETWORK_AVOID_BAD_WIFI);
        final String value = mAvoidBadWifiTracker.getSettingsValue();
        String description;
        // Can't use a switch statement because strings are legal case labels, but null is not.
        if ("0".equals(value)) {
@@ -2858,17 +2831,12 @@ public class ConnectivityService extends IConnectivityManager.Stub
        showValidationNotification(nai, NotificationType.NO_INTERNET);
    }

    // TODO: Delete this like updateMobileDataAlwaysOn above.
    @VisibleForTesting
    void updateNetworkAvoidBadWifi() {
        mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
    }

    private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
        NetworkCapabilities nc = nai.networkCapabilities;
        if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);

        if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && shouldNotifyWifiUnvalidated()) {
        if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
            mAvoidBadWifiTracker.shouldNotifyWifiUnvalidated()) {
            showValidationNotification(nai, NotificationType.LOST_INTERNET);
        }
    }
@@ -2958,18 +2926,6 @@ public class ConnectivityService extends IConnectivityManager.Stub
                    handleMobileDataAlwaysOn();
                    break;
                }
                case EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI: {
                    if (updateAvoidBadWifi()) {
                        rematchAllNetworksAndRequests(null, 0);
                        for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
                            if (nai.networkCapabilities.hasTransport(
                                    NetworkCapabilities.TRANSPORT_WIFI)) {
                                sendUpdatedScoreToFactories(nai);
                            }
                        }
                    }
                    break;
                }
                case EVENT_REQUEST_LINKPROPERTIES:
                    handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
                    break;
@@ -5442,6 +5398,11 @@ public class ConnectivityService extends IConnectivityManager.Stub
        return new NetworkMonitor(context, handler, nai, defaultRequest);
    }

    @VisibleForTesting
    AvoidBadWifiTracker createAvoidBadWifiTracker(Context c, Handler h, Runnable r) {
        return new AvoidBadWifiTracker(c, h, r);
    }

    @VisibleForTesting
    public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
        return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
+28 −6
Original line number Diff line number Diff line
@@ -33,6 +33,7 @@ import android.net.StaticIpConfiguration;
import android.net.dhcp.DhcpClient;
import android.net.metrics.IpConnectivityLog;
import android.net.metrics.IpManagerEvent;
import android.net.util.AvoidBadWifiTracker;
import android.os.INetworkManagementService;
import android.os.Message;
import android.os.RemoteException;
@@ -393,6 +394,7 @@ public class IpManager extends StateMachine {
    private final NetlinkTracker mNetlinkTracker;
    private final WakeupMessage mProvisioningTimeoutAlarm;
    private final WakeupMessage mDhcpActionTimeoutAlarm;
    private final AvoidBadWifiTracker mAvoidBadWifiTracker;
    private final LocalLog mLocalLog;
    private final IpConnectivityLog mMetricsLog = new IpConnectivityLog();

@@ -466,6 +468,8 @@ public class IpManager extends StateMachine {
            Log.e(mTag, "Couldn't register NetlinkTracker: " + e.toString());
        }

        mAvoidBadWifiTracker = new AvoidBadWifiTracker(mContext, getHandler());

        resetLinkProperties();

        mProvisioningTimeoutAlarm = new WakeupMessage(mContext, getHandler(),
@@ -653,7 +657,7 @@ public class IpManager extends StateMachine {
    // object that is a correct and complete assessment of what changed, taking
    // account of the asymmetries described in the comments in this function.
    // Then switch to using it everywhere (IpReachabilityMonitor, etc.).
    private static ProvisioningChange compareProvisioning(
    private ProvisioningChange compareProvisioning(
            LinkProperties oldLp, LinkProperties newLp) {
        ProvisioningChange delta;

@@ -680,6 +684,25 @@ public class IpManager extends StateMachine {
            delta = ProvisioningChange.LOST_PROVISIONING;
        }

        final boolean lostIPv6 = oldLp.isIPv6Provisioned() && !newLp.isIPv6Provisioned();
        final boolean lostIPv4Address = oldLp.hasIPv4Address() && !newLp.hasIPv4Address();
        final boolean lostIPv6Router = oldLp.hasIPv6DefaultRoute() && !newLp.hasIPv6DefaultRoute();

        // If bad wifi avoidance is disabled, then ignore IPv6 loss of
        // provisioning. Otherwise, when a hotspot that loses Internet
        // access sends out a 0-lifetime RA to its clients, the clients
        // will disconnect and then reconnect, avoiding the bad hotspot,
        // instead of getting stuck on the bad hotspot. http://b/31827713 .
        //
        // This is incorrect because if the hotspot then regains Internet
        // access with a different prefix, TCP connections on the
        // deprecated addresses will remain stuck.
        //
        // Note that we can still be disconnected by IpReachabilityMonitor
        // if the IPv6 default gateway (but not the IPv6 DNS servers; see
        // accompanying code in IpReachabilityMonitor) is unreachable.
        final boolean ignoreIPv6ProvisioningLoss = !mAvoidBadWifiTracker.currentValue();

        // Additionally:
        //
        // Partial configurations (e.g., only an IPv4 address with no DNS
@@ -692,8 +715,7 @@ public class IpManager extends StateMachine {
        // Because on such a network isProvisioned() will always return false,
        // delta will never be LOST_PROVISIONING. So check for loss of
        // provisioning here too.
        if ((oldLp.hasIPv4Address() && !newLp.hasIPv4Address()) ||
                (oldLp.isIPv6Provisioned() && !newLp.isIPv6Provisioned())) {
        if (lostIPv4Address || (lostIPv6 && !ignoreIPv6ProvisioningLoss)) {
            delta = ProvisioningChange.LOST_PROVISIONING;
        }

@@ -702,8 +724,7 @@ public class IpManager extends StateMachine {
        // If the previous link properties had a global IPv6 address and an
        // IPv6 default route then also consider the loss of that default route
        // to be a loss of provisioning. See b/27962810.
        if (oldLp.hasGlobalIPv6Address() && oldLp.hasIPv6DefaultRoute() &&
                !newLp.hasIPv6DefaultRoute()) {
        if (oldLp.hasGlobalIPv6Address() && (lostIPv6Router && !ignoreIPv6ProvisioningLoss)) {
            delta = ProvisioningChange.LOST_PROVISIONING;
        }

@@ -1064,7 +1085,8 @@ public class IpManager extends StateMachine {
                            public void notifyLost(InetAddress ip, String logMsg) {
                                mCallback.onReachabilityLost(logMsg);
                            }
                        });
                        },
                        mAvoidBadWifiTracker);
            }
        }

+19 −3
Original line number Diff line number Diff line
@@ -34,6 +34,7 @@ import android.net.netlink.RtNetlinkNeighborMessage;
import android.net.netlink.StructNdaCacheInfo;
import android.net.netlink.StructNdMsg;
import android.net.netlink.StructNlMsgHdr;
import android.net.util.AvoidBadWifiTracker;
import android.os.PowerManager;
import android.os.SystemClock;
import android.system.ErrnoException;
@@ -42,6 +43,7 @@ import android.system.OsConstants;
import android.util.Log;

import java.io.InterruptedIOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
@@ -149,6 +151,7 @@ public class IpReachabilityMonitor {
    private final String mInterfaceName;
    private final int mInterfaceIndex;
    private final Callback mCallback;
    private final AvoidBadWifiTracker mAvoidBadWifiTracker;
    private final NetlinkSocketObserver mNetlinkSocketObserver;
    private final Thread mObserverThread;
    private final IpConnectivityLog mMetricsLog = new IpConnectivityLog();
@@ -219,8 +222,12 @@ public class IpReachabilityMonitor {
        return errno;
    }

    public IpReachabilityMonitor(Context context, String ifName, Callback callback)
                throws IllegalArgumentException {
    public IpReachabilityMonitor(Context context, String ifName, Callback callback) {
        this(context, ifName, callback, null);
    }

    public IpReachabilityMonitor(Context context, String ifName, Callback callback,
            AvoidBadWifiTracker tracker) throws IllegalArgumentException {
        mInterfaceName = ifName;
        int ifIndex = -1;
        try {
@@ -232,6 +239,7 @@ public class IpReachabilityMonitor {
        mWakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, TAG + "." + mInterfaceName);
        mCallback = callback;
        mAvoidBadWifiTracker = tracker;
        mNetlinkSocketObserver = new NetlinkSocketObserver();
        mObserverThread = new Thread(mNetlinkSocketObserver);
        mObserverThread.start();
@@ -355,8 +363,12 @@ public class IpReachabilityMonitor {
                        whatIfLp.removeRoute(route);
                    }
                }

                if (avoidingBadLinks() || !(ip instanceof Inet6Address)) {
                    // We should do this unconditionally, but alas we cannot: b/31827713.
                    whatIfLp.removeDnsServer(ip);
                }
            }

            delta = LinkProperties.compareProvisioning(mLinkProperties, whatIfLp);
        }
@@ -373,6 +385,10 @@ public class IpReachabilityMonitor {
        logNudFailed(delta);
    }

    private boolean avoidingBadLinks() {
        return (mAvoidBadWifiTracker != null) ? mAvoidBadWifiTracker.currentValue() : true;
    }

    public void probeAll() {
        Set<InetAddress> ipProbeList = new HashSet<InetAddress>();
        synchronized (mLock) {
+139 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.util;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.Slog;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.R;

import static android.provider.Settings.Global.NETWORK_AVOID_BAD_WIFI;

/**
 * A class to encapsulate management of the "Smart Networking" capability of
 * avoiding bad Wi-Fi when, for example upstream connectivity is lost or
 * certain critical link failures occur.
 *
 * This enables the device to switch to another form of connectivity, like
 * mobile, if it's available and working.
 *
 * The Runnable |cb|, if given, is called on the supplied Handler's thread
 * whether the computed "avoid bad wifi" value changes.
 *
 * Disabling this reverts the device to a level of networking sophistication
 * circa 2012-13 by disabling disparate code paths each of which contribute to
 * maintaining continuous, working Internet connectivity.
 *
 * @hide
 */
public class AvoidBadWifiTracker {
    private static String TAG = AvoidBadWifiTracker.class.getSimpleName();

    private final Context mContext;
    private final Handler mHandler;
    private final Runnable mReevaluateRunnable;
    private final SettingObserver mSettingObserver;
    private volatile boolean mAvoidBadWifi = true;

    public AvoidBadWifiTracker(Context ctx, Handler handler) {
        this(ctx, handler, null);
    }

    public AvoidBadWifiTracker(Context ctx, Handler handler, Runnable cb) {
        mContext = ctx;
        mHandler = handler;
        mReevaluateRunnable = () -> { if (update() && cb != null) cb.run(); };
        mSettingObserver = new SettingObserver();

        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
        mContext.registerReceiverAsUser(new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                reevaluate();
            }
        }, UserHandle.ALL, intentFilter, null, null);

        update();
    }

    public boolean currentValue() {
        return mAvoidBadWifi;
    }

    /**
     * Whether the device or carrier configuration disables avoiding bad wifi by default.
     */
    public boolean configRestrictsAvoidBadWifi() {
        return (mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi) == 0);
    }

    /**
     * Whether we should display a notification when wifi becomes unvalidated.
     */
    public boolean shouldNotifyWifiUnvalidated() {
        return configRestrictsAvoidBadWifi() && getSettingsValue() == null;
    }

    public String getSettingsValue() {
        final ContentResolver resolver = mContext.getContentResolver();
        return Settings.Global.getString(resolver, NETWORK_AVOID_BAD_WIFI);
    }

    @VisibleForTesting
    public void reevaluate() {
        mHandler.post(mReevaluateRunnable);
    }

    public boolean update() {
        final boolean settingAvoidBadWifi = "1".equals(getSettingsValue());
        final boolean prev = mAvoidBadWifi;
        mAvoidBadWifi = settingAvoidBadWifi || !configRestrictsAvoidBadWifi();
        return mAvoidBadWifi != prev;
    }

    private class SettingObserver extends ContentObserver {
        private final Uri mUri = Settings.Global.getUriFor(NETWORK_AVOID_BAD_WIFI);

        public SettingObserver() {
            super(null);
            final ContentResolver resolver = mContext.getContentResolver();
            resolver.registerContentObserver(mUri, false, this);
        }

        @Override
        public void onChange(boolean selfChange) {
            Slog.wtf(TAG, "Should never be reached.");
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            if (!mUri.equals(uri)) return;
            reevaluate();
        }
    }
}
+48 −26

File changed.

Preview size limit exceeded, changes collapsed.