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

Commit bee04d08 authored by Philip P. Moltmann's avatar Philip P. Moltmann
Browse files

Clean up USB*Manager.

Just automatic cleanup.

Test: Built
Change-Id: I1da09d6b43503a6b77a3619f0f8513ef39cf2d75
parent cc1ee935
Loading
Loading
Loading
Loading
+6 −8
Original line number Diff line number Diff line
@@ -43,12 +43,10 @@ import com.android.internal.util.IndentingPrintWriter;
import com.android.server.FgThread;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.Arrays;

@@ -56,10 +54,10 @@ public class UsbDebuggingManager {
    private static final String TAG = "UsbDebuggingManager";
    private static final boolean DEBUG = false;

    private final String ADBD_SOCKET = "adbd";
    private final String ADB_DIRECTORY = "misc/adb";
    private final String ADB_KEYS_FILE = "adb_keys";
    private final int BUFFER_SIZE = 4096;
    private static final String ADBD_SOCKET = "adbd";
    private static final String ADB_DIRECTORY = "misc/adb";
    private static final String ADB_KEYS_FILE = "adb_keys";
    private static final int BUFFER_SIZE = 4096;

    private final Context mContext;
    private final Handler mHandler;
@@ -346,7 +344,7 @@ public class UsbDebuggingManager {
    }

    /**
     * @returns true if the componentName led to an Activity that was started.
     * @return true if the componentName led to an Activity that was started.
     */
    private boolean startConfirmationActivity(ComponentName componentName, UserHandle userHandle,
            String key, String fingerprints) {
@@ -365,7 +363,7 @@ public class UsbDebuggingManager {
    }

    /**
     * @returns true if the componentName led to a Service that was started.
     * @return true if the componentName led to a Service that was started.
     */
    private boolean startConfirmationService(ComponentName componentName, UserHandle userHandle,
            String key, String fingerprints) {
+54 −68
Original line number Diff line number Diff line
@@ -91,14 +91,6 @@ public class UsbDeviceManager {
     */
    private static final String USB_CONFIG_PROPERTY = "sys.usb.config";

    /**
     * The property which stores the current build type (user/userdebug/eng).
     */
    private static final String BUILD_TYPE_PROPERTY = "ro.build.type";

    private static final String BUILD_TYPE_USERDEBUG = "userdebug";
    private static final String BUILD_TYPE_ENG = "eng";

    /**
     * The non-persistent property which stores the current USB actual state.
     */
@@ -179,7 +171,7 @@ public class UsbDeviceManager {
    private static Set<Integer> sBlackListedInterfaces;

    static {
        sBlackListedInterfaces = new HashSet<Integer>();
        sBlackListedInterfaces = new HashSet<>();
        sBlackListedInterfaces.add(UsbConstants.USB_CLASS_AUDIO);
        sBlackListedInterfaces.add(UsbConstants.USB_CLASS_COMM);
        sBlackListedInterfaces.add(UsbConstants.USB_CLASS_HID);
@@ -191,7 +183,7 @@ public class UsbDeviceManager {
        sBlackListedInterfaces.add(UsbConstants.USB_CLASS_CONTENT_SEC);
        sBlackListedInterfaces.add(UsbConstants.USB_CLASS_VIDEO);
        sBlackListedInterfaces.add(UsbConstants.USB_CLASS_WIRELESS_CONTROLLER);
    };
    }

    private class AdbSettingsObserver extends ContentObserver {
        public AdbSettingsObserver() {
@@ -225,7 +217,32 @@ public class UsbDeviceManager {
        }
    };

    private final BroadcastReceiver mPortReceiver = new BroadcastReceiver() {
    public UsbDeviceManager(Context context, UsbAlsaManager alsaManager,
            UsbSettingsManager settingsManager) {
        mContext = context;
        mUsbAlsaManager = alsaManager;
        mSettingsManager = settingsManager;
        mContentResolver = context.getContentResolver();
        PackageManager pm = mContext.getPackageManager();
        mHasUsbAccessory = pm.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
        initRndisAddress();

        readOemUsbOverrideConfig();

        mHandler = new UsbHandler(FgThread.get().getLooper());

        if (nativeIsStartRequested()) {
            if (DEBUG) Slog.d(TAG, "accessory attached at boot");
            startAccessoryMode();
        }

        boolean secureAdbEnabled = SystemProperties.getBoolean("ro.adb.secure", false);
        boolean dataEncrypted = "1".equals(SystemProperties.get("vold.decrypt"));
        if (secureAdbEnabled && !dataEncrypted) {
            mDebuggingManager = new UsbDebuggingManager(context);
        }

        BroadcastReceiver portReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                UsbPort port = intent.getParcelableExtra(UsbManager.EXTRA_PORT);
@@ -234,7 +251,7 @@ public class UsbDeviceManager {
            }
        };

    private final BroadcastReceiver mChargingReceiver = new BroadcastReceiver() {
        BroadcastReceiver chargingReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
@@ -243,7 +260,7 @@ public class UsbDeviceManager {
            }
        };

    private final BroadcastReceiver mHostReceiver = new BroadcastReceiver() {
        BroadcastReceiver hostReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Iterator devices = ((UsbManager) context.getSystemService(Context.USB_SERVICE))
@@ -256,48 +273,24 @@ public class UsbDeviceManager {
            }
        };

    private final BroadcastReceiver mLanguageChangedReceiver = new BroadcastReceiver() {
        BroadcastReceiver languageChangedReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mHandler.sendEmptyMessage(MSG_LOCALE_CHANGED);
            }
        };

    public UsbDeviceManager(Context context, UsbAlsaManager alsaManager,
            UsbSettingsManager settingsManager) {
        mContext = context;
        mUsbAlsaManager = alsaManager;
        mSettingsManager = settingsManager;
        mContentResolver = context.getContentResolver();
        PackageManager pm = mContext.getPackageManager();
        mHasUsbAccessory = pm.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
        initRndisAddress();

        readOemUsbOverrideConfig();

        mHandler = new UsbHandler(FgThread.get().getLooper());

        if (nativeIsStartRequested()) {
            if (DEBUG) Slog.d(TAG, "accessory attached at boot");
            startAccessoryMode();
        }

        boolean secureAdbEnabled = SystemProperties.getBoolean("ro.adb.secure", false);
        boolean dataEncrypted = "1".equals(SystemProperties.get("vold.decrypt"));
        if (secureAdbEnabled && !dataEncrypted) {
            mDebuggingManager = new UsbDebuggingManager(context);
        }
        mContext.registerReceiver(mPortReceiver,
        mContext.registerReceiver(portReceiver,
                new IntentFilter(UsbManager.ACTION_USB_PORT_CHANGED));
        mContext.registerReceiver(mChargingReceiver,
        mContext.registerReceiver(chargingReceiver,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        IntentFilter filter =
                new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        mContext.registerReceiver(mHostReceiver, filter);
        mContext.registerReceiver(hostReceiver, filter);

        mContext.registerReceiver(mLanguageChangedReceiver,
        mContext.registerReceiver(languageChangedReceiver,
                new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
    }

@@ -326,7 +319,7 @@ public class UsbDeviceManager {

        // We do not show the USB notification if the primary volume supports mass storage.
        // The legacy mass storage UI will be used instead.
        boolean massStorageSupported = false;
        boolean massStorageSupported;
        final StorageManager storageManager = StorageManager.from(mContext);
        final StorageVolume primary = storageManager.getPrimaryVolume();
        massStorageSupported = primary != null && primary.allowMassStorage();
@@ -454,7 +447,7 @@ public class UsbDeviceManager {
                            SystemProperties.get(USB_STATE_PROPERTY));
                }

                /**
                /*
                 * Use the normal bootmode persistent prop to maintain state of adb across
                 * all boot modes.
                 */
@@ -462,7 +455,7 @@ public class UsbDeviceManager {
                        SystemProperties.get(USB_PERSISTENT_CONFIG_PROPERTY),
                        UsbManager.USB_FUNCTION_ADB);

                /**
                /*
                 * Previous versions can set persist config to mtp/ptp but it does not
                 * get reset on OTA. Reset the property here instead.
                 */
@@ -652,10 +645,7 @@ public class UsbDeviceManager {

        private boolean isNormalBoot() {
            String bootMode = SystemProperties.get(BOOT_MODE_PROPERTY, "unknown");
            if (bootMode.equals(NORMAL_BOOT) || bootMode.equals("unknown")) {
                return true;
            }
            return false;
            return bootMode.equals(NORMAL_BOOT) || bootMode.equals("unknown");
        }

        private boolean trySetEnabledFunctions(String functions, boolean forceRestart) {
@@ -1311,25 +1301,21 @@ public class UsbDeviceManager {
                String[] items = config.split(":");
                if (items.length == 3 || items.length == 4) {
                    if (mOemModeMap == null) {
                        mOemModeMap = new HashMap<String, HashMap<String,
                                Pair<String, String>>>();
                        mOemModeMap = new HashMap<>();
                    }
                    HashMap<String, Pair<String, String>> overrideMap
                            = mOemModeMap.get(items[0]);
                    if (overrideMap == null) {
                        overrideMap = new HashMap<String,
                                Pair<String, String>>();
                        overrideMap = new HashMap<>();
                        mOemModeMap.put(items[0], overrideMap);
                    }

                    // Favoring the first combination if duplicate exists
                    if (!overrideMap.containsKey(items[1])) {
                        if (items.length == 3) {
                            overrideMap.put(items[1],
                                    new Pair<String, String>(items[2], ""));
                            overrideMap.put(items[1], new Pair<>(items[2], ""));
                        } else {
                            overrideMap.put(items[1],
                                    new Pair<String, String>(items[2], items[3]));
                            overrideMap.put(items[1], new Pair<>(items[2], items[3]));
                        }
                    }
                }
@@ -1390,7 +1376,7 @@ public class UsbDeviceManager {
        String bootMode = SystemProperties.get(BOOT_MODE_PROPERTY, "unknown");
        String persistProp = USB_PERSISTENT_CONFIG_PROPERTY;
        if (!(bootMode.equals(NORMAL_BOOT) || bootMode.equals("unknown"))) {
            if (functions == true) {
            if (functions) {
                persistProp = "persist.sys.usb." + bootMode + ".func";
            } else {
                persistProp = "persist.sys.usb." + bootMode + ".config";
+15 −20
Original line number Diff line number Diff line
@@ -16,7 +16,6 @@

package com.android.server.usb;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.ComponentName;
import android.content.Context;
@@ -44,13 +43,11 @@ public class UsbHostManager {
    private static final boolean DEBUG = false;

    // contains all connected USB devices
    private final HashMap<String, UsbDevice> mDevices = new HashMap<String, UsbDevice>();

    private final HashMap<String, UsbDevice> mDevices = new HashMap<>();

    // USB busses to exclude from USB host support
    private final String[] mHostBlacklist;

    private final Context mContext;
    private final Object mLock = new Object();

    private UsbDevice mNewDevice;
@@ -71,7 +68,6 @@ public class UsbHostManager {

    public UsbHostManager(Context context, UsbAlsaManager alsaManager,
            UsbSettingsManager settingsManager) {
        mContext = context;
        mHostBlacklist = context.getResources().getStringArray(
                com.android.internal.R.array.config_usbHostBlacklist);
        mUsbAlsaManager = alsaManager;
@@ -119,17 +115,14 @@ public class UsbHostManager {
    }

    /* returns true if the USB device should not be accessible by applications */
    private boolean isBlackListed(int clazz, int subClass, int protocol) {
    private boolean isBlackListed(int clazz, int subClass) {
        // blacklist hubs
        if (clazz == UsbConstants.USB_CLASS_HUB) return true;

        // blacklist HID boot devices (mouse and keyboard)
        if (clazz == UsbConstants.USB_CLASS_HID &&
                subClass == UsbConstants.USB_INTERFACE_SUBCLASS_BOOT) {
            return true;
        }
        return clazz == UsbConstants.USB_CLASS_HID
                && subClass == UsbConstants.USB_INTERFACE_SUBCLASS_BOOT;

        return false;
    }

    /* Called from JNI in monitorUsbHostBus() to report new USB devices
@@ -137,6 +130,7 @@ public class UsbHostManager {
       interfaces and endpoints, and finally call endUsbDeviceAdded after all descriptors
       have been processed
     */
    @SuppressWarnings("unused")
    private boolean beginUsbDeviceAdded(String deviceName, int vendorID, int productID,
            int deviceClass, int deviceSubclass, int deviceProtocol,
            String manufacturerName, String productName, int version, String serialNumber) {
@@ -161,7 +155,7 @@ public class UsbHostManager {
        // such test until endUsbDeviceAdded() when we have that info.

        if (isBlackListed(deviceName) ||
                isBlackListed(deviceClass, deviceSubclass, deviceProtocol)) {
                isBlackListed(deviceClass, deviceSubclass)) {
            return false;
        }

@@ -183,9 +177,9 @@ public class UsbHostManager {
                    deviceClass, deviceSubclass, deviceProtocol,
                    manufacturerName, productName, versionString, serialNumber);

            mNewConfigurations = new ArrayList<UsbConfiguration>();
            mNewInterfaces = new ArrayList<UsbInterface>();
            mNewEndpoints = new ArrayList<UsbEndpoint>();
            mNewConfigurations = new ArrayList<>();
            mNewInterfaces = new ArrayList<>();
            mNewEndpoints = new ArrayList<>();
        }

        return true;
@@ -194,6 +188,7 @@ public class UsbHostManager {
    /* Called from JNI in monitorUsbHostBus() to report new USB configuration for the device
       currently being added.  Returns true if successful, false in case of error.
     */
    @SuppressWarnings("unused")
    private void addUsbConfiguration(int id, String name, int attributes, int maxPower) {
        if (mNewConfiguration != null) {
            mNewConfiguration.setInterfaces(
@@ -208,6 +203,7 @@ public class UsbHostManager {
    /* Called from JNI in monitorUsbHostBus() to report new USB interface for the device
       currently being added.  Returns true if successful, false in case of error.
     */
    @SuppressWarnings("unused")
    private void addUsbInterface(int id, String name, int altSetting,
            int Class, int subClass, int protocol) {
        if (mNewInterface != null) {
@@ -223,11 +219,13 @@ public class UsbHostManager {
    /* Called from JNI in monitorUsbHostBus() to report new USB endpoint for the device
       currently being added.  Returns true if successful, false in case of error.
     */
    @SuppressWarnings("unused")
    private void addUsbEndpoint(int address, int attributes, int maxPacketSize, int interval) {
        mNewEndpoints.add(new UsbEndpoint(address, attributes, maxPacketSize, interval));
    }

    /* Called from JNI in monitorUsbHostBus() to finish adding a new device */
    @SuppressWarnings("unused")
    private void endUsbDeviceAdded() {
        if (DEBUG) {
            Slog.d(TAG, "usb:UsbHostManager.endUsbDeviceAdded()");
@@ -273,6 +271,7 @@ public class UsbHostManager {
    }

    /* Called from JNI in monitorUsbHostBus to report USB device removal */
    @SuppressWarnings("unused")
    private void usbDeviceRemoved(String deviceName) {
        synchronized (mLock) {
            UsbDevice device = mDevices.remove(deviceName);
@@ -288,11 +287,7 @@ public class UsbHostManager {
        synchronized (mLock) {
            // Create a thread to call into native code to wait for USB host events.
            // This thread will call us back on usbDeviceAdded and usbDeviceRemoved.
            Runnable runnable = new Runnable() {
                public void run() {
                    monitorUsbHostBus();
                }
            };
            Runnable runnable = this::monitorUsbHostBus;
            new Thread(null, runnable, "UsbService host thread").start();
        }
    }
+9 −23
Original line number Diff line number Diff line
@@ -87,9 +87,6 @@ public class UsbPortManager {
    // Mostly due a command sent by the remote Usb device.
    private HALCallback mHALCallback = new HALCallback(null, this);

    // Notification object used to listen to the start of the usb daemon.
    private final ServiceNotification mServiceNotification = new ServiceNotification();

    // Cookie sent for usb hal death notification.
    private static final int USB_HAL_DEATH_COOKIE = 1000;

@@ -107,18 +104,20 @@ public class UsbPortManager {
    // Ports may temporarily have different dispositions as they are added or removed
    // but the class invariant is that this list will only contain ports with DISPOSITION_READY
    // except while updatePortsLocked() is in progress.
    private final ArrayMap<String, PortInfo> mPorts = new ArrayMap<String, PortInfo>();
    private final ArrayMap<String, PortInfo> mPorts = new ArrayMap<>();

    // List of all simulated ports, indexed by id.
    private final ArrayMap<String, RawPortInfo> mSimulatedPorts =
            new ArrayMap<String, RawPortInfo>();
            new ArrayMap<>();

    public UsbPortManager(Context context) {
        mContext = context;
        try {
            ServiceNotification serviceNotification = new ServiceNotification();

            boolean ret = IServiceManager.getService()
                    .registerForNotifications("android.hardware.usb@1.0::IUsb",
                            "", mServiceNotification);
                            "", serviceNotification);
            if (!ret) {
                logAndPrint(Log.ERROR, null,
                        "Failed to register service start notification");
@@ -258,7 +257,6 @@ public class UsbPortManager {
                        logAndPrintException(pw, "Failed to set the USB port mode: "
                                + "portId=" + portId
                                + ", newMode=" + UsbPort.modeToString(newRole.role), e);
                        return;
                    }
                } else {
                    // Change power and data role independently as needed.
@@ -289,7 +287,6 @@ public class UsbPortManager {
                                            + ", newDataRole=" + UsbPort.dataRoleToString(newRole
                                            .role),
                                    e);
                            return;
                        }
                    }
                }
@@ -415,10 +412,6 @@ public class UsbPortManager {
        public IndentingPrintWriter pw;
        public UsbPortManager portManager;

        HALCallback() {
            super();
        }

        HALCallback(IndentingPrintWriter pw, UsbPortManager portManager) {
            this.pw = pw;
            this.portManager = portManager;
@@ -434,7 +427,7 @@ public class UsbPortManager {
                return;
            }

            ArrayList<RawPortInfo> newPortInfo = new ArrayList<RawPortInfo>();
            ArrayList<RawPortInfo> newPortInfo = new ArrayList<>();

            for (PortStatus current : currentPortStatus) {
                RawPortInfo temp = new RawPortInfo(current.portName,
@@ -452,7 +445,6 @@ public class UsbPortManager {
            message.what = MSG_UPDATE_PORTS;
            message.setData(bundle);
            portManager.mHandler.sendMessage(message);
            return;
        }


@@ -467,7 +459,7 @@ public class UsbPortManager {
                return;
            }

            ArrayList<RawPortInfo> newPortInfo = new ArrayList<RawPortInfo>();
            ArrayList<RawPortInfo> newPortInfo = new ArrayList<>();

            for (PortStatus_1_1 current : currentPortStatus) {
                RawPortInfo temp = new RawPortInfo(current.status.portName,
@@ -485,7 +477,6 @@ public class UsbPortManager {
            message.what = MSG_UPDATE_PORTS;
            message.setData(bundle);
            portManager.mHandler.sendMessage(message);
            return;
        }

        public void notifyRoleSwitchStatus(String portName, PortRole role, int retval) {
@@ -495,7 +486,7 @@ public class UsbPortManager {
                logAndPrint(Log.ERROR, pw, portName + " role switch failed");
            }
        }
    };
    }

    final class DeathRecipient implements HwBinder.DeathRecipient {
        public IndentingPrintWriter pw;
@@ -701,12 +692,7 @@ public class UsbPortManager {

        // Guard against possible reentrance by posting the broadcast from the handler
        // instead of from within the critical section.
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
            }
        });
        mHandler.post(() -> mContext.sendBroadcastAsUser(intent, UserHandle.ALL));
    }

    private static void logAndPrint(int priority, IndentingPrintWriter pw, String msg) {
+21 −30

File changed.

Preview size limit exceeded, changes collapsed.

Loading