diff options
48 files changed, 2504 insertions, 1301 deletions
diff --git a/compiled-classes-phone b/compiled-classes-phone index ec3371e45711..2cbfc2264ebb 100644 --- a/compiled-classes-phone +++ b/compiled-classes-phone @@ -633,6 +633,7 @@ android.bluetooth.BluetoothAudioConfig android.bluetooth.BluetoothClass android.bluetooth.BluetoothClass$1 android.bluetooth.BluetoothCodecConfig +android.bluetooth.BluetoothCodecStatus android.bluetooth.BluetoothDevice android.bluetooth.BluetoothDevice$1 android.bluetooth.BluetoothDevice$2 diff --git a/core/java/android/bluetooth/BluetoothA2dp.java b/core/java/android/bluetooth/BluetoothA2dp.java index 1165fce3ce0a..4960159db212 100644 --- a/core/java/android/bluetooth/BluetoothA2dp.java +++ b/core/java/android/bluetooth/BluetoothA2dp.java @@ -105,10 +105,9 @@ public final class BluetoothA2dp implements BluetoothProfile { * Intent used to broadcast the change in the Audio Codec state of the * A2DP Source profile. * - * <p>This intent will have 3 extras: + * <p>This intent will have 2 extras: * <ul> - * <li> {@link #EXTRA_CODEC_CONFIG} - The current codec configuration. </li> - * <li> {@link #EXTRA_PREVIOUS_CODEC_CONFIG} - The previous codec configuration. </li> + * <li> {@link BluetoothCodecStatus#EXTRA_CODEC_STATUS} - The codec status. </li> * <li> {@link BluetoothDevice#EXTRA_DEVICE} - The remote device if the device is currently * connected, otherwise it is not included.</li> * </ul> @@ -564,24 +563,24 @@ public final class BluetoothA2dp implements BluetoothProfile { } /** - * Gets the current codec configuration. + * Gets the current codec status (configuration and capability). * - * @return the current codec configuration + * @return the current codec status * @hide */ - public BluetoothCodecConfig getCodecConfig() { - if (DBG) Log.d(TAG, "getCodecConfig"); + public BluetoothCodecStatus getCodecStatus() { + if (DBG) Log.d(TAG, "getCodecStatus"); try { mServiceLock.readLock().lock(); if (mService != null && isEnabled()) { - return mService.getCodecConfig(); + return mService.getCodecStatus(); } if (mService == null) { Log.w(TAG, "Proxy not attached to service"); } return null; } catch (RemoteException e) { - Log.e(TAG, "Error talking to BT service in getCodecConfig()", e); + Log.e(TAG, "Error talking to BT service in getCodecStatus()", e); return null; } finally { mServiceLock.readLock().unlock(); diff --git a/core/java/android/bluetooth/BluetoothCodecConfig.java b/core/java/android/bluetooth/BluetoothCodecConfig.java index a37a0b38aa7c..a48210340e63 100644 --- a/core/java/android/bluetooth/BluetoothCodecConfig.java +++ b/core/java/android/bluetooth/BluetoothCodecConfig.java @@ -29,24 +29,6 @@ import java.util.Objects; * {@hide} */ public final class BluetoothCodecConfig implements Parcelable { - - /** - * Extra for the codec configuration intents of the individual profiles. - * - * This extra represents the current codec configuration of the A2DP - * profile. - */ - public static final String EXTRA_CODEC_CONFIG = "android.bluetooth.codec.extra.CODEC_CONFIG"; - - /** - * Extra for the codec configuration intents of the individual profiles. - * - * This extra represents the previous codec configuration of the A2DP - * profile. - */ - public static final String EXTRA_PREVIOUS_CODEC_CONFIG = - "android.bluetooth.codec.extra.PREVIOUS_CODEC_CONFIG"; - // Add an entry for each source codec here. // NOTE: The values should be same as those listed in the following file: // hardware/libhardware/include/hardware/bt_av.h @@ -128,13 +110,93 @@ public final class BluetoothCodecConfig implements Parcelable { mCodecSpecific2, mCodecSpecific3, mCodecSpecific4); } + /** + * Checks whether the object contains valid codec configuration. + * + * @return true if the object contains valid codec configuration, + * otherwise false. + */ + public boolean isValid() { + return (mSampleRate != SAMPLE_RATE_NONE) && + (mBitsPerSample != BITS_PER_SAMPLE_NONE) && + (mChannelMode != CHANNEL_MODE_NONE); + } + + /** + * Adds capability string to an existing string. + * + * @param prevStr the previous string with the capabilities. Can be + * a null pointer. + * @param capStr the capability string to append to prevStr argument. + * @return the result string in the form "prevStr|capStr". + */ + private static String appendCapabilityToString(String prevStr, + String capStr) { + if (prevStr == null) { + return capStr; + } + return prevStr + "|" + capStr; + } + @Override public String toString() { - return "{mCodecType:" + mCodecType + + String sampleRateStr = null; + if (mSampleRate == SAMPLE_RATE_NONE) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "NONE"); + } + if ((mSampleRate & SAMPLE_RATE_44100) != 0) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "44100"); + } + if ((mSampleRate & SAMPLE_RATE_48000) != 0) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "48000"); + } + if ((mSampleRate & SAMPLE_RATE_88200) != 0) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "88200"); + } + if ((mSampleRate & SAMPLE_RATE_96000) != 0) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "96000"); + } + if ((mSampleRate & SAMPLE_RATE_176400) != 0) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "176400"); + } + if ((mSampleRate & SAMPLE_RATE_192000) != 0) { + sampleRateStr = appendCapabilityToString(sampleRateStr, "192000"); + } + + String bitsPerSampleStr = null; + if (mBitsPerSample == BITS_PER_SAMPLE_NONE) { + bitsPerSampleStr = appendCapabilityToString(bitsPerSampleStr, "NONE"); + } + if ((mBitsPerSample & BITS_PER_SAMPLE_16) != 0) { + bitsPerSampleStr = appendCapabilityToString(bitsPerSampleStr, "16"); + } + if ((mBitsPerSample & BITS_PER_SAMPLE_24) != 0) { + bitsPerSampleStr = appendCapabilityToString(bitsPerSampleStr, "24"); + } + if ((mBitsPerSample & BITS_PER_SAMPLE_32) != 0) { + bitsPerSampleStr = appendCapabilityToString(bitsPerSampleStr, "32"); + } + + String channelModeStr = null; + if (mChannelMode == CHANNEL_MODE_NONE) { + channelModeStr = appendCapabilityToString(channelModeStr, "NONE"); + } + if ((mChannelMode & CHANNEL_MODE_MONO) != 0) { + channelModeStr = appendCapabilityToString(channelModeStr, "MONO"); + } + if ((mChannelMode & CHANNEL_MODE_STEREO) != 0) { + channelModeStr = appendCapabilityToString(channelModeStr, "STEREO"); + } + + return "{codecName:" + getCodecName() + + ",mCodecType:" + mCodecType + ",mCodecPriority:" + mCodecPriority + ",mSampleRate:" + String.format("0x%x", mSampleRate) + + "(" + sampleRateStr + ")" + ",mBitsPerSample:" + String.format("0x%x", mBitsPerSample) + + "(" + bitsPerSampleStr + ")" + ",mChannelMode:" + String.format("0x%x", mChannelMode) + + "(" + channelModeStr + ")" + ",mCodecSpecific1:" + mCodecSpecific1 + ",mCodecSpecific2:" + mCodecSpecific2 + ",mCodecSpecific3:" + mCodecSpecific3 + @@ -181,7 +243,32 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns the codec type. + * Gets the codec name. + * + * @return the codec name + */ + public String getCodecName() { + switch (mCodecType) { + case SOURCE_CODEC_TYPE_SBC: + return "SBC"; + case SOURCE_CODEC_TYPE_AAC: + return "AAC"; + case SOURCE_CODEC_TYPE_APTX: + return "aptX"; + case SOURCE_CODEC_TYPE_APTX_HD: + return "aptX HD"; + case SOURCE_CODEC_TYPE_LDAC: + return "LDAC"; + case SOURCE_CODEC_TYPE_INVALID: + return "INVALID CODEC"; + default: + break; + } + return "UNKNOWN CODEC(" + mCodecType + ")"; + } + + /** + * Gets the codec type. * See {@link android.bluetooth.BluetoothCodecConfig#SOURCE_CODEC_TYPE_SBC}. * * @return the codec type @@ -191,7 +278,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns the codec selection priority. + * Gets the codec selection priority. * The codec selection priority is relative to other codecs: larger value * means higher priority. If 0, reset to default. * @@ -202,7 +289,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns the codec sample rate. The value can be a bitmask with all + * Gets the codec sample rate. The value can be a bitmask with all * supported sample rates: * {@link android.bluetooth.BluetoothCodecConfig#SAMPLE_RATE_NONE} or * {@link android.bluetooth.BluetoothCodecConfig#SAMPLE_RATE_44100} or @@ -219,7 +306,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns the codec bits per sample. The value can be a bitmask with all + * Gets the codec bits per sample. The value can be a bitmask with all * bits per sample supported: * {@link android.bluetooth.BluetoothCodecConfig#BITS_PER_SAMPLE_NONE} or * {@link android.bluetooth.BluetoothCodecConfig#BITS_PER_SAMPLE_16} or @@ -233,7 +320,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns the codec channel mode. The value can be a bitmask with all + * Gets the codec channel mode. The value can be a bitmask with all * supported channel modes: * {@link android.bluetooth.BluetoothCodecConfig#CHANNEL_MODE_NONE} or * {@link android.bluetooth.BluetoothCodecConfig#CHANNEL_MODE_MONO} or @@ -246,7 +333,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns a codec specific value1. + * Gets a codec specific value1. * * @return a codec specific value1. */ @@ -255,7 +342,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns a codec specific value2. + * Gets a codec specific value2. * * @return a codec specific value2 */ @@ -264,7 +351,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns a codec specific value3. + * Gets a codec specific value3. * * @return a codec specific value3 */ @@ -273,7 +360,7 @@ public final class BluetoothCodecConfig implements Parcelable { } /** - * Returns a codec specific value4. + * Gets a codec specific value4. * * @return a codec specific value4 */ diff --git a/core/java/android/bluetooth/BluetoothCodecStatus.aidl b/core/java/android/bluetooth/BluetoothCodecStatus.aidl new file mode 100644 index 000000000000..f9c3a3de2f4c --- /dev/null +++ b/core/java/android/bluetooth/BluetoothCodecStatus.aidl @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2017 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.bluetooth; + +parcelable BluetoothCodecStatus; diff --git a/core/java/android/bluetooth/BluetoothCodecStatus.java b/core/java/android/bluetooth/BluetoothCodecStatus.java new file mode 100644 index 000000000000..c8cd8d17ce36 --- /dev/null +++ b/core/java/android/bluetooth/BluetoothCodecStatus.java @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2017 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.bluetooth; + +import android.os.Parcel; +import android.os.Parcelable; + +import java.util.Arrays; +import java.util.Objects; + +/** + * Represents the codec status (configuration and capability) for a Bluetooth + * A2DP source device. + * + * {@see BluetoothA2dp} + * + * {@hide} + */ +public final class BluetoothCodecStatus implements Parcelable { + /** + * Extra for the codec configuration intents of the individual profiles. + * + * This extra represents the current codec status of the A2DP + * profile. + */ + public static final String EXTRA_CODEC_STATUS = + "android.bluetooth.codec.extra.CODEC_STATUS"; + + private final BluetoothCodecConfig mCodecConfig; + private final BluetoothCodecConfig[] mCodecsLocalCapabilities; + private final BluetoothCodecConfig[] mCodecsSelectableCapabilities; + + public BluetoothCodecStatus(BluetoothCodecConfig codecConfig, + BluetoothCodecConfig[] codecsLocalCapabilities, + BluetoothCodecConfig[] codecsSelectableCapabilities) { + mCodecConfig = codecConfig; + mCodecsLocalCapabilities = codecsLocalCapabilities; + mCodecsSelectableCapabilities = codecsSelectableCapabilities; + } + + @Override + public boolean equals(Object o) { + if (o instanceof BluetoothCodecStatus) { + BluetoothCodecStatus other = (BluetoothCodecStatus)o; + return (Objects.equals(other.mCodecConfig, mCodecConfig) && + Objects.equals(other.mCodecsLocalCapabilities, + mCodecsLocalCapabilities) && + Objects.equals(other.mCodecsSelectableCapabilities, + mCodecsSelectableCapabilities)); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hash(mCodecConfig, mCodecsLocalCapabilities, + mCodecsLocalCapabilities); + } + + @Override + public String toString() { + return "{mCodecConfig:" + mCodecConfig + + ",mCodecsLocalCapabilities:" + Arrays.toString(mCodecsLocalCapabilities) + + ",mCodecsSelectableCapabilities:" + Arrays.toString(mCodecsSelectableCapabilities) + + "}"; + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<BluetoothCodecStatus> CREATOR = + new Parcelable.Creator<BluetoothCodecStatus>() { + public BluetoothCodecStatus createFromParcel(Parcel in) { + final BluetoothCodecConfig codecConfig = in.readTypedObject(BluetoothCodecConfig.CREATOR); + final BluetoothCodecConfig[] codecsLocalCapabilities = in.createTypedArray(BluetoothCodecConfig.CREATOR); + final BluetoothCodecConfig[] codecsSelectableCapabilities = in.createTypedArray(BluetoothCodecConfig.CREATOR); + + return new BluetoothCodecStatus(codecConfig, + codecsLocalCapabilities, + codecsSelectableCapabilities); + } + public BluetoothCodecStatus[] newArray(int size) { + return new BluetoothCodecStatus[size]; + } + }; + + public void writeToParcel(Parcel out, int flags) { + out.writeTypedObject(mCodecConfig, 0); + out.writeTypedArray(mCodecsLocalCapabilities, 0); + out.writeTypedArray(mCodecsSelectableCapabilities, 0); + } + + /** + * Gets the current codec configuration. + * + * @return the current codec configuration + */ + public BluetoothCodecConfig getCodecConfig() { + return mCodecConfig; + } + + /** + * Gets the codecs local capabilities. + * + * @return an array with the codecs local capabilities + */ + public BluetoothCodecConfig[] getCodecsLocalCapabilities() { + return mCodecsLocalCapabilities; + } + + /** + * Gets the codecs selectable capabilities. + * + * @return an array with the codecs selectable capabilities + */ + public BluetoothCodecConfig[] getCodecsSelectableCapabilities() { + return mCodecsSelectableCapabilities; + } +} diff --git a/core/java/android/bluetooth/IBluetoothA2dp.aidl b/core/java/android/bluetooth/IBluetoothA2dp.aidl index 5b524eb18a5e..dbb5b7d7944b 100644 --- a/core/java/android/bluetooth/IBluetoothA2dp.aidl +++ b/core/java/android/bluetooth/IBluetoothA2dp.aidl @@ -17,6 +17,7 @@ package android.bluetooth; import android.bluetooth.BluetoothCodecConfig; +import android.bluetooth.BluetoothCodecStatus; import android.bluetooth.BluetoothDevice; /** @@ -37,6 +38,6 @@ interface IBluetoothA2dp { oneway void adjustAvrcpAbsoluteVolume(int direction); oneway void setAvrcpAbsoluteVolume(int volume); boolean isA2dpPlaying(in BluetoothDevice device); - BluetoothCodecConfig getCodecConfig(); + BluetoothCodecStatus getCodecStatus(); oneway void setCodecConfigPreference(in BluetoothCodecConfig codecConfig); } diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl index f35b13d44474..c51945e4e27d 100644 --- a/core/java/android/content/pm/IPackageManager.aidl +++ b/core/java/android/content/pm/IPackageManager.aidl @@ -563,6 +563,7 @@ interface IPackageManager { void addOnPermissionsChangeListener(in IOnPermissionsChangeListener listener); void removeOnPermissionsChangeListener(in IOnPermissionsChangeListener listener); void grantDefaultPermissionsToEnabledCarrierApps(in String[] packageNames, int userId); + void grantDefaultPermissionsToEnabledImsServices(in String[] packageNames, int userId); boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId); diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index 042481f1727e..82e3093728bc 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -46,6 +46,7 @@ import android.telephony.SubscriptionManager; import android.util.ArrayMap; import android.util.Log; import android.util.SparseArray; +import android.util.SparseIntArray; import com.android.internal.telephony.ITelephony; import com.android.internal.telephony.PhoneConstants; @@ -1219,36 +1220,27 @@ public class ConnectivityManager { private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) { if (networkType == TYPE_MOBILE) { - int cap = -1; - if ("enableMMS".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_MMS; - } else if ("enableSUPL".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_SUPL; - } else if ("enableDUN".equals(feature) || "enableDUNAlways".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_DUN; - } else if ("enableHIPRI".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_INTERNET; - } else if ("enableFOTA".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_FOTA; - } else if ("enableIMS".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_IMS; - } else if ("enableCBS".equals(feature)) { - cap = NetworkCapabilities.NET_CAPABILITY_CBS; - } else { - return null; - } - NetworkCapabilities netCap = new NetworkCapabilities(); - netCap.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addCapability(cap); - netCap.maybeMarkCapabilitiesRestricted(); - return netCap; - } else if (networkType == TYPE_WIFI) { - if ("p2p".equals(feature)) { - NetworkCapabilities netCap = new NetworkCapabilities(); - netCap.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); - netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P); - netCap.maybeMarkCapabilitiesRestricted(); - return netCap; + switch (feature) { + case "enableCBS": + return networkCapabilitiesForType(TYPE_MOBILE_CBS); + case "enableDUN": + case "enableDUNAlways": + return networkCapabilitiesForType(TYPE_MOBILE_DUN); + case "enableFOTA": + return networkCapabilitiesForType(TYPE_MOBILE_FOTA); + case "enableHIPRI": + return networkCapabilitiesForType(TYPE_MOBILE_HIPRI); + case "enableIMS": + return networkCapabilitiesForType(TYPE_MOBILE_IMS); + case "enableMMS": + return networkCapabilitiesForType(TYPE_MOBILE_MMS); + case "enableSUPL": + return networkCapabilitiesForType(TYPE_MOBILE_SUPL); + default: + return null; } + } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) { + return networkCapabilitiesForType(TYPE_WIFI_P2P); } return null; } @@ -1456,6 +1448,59 @@ public class ConnectivityManager { return true; } + private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray(); + static { + sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR); + sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI); + sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI); + sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH); + sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET); + } + + private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray(); + static { + sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS); + sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN); + sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA); + sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS); + sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS); + sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL); + sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P); + } + + /** + * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities + * instance suitable for registering a request or callback. Throws an + * IllegalArgumentException if no mapping from the legacy type to + * NetworkCapabilities is known. + * + * @hide + */ + public static NetworkCapabilities networkCapabilitiesForType(int type) { + final NetworkCapabilities nc = new NetworkCapabilities(); + + // Map from type to transports. + final int NOT_FOUND = -1; + final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND); + if (transport == NOT_FOUND) { + throw new IllegalArgumentException("unknown legacy type: " + type); + } + nc.addTransportType(transport); + + // Map from type to capabilities. + nc.addCapability(sLegacyTypeToCapability.get( + type, NetworkCapabilities.NET_CAPABILITY_INTERNET)); + nc.maybeMarkCapabilitiesRestricted(); + return nc; + } + /** @hide */ public static class PacketKeepaliveCallback { /** The requested keepalive was successfully started. */ diff --git a/core/java/android/net/NetworkRecommendationProvider.java b/core/java/android/net/NetworkRecommendationProvider.java index 16ae867d81e7..5739c79b8f96 100644 --- a/core/java/android/net/NetworkRecommendationProvider.java +++ b/core/java/android/net/NetworkRecommendationProvider.java @@ -5,8 +5,6 @@ import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.IRemoteCallback; -import android.os.Looper; -import android.os.Message; import android.os.RemoteException; import android.util.Log; @@ -27,8 +25,6 @@ public abstract class NetworkRecommendationProvider { "android.net.extra.RECOMMENDATION_RESULT"; /** The key into the callback Bundle where the sequence will be found. */ public static final String EXTRA_SEQUENCE = "android.net.extra.SEQUENCE"; - private static final String EXTRA_RECOMMENDATION_REQUEST = - "android.net.extra.RECOMMENDATION_REQUEST"; private final IBinder mService; /** @@ -39,7 +35,7 @@ public abstract class NetworkRecommendationProvider { if (handler == null) { throw new IllegalArgumentException("The provided handler cannot be null."); } - mService = new ServiceWrapper(new ServiceHandler(handler.getLooper())); + mService = new ServiceWrapper(handler); } /** @@ -125,42 +121,10 @@ public abstract class NetworkRecommendationProvider { } } - private final class ServiceHandler extends Handler { - static final int MSG_GET_RECOMMENDATION = 1; - static final int MSG_REQUEST_SCORES = 2; - - ServiceHandler(Looper looper) { - super(looper, null /*callback*/, true /*async*/); - } - - @Override - public void handleMessage(Message msg) { - final int what = msg.what; - switch (what) { - case MSG_GET_RECOMMENDATION: - final IRemoteCallback callback = (IRemoteCallback) msg.obj; - final int seq = msg.arg1; - final RecommendationRequest request = - msg.getData().getParcelable(EXTRA_RECOMMENDATION_REQUEST); - final ResultCallback resultCallback = new ResultCallback(callback, seq); - onRequestRecommendation(request, resultCallback); - break; - - case MSG_REQUEST_SCORES: - final NetworkKey[] networks = (NetworkKey[]) msg.obj; - onRequestScores(networks); - break; - - default: - throw new IllegalArgumentException("Unknown message: " + what); - } - } - } - /** - * A wrapper around INetworkRecommendationProvider that sends calls to the internal Handler. + * A wrapper around INetworkRecommendationProvider that dispatches to the provided Handler. */ - private static final class ServiceWrapper extends INetworkRecommendationProvider.Stub { + private final class ServiceWrapper extends INetworkRecommendationProvider.Stub { private final Handler mHandler; ServiceWrapper(Handler handler) { @@ -168,20 +132,26 @@ public abstract class NetworkRecommendationProvider { } @Override - public void requestRecommendation(RecommendationRequest request, IRemoteCallback callback, - int sequence) throws RemoteException { - final Message msg = mHandler.obtainMessage( - ServiceHandler.MSG_GET_RECOMMENDATION, sequence, 0 /*arg2*/, callback); - final Bundle data = new Bundle(); - data.putParcelable(EXTRA_RECOMMENDATION_REQUEST, request); - msg.setData(data); - msg.sendToTarget(); + public void requestRecommendation(final RecommendationRequest request, + final IRemoteCallback callback, final int sequence) throws RemoteException { + mHandler.post(new Runnable() { + @Override + public void run() { + ResultCallback resultCallback = new ResultCallback(callback, sequence); + onRequestRecommendation(request, resultCallback); + } + }); } @Override - public void requestScores(NetworkKey[] networks) throws RemoteException { + public void requestScores(final NetworkKey[] networks) throws RemoteException { if (networks != null && networks.length > 0) { - mHandler.obtainMessage(ServiceHandler.MSG_REQUEST_SCORES, networks).sendToTarget(); + mHandler.post(new Runnable() { + @Override + public void run() { + onRequestScores(networks); + } + }); } } } diff --git a/core/java/android/net/NetworkRequest.java b/core/java/android/net/NetworkRequest.java index ae724709c6c6..cb780090c46a 100644 --- a/core/java/android/net/NetworkRequest.java +++ b/core/java/android/net/NetworkRequest.java @@ -178,6 +178,20 @@ public class NetworkRequest implements Parcelable { } /** + * Set the {@code NetworkCapabilities} for this builder instance, + * overriding any capabilities that had been previously set. + * + * @param nc The superseding {@code NetworkCapabilities} instance. + * @return The builder to facilitate chaining. + * @hide + */ + public Builder setCapabilities(NetworkCapabilities nc) { + mNetworkCapabilities.clearAll(); + mNetworkCapabilities.combineCapabilities(nc); + return this; + } + + /** * Completely clears all the {@code NetworkCapabilities} from this builder instance, * removing even the capabilities that are set by default when the object is constructed. * diff --git a/core/java/android/os/Seccomp.java b/core/java/android/os/Seccomp.java new file mode 100644 index 000000000000..f14e93fe9403 --- /dev/null +++ b/core/java/android/os/Seccomp.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2017 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.os; + +/** + * @hide + */ +public final class Seccomp { + public static final native void setPolicy(); +} diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java index ef5231cb6ff3..b55dccf39094 100644 --- a/core/java/com/android/internal/os/ZygoteInit.java +++ b/core/java/com/android/internal/os/ZygoteInit.java @@ -29,6 +29,7 @@ import android.opengl.EGL14; import android.os.IInstalld; import android.os.Process; import android.os.RemoteException; +import android.os.Seccomp; import android.os.ServiceManager; import android.os.ServiceSpecificException; import android.os.SystemClock; @@ -692,6 +693,9 @@ public class ZygoteInit { // Zygote process unmounts root storage spaces. Zygote.nativeUnmountStorageOnInit(); + // Set seccomp policy + Seccomp.setPolicy(); + ZygoteHooks.stopZygoteNoThreadCreation(); if (startSystemServer) { diff --git a/core/jni/Android.mk b/core/jni/Android.mk index 24c8bfb43c6e..e940732cec8a 100644 --- a/core/jni/Android.mk +++ b/core/jni/Android.mk @@ -84,6 +84,7 @@ LOCAL_SRC_FILES:= \ android_os_MessageQueue.cpp \ android_os_Parcel.cpp \ android_os_SELinux.cpp \ + android_os_seccomp.cpp \ android_os_SystemClock.cpp \ android_os_SystemProperties.cpp \ android_os_Trace.cpp \ @@ -215,6 +216,9 @@ LOCAL_C_INCLUDES += \ external/freetype/include # TODO: clean up Minikin so it doesn't need the freetype include +LOCAL_STATIC_LIBRARIES := \ + libseccomp_policy \ + LOCAL_SHARED_LIBRARIES := \ libmemtrack \ libandroidfw \ diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp index 07392c4055d3..3580812c68f9 100644 --- a/core/jni/AndroidRuntime.cpp +++ b/core/jni/AndroidRuntime.cpp @@ -163,6 +163,7 @@ extern int register_android_os_HwRemoteBinder(JNIEnv *env); extern int register_android_os_MessageQueue(JNIEnv* env); extern int register_android_os_Parcel(JNIEnv* env); extern int register_android_os_SELinux(JNIEnv* env); +extern int register_android_os_seccomp(JNIEnv* env); extern int register_android_os_SystemProperties(JNIEnv *env); extern int register_android_os_SystemClock(JNIEnv* env); extern int register_android_os_Trace(JNIEnv* env); @@ -1366,6 +1367,7 @@ static const RegJNIRec gRegJNI[] = { REG_JNI(register_android_os_FileObserver), REG_JNI(register_android_os_MessageQueue), REG_JNI(register_android_os_SELinux), + REG_JNI(register_android_os_seccomp), REG_JNI(register_android_os_Trace), REG_JNI(register_android_os_UEventObserver), REG_JNI(register_android_net_LocalSocketImpl), diff --git a/core/jni/android_os_HwBinder.cpp b/core/jni/android_os_HwBinder.cpp index e65390047c55..d35ffbba3a1e 100644 --- a/core/jni/android_os_HwBinder.cpp +++ b/core/jni/android_os_HwBinder.cpp @@ -302,6 +302,14 @@ static jobject JHwBinder_native_getService( return NULL; } + auto manager = hardware::defaultServiceManager(); + + if (manager == nullptr) { + LOG(ERROR) << "Could not get hwservicemanager."; + signalExceptionForError(env, UNKNOWN_ERROR, true /* canThrowRemoteException */); + return NULL; + } + const char *ifaceName = env->GetStringUTFChars(ifaceNameObj, NULL); if (ifaceName == NULL) { return NULL; // XXX exception already pending? @@ -312,32 +320,26 @@ static jobject JHwBinder_native_getService( return NULL; // XXX exception already pending? } - LOG(INFO) << "looking for service '" - << serviceName - << "'"; - - auto manager = hardware::defaultServiceManager(); - - if (manager == nullptr) { - LOG(ERROR) << "Could not get hwservicemanager."; - signalExceptionForError(env, UNKNOWN_ERROR, true /* canThrowRemoteException */); - return NULL; - } + LOG(INFO) << "Looking for service " + << ifaceName + << "/" + << serviceName; Return<sp<hidl::base::V1_0::IBase>> ret = manager->get(ifaceName, serviceName); + env->ReleaseStringUTFChars(ifaceNameObj, ifaceName); + ifaceName = NULL; + env->ReleaseStringUTFChars(serviceNameObj, serviceName); + serviceName = NULL; + if (!ret.isOk()) { signalExceptionForError(env, UNKNOWN_ERROR, true /* canThrowRemoteException */); + return NULL; } sp<hardware::IBinder> service = hardware::toBinder< hidl::base::V1_0::IBase, hidl::base::V1_0::BpHwBase>(ret); - env->ReleaseStringUTFChars(ifaceNameObj, ifaceName); - ifaceName = NULL; - env->ReleaseStringUTFChars(serviceNameObj, serviceName); - serviceName = NULL; - if (service == NULL) { signalExceptionForError(env, NAME_NOT_FOUND); return NULL; diff --git a/core/jni/android_os_seccomp.cpp b/core/jni/android_os_seccomp.cpp new file mode 100644 index 000000000000..fc35a7469753 --- /dev/null +++ b/core/jni/android_os_seccomp.cpp @@ -0,0 +1,235 @@ +/* + * Copyright (C) 2017 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. + */ + +#include "JNIHelp.h" +#include "core_jni_helpers.h" +#include "JniConstants.h" +#include "utils/Log.h" +#include "utils/misc.h" + +#if defined __arm__ || defined __aarch64__ + +#include <vector> + +#include <sys/prctl.h> + +#include <linux/unistd.h> +#include <linux/audit.h> +#include <linux/filter.h> +#include <linux/seccomp.h> + +#include "seccomp_policy.h" + +#define syscall_nr (offsetof(struct seccomp_data, nr)) +#define arch_nr (offsetof(struct seccomp_data, arch)) + +typedef std::vector<sock_filter> filter; + +// We want to keep the below inline functions for debugging and future +// development even though they are not all sed currently. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" + +static inline void Kill(filter& f) { + f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_KILL)); +} + +static inline void Trap(filter& f) { + f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRAP)); +} + +static inline void Error(filter& f, __u16 retcode) { + f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ERRNO + retcode)); +} + +inline static void Trace(filter& f) { + f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_TRACE)); +} + +inline static void Allow(filter& f) { + f.push_back(BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW)); +} + +#pragma clang diagnostic pop + +inline static void AllowSyscall(filter& f, __u32 num) { + f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, num, 0, 1)); + Allow(f); +} + +inline static void ExamineSyscall(filter& f) { + f.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_nr)); +} + +inline static int SetValidateArchitectureJumpTarget(size_t offset, filter& f) { + size_t jump_length = f.size() - offset - 1; + auto u8_jump_length = (__u8) jump_length; + if (u8_jump_length != jump_length) { + ALOGE("Can't set jump greater than 255 - actual jump is %zu", + jump_length); + return -1; + } + f[offset] = BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_ARM, u8_jump_length, 0); + return 0; +} + +inline static size_t ValidateArchitectureAndJumpIfNeeded(filter& f) { + f.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS, arch_nr)); + + f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_AARCH64, 2, 0)); + f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, AUDIT_ARCH_ARM, 1, 0)); + Trap(f); + return f.size() - 2; +} + +static bool install_filter(filter const& f) { + struct sock_fprog prog = { + (unsigned short) f.size(), + (struct sock_filter*) &f[0], + }; + + if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) < 0) { + ALOGE("SECCOMP: Could not set seccomp filter of size %zu: %s", f.size(), strerror(errno)); + return false; + } + + ALOGI("SECCOMP: Global filter of size %zu installed", f.size()); + return true; +} + +bool set_seccomp_filter() { + filter f; + + // Note that for mixed 64/32 bit architectures, ValidateArchitecture inserts a + // jump that must be changed to point to the start of the 32-bit policy + // 32 bit syscalls will not hit the policy between here and the call to SetJump + auto offset_to_32bit_filter = + ValidateArchitectureAndJumpIfNeeded(f); + + // 64-bit filter + ExamineSyscall(f); + + // Syscalls needed to boot Android + AllowSyscall(f, 41); // __NR_pivot_root + AllowSyscall(f, 31); // __NR_ioprio_get + AllowSyscall(f, 30); // __NR_ioprio_set + AllowSyscall(f, 178); // __NR_gettid + AllowSyscall(f, 98); // __NR_futex + AllowSyscall(f, 220); // __NR_clone + AllowSyscall(f, 139); // __NR_rt_sigreturn + AllowSyscall(f, 240); // __NR_rt_tgsigqueueinfo + AllowSyscall(f, 128); // __NR_restart_syscall + AllowSyscall(f, 278); // __NR_getrandom + + // Needed for performance tools + AllowSyscall(f, 241); // __NR_perf_event_open + + // Needed for strace + AllowSyscall(f, 130); // __NR_tkill + + // Needed for kernel to restart syscalls + AllowSyscall(f, 128); // __NR_restart_syscall + + // arm64-only filter - autogenerated from bionic syscall usage + for (size_t i = 0; i < arm64_filter_size; ++i) + f.push_back(arm64_filter[i]); + + if (SetValidateArchitectureJumpTarget(offset_to_32bit_filter, f) != 0) + return -1; + + // 32-bit filter + ExamineSyscall(f); + + // Syscalls needed to boot android + AllowSyscall(f, 120); // __NR_clone + AllowSyscall(f, 240); // __NR_futex + AllowSyscall(f, 119); // __NR_sigreturn + AllowSyscall(f, 173); // __NR_rt_sigreturn + AllowSyscall(f, 363); // __NR_rt_tgsigqueueinfo + AllowSyscall(f, 224); // __NR_gettid + + // Syscalls needed to run Chrome + AllowSyscall(f, 383); // __NR_seccomp - needed to start Chrome + AllowSyscall(f, 384); // __NR_getrandom - needed to start Chrome + + // Syscalls needed to run GFXBenchmark + AllowSyscall(f, 190); // __NR_vfork + + // Needed for strace + AllowSyscall(f, 238); // __NR_tkill + + // Needed for kernel to restart syscalls + AllowSyscall(f, 0); // __NR_restart_syscall + + // Needed for debugging 32-bit Chrome + AllowSyscall(f, 42); // __NR_pipe + + // b/34732712 + AllowSyscall(f, 364); // __NR_perf_event_open + + // b/34651972 + AllowSyscall(f, 33); // __NR_access + AllowSyscall(f, 195); // __NR_stat64 + + // b/34813887 + AllowSyscall(f, 5); // __NR_open + AllowSyscall(f, 141); // __NR_getdents + AllowSyscall(f, 217); // __NR_getdents64 + + // b/34719286 + AllowSyscall(f, 351); // __NR_eventfd + + // b/34817266 + AllowSyscall(f, 252); // __NR_epoll_wait + + // Needed by sanitizers (b/34606909) + // 5 (__NR_open) and 195 (__NR_stat64) are also required, but they are + // already allowed. + AllowSyscall(f, 85); // __NR_readlink + + // arm32 filter - autogenerated from bionic syscall usage + for (size_t i = 0; i < arm_filter_size; ++i) + f.push_back(arm_filter[i]); + + return install_filter(f); +} + +static void Seccomp_setPolicy(JNIEnv* /*env*/) { + if (!set_seccomp_filter()) { + ALOGE("Failed to set seccomp policy - killing"); + exit(1); + } +} + +#else // #if defined __arm__ || defined __aarch64__ + +static void Seccomp_setPolicy(JNIEnv* /*env*/) { +} + +#endif + +static const JNINativeMethod method_table[] = { + NATIVE_METHOD(Seccomp, setPolicy, "()V"), +}; + +namespace android { + +int register_android_os_seccomp(JNIEnv* env) { + return android::RegisterMethodsOrDie(env, "android/os/Seccomp", + method_table, NELEM(method_table)); +} + +} diff --git a/core/jni/com_google_android_gles_jni_GLImpl.cpp b/core/jni/com_google_android_gles_jni_GLImpl.cpp index ad7d744cb693..3e74d1c855b3 100644 --- a/core/jni/com_google_android_gles_jni_GLImpl.cpp +++ b/core/jni/com_google_android_gles_jni_GLImpl.cpp @@ -132,6 +132,7 @@ getPointer(JNIEnv *_env, jobject buffer, jarray *array, jint *remaining, jint *o pointer = _env->CallStaticLongMethod(nioAccessClass, getBasePointerID, buffer); if (pointer != 0L) { + *offset = 0; *array = NULL; return reinterpret_cast<void *>(pointer); } @@ -139,6 +140,7 @@ getPointer(JNIEnv *_env, jobject buffer, jarray *array, jint *remaining, jint *o *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass, getBaseArrayID, buffer); if (*array == NULL) { + *offset = 0; return (void*) NULL; } *offset = _env->CallStaticIntMethod(nioAccessClass, diff --git a/core/res/res/values-mcc704-mnc01/config.xml b/core/res/res/values-mcc704-mnc01/config.xml new file mode 100644 index 000000000000..10b647044c73 --- /dev/null +++ b/core/res/res/values-mcc704-mnc01/config.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +/* +** Copyright 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 my 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. +*/ +--> + +<resources> + <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD --> + <string-array name="config_twoDigitNumberPattern"> + <item>"*1"</item> + <item>"*5"</item> + <item>"*9"</item> + </string-array> +</resources> diff --git a/core/res/res/values-mcc708-mnc001/config.xml b/core/res/res/values-mcc708-mnc001/config.xml new file mode 100755 index 000000000000..7b7c48d46b14 --- /dev/null +++ b/core/res/res/values-mcc708-mnc001/config.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +/* +** Copyright 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 my 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. +*/ +--> + +<!-- These resources are around just to allow their values to be customized + for different hardware and product builds. --> +<resources> + <string-array translatable="false" name="config_twoDigitNumberPattern"> + <item>"*1"</item> + <item>"*5"</item> + </string-array> +</resources> diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index fbde9c0324f4..4ff78ead9e5f 100644 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -2272,7 +2272,7 @@ <string name="config_ims_package"/> <!-- Flag specifying whether or not IMS will use the dynamic ImsResolver --> - <bool name="config_dynamic_bind_ims">true</bool> + <bool name="config_dynamic_bind_ims">false</bool> <bool name="config_networkSamplingWakesDevice">true</bool> diff --git a/native/android/Android.mk b/native/android/Android.mk index da4e4bac6dbc..1f69df1ae21d 100644 --- a/native/android/Android.mk +++ b/native/android/Android.mk @@ -1,6 +1,8 @@ BASE_PATH := $(call my-dir) LOCAL_PATH:= $(call my-dir) +common_cflags := -Wall -Werror -Wunused -Wunreachable-code + include $(CLEAR_VARS) # our source files @@ -42,6 +44,23 @@ LOCAL_C_INCLUDES += \ LOCAL_MODULE := libandroid -LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code +LOCAL_CFLAGS += $(common_cflags) + +include $(BUILD_SHARED_LIBRARY) + +# Network library. +include $(CLEAR_VARS) +LOCAL_MODULE := libandroid_net +LOCAL_CFLAGS := $(common_cflags) +LOCAL_SRC_FILES:= \ + net.c \ + +LOCAL_SHARED_LIBRARIES := \ + libnetd_client \ + +LOCAL_C_INCLUDES += \ + frameworks/base/native/include \ + bionic/libc/dns/include \ + system/netd/include \ include $(BUILD_SHARED_LIBRARY) diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto index 735afce21cdb..d3ed525c1595 100644 --- a/proto/src/metrics_constants.proto +++ b/proto/src/metrics_constants.proto @@ -2218,6 +2218,30 @@ message MetricsEvent { // CATEGORY: QUICK_SETTINGS QS_NFC = 497; + // ---- End N-MR2 Constants, all N-MR1 constants go above this line ---- + + // ACTION: A captive portal was detected during network validation + // CATEGORY: NOTIFICATION + // OS: N-MR2 + NOTIFICATION_NETWORK_SIGN_IN = 740; + + // ACTION: An unvalidated network without Internet was selected by the user + // CATEGORY: NOTIFICATION + // OS: N-MR2 + NOTIFICATION_NETWORK_NO_INTERNET = 741; + + // ACTION: A validated network failed revalidation and lost Internet access + // CATEGORY: NOTIFICATION + // OS: N-MR2 + NOTIFICATION_NETWORK_LOST_INTERNET = 742; + + // ACTION: The system default network switched to a different network + // CATEGORY: NOTIFICATION + // OS: N-MR2 + NOTIFICATION_NETWORK_SWITCH = 743; + + // ---- End O Constants, all O constants go above this line ---- + // Add new aosp constants above this line. // END OF AOSP CONSTANTS } diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java index 803c2db83d13..dfca02ecc9d9 100644 --- a/services/core/java/com/android/server/ConnectivityService.java +++ b/services/core/java/com/android/server/ConnectivityService.java @@ -78,7 +78,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.net.util.MultinetworkPolicyTracker; import android.os.Binder; import android.os.Build; import android.os.Bundle; @@ -499,7 +499,7 @@ public class ConnectivityService extends IConnectivityManager.Stub private final IpConnectivityLog mMetricsLog; @VisibleForTesting - final AvoidBadWifiTracker mAvoidBadWifiTracker; + final MultinetworkPolicyTracker mMultinetworkPolicyTracker; /** * Implements support for the legacy "one network per network type" model. @@ -849,9 +849,9 @@ public class ConnectivityService extends IConnectivityManager.Stub LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS); mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit); - mAvoidBadWifiTracker = createAvoidBadWifiTracker( + mMultinetworkPolicyTracker = createMultinetworkPolicyTracker( mContext, mHandler, () -> rematchForAvoidBadWifiUpdate()); - mAvoidBadWifiTracker.start(); + mMultinetworkPolicyTracker.start(); } private NetworkRequest createInternetRequestForTransport( @@ -2793,7 +2793,7 @@ public class ConnectivityService extends IConnectivityManager.Stub } public boolean avoidBadWifi() { - return mAvoidBadWifiTracker.currentValue(); + return mMultinetworkPolicyTracker.getAvoidBadWifi(); } private void rematchForAvoidBadWifiUpdate() { @@ -2806,9 +2806,9 @@ public class ConnectivityService extends IConnectivityManager.Stub } // TODO: Evaluate whether this is of interest to other consumers of - // AvoidBadWifiTracker and worth moving out of here. + // MultinetworkPolicyTracker and worth moving out of here. private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) { - final boolean configRestrict = mAvoidBadWifiTracker.configRestrictsAvoidBadWifi(); + final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi(); if (!configRestrict) { pw.println("Bad Wi-Fi avoidance: unrestricted"); return; @@ -2818,7 +2818,7 @@ public class ConnectivityService extends IConnectivityManager.Stub pw.increaseIndent(); pw.println("Config restrict: " + configRestrict); - final String value = mAvoidBadWifiTracker.getSettingsValue(); + final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting(); String description; // Can't use a switch statement because strings are legal case labels, but null is not. if ("0".equals(value)) { @@ -2886,7 +2886,7 @@ public class ConnectivityService extends IConnectivityManager.Stub if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc); if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && - mAvoidBadWifiTracker.shouldNotifyWifiUnvalidated()) { + mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) { showValidationNotification(nai, NotificationType.LOST_INTERNET); } } @@ -5534,8 +5534,8 @@ public class ConnectivityService extends IConnectivityManager.Stub } @VisibleForTesting - AvoidBadWifiTracker createAvoidBadWifiTracker(Context c, Handler h, Runnable r) { - return new AvoidBadWifiTracker(c, h, r); + MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) { + return new MultinetworkPolicyTracker(c, h, r); } @VisibleForTesting diff --git a/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java b/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java index 08a333230793..017c5fb4d4ec 100644 --- a/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java +++ b/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java @@ -66,9 +66,9 @@ public class UpstreamNetworkMonitor { public static final int EVENT_ON_LINKPROPERTIES = 3; public static final int EVENT_ON_LOST = 4; - private static final int LISTEN_ALL = 1; - private static final int TRACK_DEFAULT = 2; - private static final int MOBILE_REQUEST = 3; + private static final int CALLBACK_LISTEN_ALL = 1; + private static final int CALLBACK_TRACK_DEFAULT = 2; + private static final int CALLBACK_MOBILE_REQUEST = 3; private final Context mContext; private final StateMachine mTarget; @@ -98,10 +98,10 @@ public class UpstreamNetworkMonitor { final NetworkRequest listenAllRequest = new NetworkRequest.Builder() .clearCapabilities().build(); - mListenAllCallback = new UpstreamNetworkCallback(LISTEN_ALL); + mListenAllCallback = new UpstreamNetworkCallback(CALLBACK_LISTEN_ALL); cm().registerNetworkCallback(listenAllRequest, mListenAllCallback); - mDefaultNetworkCallback = new UpstreamNetworkCallback(TRACK_DEFAULT); + mDefaultNetworkCallback = new UpstreamNetworkCallback(CALLBACK_TRACK_DEFAULT); cm().registerDefaultNetworkCallback(mDefaultNetworkCallback); } @@ -136,30 +136,25 @@ public class UpstreamNetworkMonitor { return; } - final NetworkRequest.Builder builder = new NetworkRequest.Builder() - .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR); - if (mDunRequired) { - builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) - .addCapability(NetworkCapabilities.NET_CAPABILITY_DUN); - } else { - builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); - } - final NetworkRequest mobileUpstreamRequest = builder.build(); + // The following use of the legacy type system cannot be removed until + // after upstream selection no longer finds networks by legacy type. + // See also http://b/34364553 . + final int legacyType = mDunRequired ? TYPE_MOBILE_DUN : TYPE_MOBILE_HIPRI; + + final NetworkRequest mobileUpstreamRequest = new NetworkRequest.Builder() + .setCapabilities(ConnectivityManager.networkCapabilitiesForType(legacyType)) + .build(); // The existing default network and DUN callbacks will be notified. // Therefore, to avoid duplicate notifications, we only register a no-op. - mMobileNetworkCallback = new UpstreamNetworkCallback(MOBILE_REQUEST); + mMobileNetworkCallback = new UpstreamNetworkCallback(CALLBACK_MOBILE_REQUEST); // TODO: Change the timeout from 0 (no onUnavailable callback) to some // moderate callback timeout. This might be useful for updating some UI. // Additionally, we log a message to aid in any subsequent debugging. Log.d(TAG, "requesting mobile upstream network: " + mobileUpstreamRequest); - // The following use of the legacy type system cannot be removed until - // after upstream selection no longer finds networks by legacy type. - // See also b/34364553. - final int apnType = mDunRequired ? TYPE_MOBILE_DUN : TYPE_MOBILE_HIPRI; - cm().requestNetwork(mobileUpstreamRequest, mMobileNetworkCallback, 0, apnType); + cm().requestNetwork(mobileUpstreamRequest, mMobileNetworkCallback, 0, legacyType); } public void releaseMobileNetworkRequest() { @@ -184,17 +179,18 @@ public class UpstreamNetworkMonitor { // Always request whatever extra information we can, in case this // was already up when start() was called, in which case we would // not have been notified of any information that had not changed. - final NetworkCallback cb = - (callbackType == TRACK_DEFAULT) ? mDefaultNetworkCallback : - (callbackType == MOBILE_REQUEST) ? mMobileNetworkCallback : null; - if (cb != null) { - final ConnectivityManager cm = cm(); - cm.requestNetworkCapabilities(mDefaultNetworkCallback); - cm.requestLinkProperties(mDefaultNetworkCallback); - } - - if (callbackType == TRACK_DEFAULT) { - mCurrentDefault = network; + switch (callbackType) { + case CALLBACK_LISTEN_ALL: + break; + case CALLBACK_TRACK_DEFAULT: + cm().requestNetworkCapabilities(mDefaultNetworkCallback); + cm().requestLinkProperties(mDefaultNetworkCallback); + mCurrentDefault = network; + break; + case CALLBACK_MOBILE_REQUEST: + cm().requestNetworkCapabilities(mMobileNetworkCallback); + cm().requestLinkProperties(mMobileNetworkCallback); + break; } // Requesting updates for mListenAllCallback is not currently possible @@ -262,7 +258,7 @@ public class UpstreamNetworkMonitor { } private void handleLost(int callbackType, Network network) { - if (callbackType == TRACK_DEFAULT) { + if (callbackType == CALLBACK_TRACK_DEFAULT) { mCurrentDefault = null; // Receiving onLost() for a default network does not necessarily // mean the network is gone. We wait for a separate notification diff --git a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java index a6f9243887df..a0fabdfb138e 100644 --- a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java +++ b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java @@ -777,6 +777,23 @@ final class DefaultPermissionGrantPolicy { } } + public void grantDefaultPermissionsToEnabledImsServicesLPr(String[] packageNames, int userId) { + Log.i(TAG, "Granting permissions to enabled ImsServices for user:" + userId); + if (packageNames == null) { + return; + } + for (String packageName : packageNames) { + PackageParser.Package imsServicePackage = getSystemPackageLPr(packageName); + if (imsServicePackage != null + && doesPackageSupportRuntimePermissions(imsServicePackage)) { + grantRuntimePermissionsLPw(imsServicePackage, PHONE_PERMISSIONS, userId); + grantRuntimePermissionsLPw(imsServicePackage, MICROPHONE_PERMISSIONS, userId); + grantRuntimePermissionsLPw(imsServicePackage, LOCATION_PERMISSIONS, userId); + grantRuntimePermissionsLPw(imsServicePackage, CAMERA_PERMISSIONS, userId); + } + } + } + public void grantDefaultPermissionsToDefaultBrowserLPr(String packageName, int userId) { Log.i(TAG, "Granting permissions to default browser for user:" + userId); if (packageName == null) { diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java index 07dbb17b9451..ca0f85d51f3e 100644 --- a/services/core/java/com/android/server/pm/PackageManagerService.java +++ b/services/core/java/com/android/server/pm/PackageManagerService.java @@ -21143,6 +21143,20 @@ Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); } } + @Override + public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { + enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); + synchronized (mPackages) { + final long identity = Binder.clearCallingIdentity(); + try { + mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( + packageNames, userId); + } finally { + Binder.restoreCallingIdentity(identity); + } + } + } + private static void enforceSystemOrPhoneCaller(String tag) { int callingUid = Binder.getCallingUid(); if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { diff --git a/services/net/java/android/net/ip/IpManager.java b/services/net/java/android/net/ip/IpManager.java index abdf6831b06c..76b1c90642ec 100644 --- a/services/net/java/android/net/ip/IpManager.java +++ b/services/net/java/android/net/ip/IpManager.java @@ -33,7 +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.net.util.MultinetworkPolicyTracker; import android.os.INetworkManagementService; import android.os.Message; import android.os.RemoteException; @@ -398,7 +398,7 @@ public class IpManager extends StateMachine { private final NetlinkTracker mNetlinkTracker; private final WakeupMessage mProvisioningTimeoutAlarm; private final WakeupMessage mDhcpActionTimeoutAlarm; - private final AvoidBadWifiTracker mAvoidBadWifiTracker; + private final MultinetworkPolicyTracker mMultinetworkPolicyTracker; private final LocalLog mLocalLog; private final LocalLog mConnectivityPacketLog; private final MessageHandlingLogger mMsgStateLogger; @@ -492,7 +492,7 @@ public class IpManager extends StateMachine { mLinkProperties = new LinkProperties(); mLinkProperties.setInterfaceName(mInterfaceName); - mAvoidBadWifiTracker = new AvoidBadWifiTracker(mContext, getHandler(), + mMultinetworkPolicyTracker = new MultinetworkPolicyTracker(mContext, getHandler(), () -> { mLocalLog.log("OBSERVED AvoidBadWifi changed"); }); mProvisioningTimeoutAlarm = new WakeupMessage(mContext, getHandler(), @@ -527,7 +527,7 @@ public class IpManager extends StateMachine { Log.e(mTag, "Couldn't register NetlinkTracker: " + e.toString()); } - mAvoidBadWifiTracker.start(); + mMultinetworkPolicyTracker.start(); } @Override @@ -538,7 +538,7 @@ public class IpManager extends StateMachine { // Shut down this IpManager instance altogether. public void shutdown() { stop(); - mAvoidBadWifiTracker.shutdown(); + mMultinetworkPolicyTracker.shutdown(); quit(); } @@ -767,7 +767,7 @@ public class IpManager extends StateMachine { // 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(); + final boolean ignoreIPv6ProvisioningLoss = !mMultinetworkPolicyTracker.getAvoidBadWifi(); // Additionally: // @@ -1045,7 +1045,7 @@ public class IpManager extends StateMachine { mCallback.onReachabilityLost(logMsg); } }, - mAvoidBadWifiTracker); + mMultinetworkPolicyTracker); } catch (IllegalArgumentException iae) { // Failed to start IpReachabilityMonitor. Log it and call // onProvisioningFailure() immediately. diff --git a/services/net/java/android/net/ip/IpReachabilityMonitor.java b/services/net/java/android/net/ip/IpReachabilityMonitor.java index a883e28e96c6..20eac622d37f 100644 --- a/services/net/java/android/net/ip/IpReachabilityMonitor.java +++ b/services/net/java/android/net/ip/IpReachabilityMonitor.java @@ -34,7 +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.net.util.MultinetworkPolicyTracker; import android.os.PowerManager; import android.os.SystemClock; import android.system.ErrnoException; @@ -151,7 +151,7 @@ public class IpReachabilityMonitor { private final String mInterfaceName; private final int mInterfaceIndex; private final Callback mCallback; - private final AvoidBadWifiTracker mAvoidBadWifiTracker; + private final MultinetworkPolicyTracker mMultinetworkPolicyTracker; private final NetlinkSocketObserver mNetlinkSocketObserver; private final Thread mObserverThread; private final IpConnectivityLog mMetricsLog = new IpConnectivityLog(); @@ -226,7 +226,7 @@ public class IpReachabilityMonitor { } public IpReachabilityMonitor(Context context, String ifName, Callback callback, - AvoidBadWifiTracker tracker) throws IllegalArgumentException { + MultinetworkPolicyTracker tracker) throws IllegalArgumentException { mInterfaceName = ifName; int ifIndex = -1; try { @@ -238,7 +238,7 @@ public class IpReachabilityMonitor { mWakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, TAG + "." + mInterfaceName); mCallback = callback; - mAvoidBadWifiTracker = tracker; + mMultinetworkPolicyTracker = tracker; mNetlinkSocketObserver = new NetlinkSocketObserver(); mObserverThread = new Thread(mNetlinkSocketObserver); mObserverThread.start(); @@ -379,7 +379,7 @@ public class IpReachabilityMonitor { } private boolean avoidingBadLinks() { - return (mAvoidBadWifiTracker != null) ? mAvoidBadWifiTracker.currentValue() : true; + return (mMultinetworkPolicyTracker == null) || mMultinetworkPolicyTracker.getAvoidBadWifi(); } public void probeAll() { diff --git a/services/net/java/android/net/util/AvoidBadWifiTracker.java b/services/net/java/android/net/util/MultinetworkPolicyTracker.java index 2abaeb1ae35b..ebd131bebb2b 100644 --- a/services/net/java/android/net/util/AvoidBadWifiTracker.java +++ b/services/net/java/android/net/util/MultinetworkPolicyTracker.java @@ -42,8 +42,8 @@ import static android.provider.Settings.Global.NETWORK_AVOID_BAD_WIFI; * 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. + * The Runnable |avoidBadWifiCallback|, if given, is posted to the supplied + * Handler' whenever 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 @@ -51,28 +51,30 @@ import static android.provider.Settings.Global.NETWORK_AVOID_BAD_WIFI; * * @hide */ -public class AvoidBadWifiTracker { - private static String TAG = AvoidBadWifiTracker.class.getSimpleName(); +public class MultinetworkPolicyTracker { + private static String TAG = MultinetworkPolicyTracker.class.getSimpleName(); private final Context mContext; private final Handler mHandler; private final Runnable mReevaluateRunnable; - private final Uri mUri; + private final Uri mAvoidBadWifiUri; private final ContentResolver mResolver; private final SettingObserver mSettingObserver; private final BroadcastReceiver mBroadcastReceiver; private volatile boolean mAvoidBadWifi = true; - public AvoidBadWifiTracker(Context ctx, Handler handler) { + public MultinetworkPolicyTracker(Context ctx, Handler handler) { this(ctx, handler, null); } - public AvoidBadWifiTracker(Context ctx, Handler handler, Runnable cb) { + public MultinetworkPolicyTracker(Context ctx, Handler handler, Runnable avoidBadWifiCallback) { mContext = ctx; mHandler = handler; - mReevaluateRunnable = () -> { if (update() && cb != null) cb.run(); }; - mUri = Settings.Global.getUriFor(NETWORK_AVOID_BAD_WIFI); + mReevaluateRunnable = () -> { + if (updateAvoidBadWifi() && avoidBadWifiCallback != null) avoidBadWifiCallback.run(); + }; + mAvoidBadWifiUri = Settings.Global.getUriFor(NETWORK_AVOID_BAD_WIFI); mResolver = mContext.getContentResolver(); mSettingObserver = new SettingObserver(); mBroadcastReceiver = new BroadcastReceiver() { @@ -82,11 +84,11 @@ public class AvoidBadWifiTracker { } }; - update(); + updateAvoidBadWifi(); } public void start() { - mResolver.registerContentObserver(mUri, false, mSettingObserver); + mResolver.registerContentObserver(mAvoidBadWifiUri, false, mSettingObserver); final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); @@ -102,7 +104,7 @@ public class AvoidBadWifiTracker { mContext.unregisterReceiver(mBroadcastReceiver); } - public boolean currentValue() { + public boolean getAvoidBadWifi() { return mAvoidBadWifi; } @@ -117,10 +119,10 @@ public class AvoidBadWifiTracker { * Whether we should display a notification when wifi becomes unvalidated. */ public boolean shouldNotifyWifiUnvalidated() { - return configRestrictsAvoidBadWifi() && getSettingsValue() == null; + return configRestrictsAvoidBadWifi() && getAvoidBadWifiSetting() == null; } - public String getSettingsValue() { + public String getAvoidBadWifiSetting() { return Settings.Global.getString(mResolver, NETWORK_AVOID_BAD_WIFI); } @@ -129,8 +131,8 @@ public class AvoidBadWifiTracker { mHandler.post(mReevaluateRunnable); } - public boolean update() { - final boolean settingAvoidBadWifi = "1".equals(getSettingsValue()); + public boolean updateAvoidBadWifi() { + final boolean settingAvoidBadWifi = "1".equals(getAvoidBadWifiSetting()); final boolean prev = mAvoidBadWifi; mAvoidBadWifi = settingAvoidBadWifi || !configRestrictsAvoidBadWifi(); return mAvoidBadWifi != prev; @@ -148,7 +150,7 @@ public class AvoidBadWifiTracker { @Override public void onChange(boolean selfChange, Uri uri) { - if (!mUri.equals(uri)) return; + if (!mAvoidBadWifiUri.equals(uri)) return; reevaluate(); } } diff --git a/tests/net/java/android/net/ConnectivityManagerTest.java b/tests/net/java/android/net/ConnectivityManagerTest.java new file mode 100644 index 000000000000..b984bbfddac3 --- /dev/null +++ b/tests/net/java/android/net/ConnectivityManagerTest.java @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2017 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; + +import static android.net.NetworkCapabilities.NET_CAPABILITY_CBS; +import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN; +import static android.net.NetworkCapabilities.NET_CAPABILITY_FOTA; +import static android.net.NetworkCapabilities.NET_CAPABILITY_IMS; +import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; +import static android.net.NetworkCapabilities.NET_CAPABILITY_MMS; +import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED; +import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN; +import static android.net.NetworkCapabilities.NET_CAPABILITY_SUPL; +import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED; +import static android.net.NetworkCapabilities.NET_CAPABILITY_WIFI_P2P; +import static android.net.NetworkCapabilities.TRANSPORT_BLUETOOTH; +import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR; +import static android.net.NetworkCapabilities.TRANSPORT_ETHERNET; +import static android.net.NetworkCapabilities.TRANSPORT_WIFI; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.net.ConnectivityManager; +import android.net.NetworkCapabilities; + +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.runner.RunWith; +import org.junit.Test; + + + +@RunWith(AndroidJUnit4.class) +@SmallTest +public class ConnectivityManagerTest { + static NetworkCapabilities verifyNetworkCapabilities( + int legacyType, int transportType, int... capabilities) { + final NetworkCapabilities nc = ConnectivityManager.networkCapabilitiesForType(legacyType); + assertNotNull(nc); + assertTrue(nc.hasTransport(transportType)); + for (int capability : capabilities) { + assertTrue(nc.hasCapability(capability)); + } + + return nc; + } + + static void verifyUnrestrictedNetworkCapabilities(int legacyType, int transportType) { + verifyNetworkCapabilities( + legacyType, + transportType, + NET_CAPABILITY_INTERNET, + NET_CAPABILITY_NOT_RESTRICTED, + NET_CAPABILITY_NOT_VPN, + NET_CAPABILITY_TRUSTED); + } + + static void verifyRestrictedMobileNetworkCapabilities(int legacyType, int capability) { + final NetworkCapabilities nc = verifyNetworkCapabilities( + legacyType, + TRANSPORT_CELLULAR, + capability, + NET_CAPABILITY_NOT_VPN, + NET_CAPABILITY_TRUSTED); + + assertFalse(nc.hasCapability(NET_CAPABILITY_INTERNET)); + assertFalse(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)); + } + + @Test + public void testNetworkCapabilitiesForTypeMobile() { + verifyUnrestrictedNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE, TRANSPORT_CELLULAR); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileCbs() { + verifyRestrictedMobileNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_CBS, NET_CAPABILITY_CBS); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileDun() { + verifyRestrictedMobileNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_DUN, NET_CAPABILITY_DUN); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileFota() { + verifyRestrictedMobileNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_FOTA, NET_CAPABILITY_FOTA); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileHipri() { + verifyUnrestrictedNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_HIPRI, TRANSPORT_CELLULAR); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileIms() { + verifyRestrictedMobileNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_IMS, NET_CAPABILITY_IMS); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileMms() { + final NetworkCapabilities nc = verifyNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_MMS, + TRANSPORT_CELLULAR, + NET_CAPABILITY_MMS, + NET_CAPABILITY_NOT_VPN, + NET_CAPABILITY_TRUSTED); + + assertFalse(nc.hasCapability(NET_CAPABILITY_INTERNET)); + } + + @Test + public void testNetworkCapabilitiesForTypeMobileSupl() { + final NetworkCapabilities nc = verifyNetworkCapabilities( + ConnectivityManager.TYPE_MOBILE_SUPL, + TRANSPORT_CELLULAR, + NET_CAPABILITY_SUPL, + NET_CAPABILITY_NOT_VPN, + NET_CAPABILITY_TRUSTED); + + assertFalse(nc.hasCapability(NET_CAPABILITY_INTERNET)); + } + + @Test + public void testNetworkCapabilitiesForTypeWifi() { + verifyUnrestrictedNetworkCapabilities( + ConnectivityManager.TYPE_WIFI, TRANSPORT_WIFI); + } + + @Test + public void testNetworkCapabilitiesForTypeWifiP2p() { + final NetworkCapabilities nc = verifyNetworkCapabilities( + ConnectivityManager.TYPE_WIFI_P2P, + TRANSPORT_WIFI, + NET_CAPABILITY_NOT_RESTRICTED, NET_CAPABILITY_NOT_VPN, + NET_CAPABILITY_TRUSTED, NET_CAPABILITY_WIFI_P2P); + + assertFalse(nc.hasCapability(NET_CAPABILITY_INTERNET)); + } + + @Test + public void testNetworkCapabilitiesForTypeBluetooth() { + verifyUnrestrictedNetworkCapabilities( + ConnectivityManager.TYPE_BLUETOOTH, TRANSPORT_BLUETOOTH); + } + + @Test + public void testNetworkCapabilitiesForTypeEthernet() { + verifyUnrestrictedNetworkCapabilities( + ConnectivityManager.TYPE_ETHERNET, TRANSPORT_ETHERNET); + } +} diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java index 2d7a68fe88fd..39406a117410 100644 --- a/tests/net/java/com/android/server/ConnectivityServiceTest.java +++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java @@ -53,7 +53,7 @@ import android.net.NetworkMisc; import android.net.NetworkRequest; import android.net.RouteInfo; import android.net.metrics.IpConnectivityLog; -import android.net.util.AvoidBadWifiTracker; +import android.net.util.MultinetworkPolicyTracker; import android.os.ConditionVariable; import android.os.Handler; import android.os.HandlerThread; @@ -155,25 +155,13 @@ public class ConnectivityServiceTest extends AndroidTestCase { /** * Block until the given handler becomes idle, or until timeoutMs has passed. */ - private static void waitForIdleHandler(HandlerThread handler, int timeoutMs) { + private static void waitForIdleHandler(HandlerThread handlerThread, int timeoutMs) { final ConditionVariable cv = new ConditionVariable(); - final MessageQueue queue = handler.getLooper().getQueue(); - final IdleHandler idleHandler = () -> { - synchronized (queue) { - cv.open(); - return false; // Remove the idleHandler. - } - }; - synchronized (queue) { - if (queue.isIdle()) { - return; - } - queue.addIdleHandler(idleHandler); - } + final Handler handler = new Handler(handlerThread.getLooper()); + handler.post(() -> cv.open()); if (!cv.block(timeoutMs)) { - fail("HandlerThread " + handler.getName() + + fail("HandlerThread " + handlerThread.getName() + " did not become idle after " + timeoutMs + " ms"); - queue.removeIdleHandler(idleHandler); } } @@ -605,10 +593,10 @@ public class ConnectivityServiceTest extends AndroidTestCase { } } - private class WrappedAvoidBadWifiTracker extends AvoidBadWifiTracker { + private class WrappedMultinetworkPolicyTracker extends MultinetworkPolicyTracker { public volatile boolean configRestrictsAvoidBadWifi; - public WrappedAvoidBadWifiTracker(Context c, Handler h, Runnable r) { + public WrappedMultinetworkPolicyTracker(Context c, Handler h, Runnable r) { super(c, h, r); } @@ -619,7 +607,7 @@ public class ConnectivityServiceTest extends AndroidTestCase { } private class WrappedConnectivityService extends ConnectivityService { - public WrappedAvoidBadWifiTracker wrappedAvoidBadWifiTracker; + public WrappedMultinetworkPolicyTracker wrappedMultinetworkPolicyTracker; private WrappedNetworkMonitor mLastCreatedNetworkMonitor; public WrappedConnectivityService(Context context, INetworkManagementService netManager, @@ -666,14 +654,14 @@ public class ConnectivityServiceTest extends AndroidTestCase { } @Override - public AvoidBadWifiTracker createAvoidBadWifiTracker( + public MultinetworkPolicyTracker createMultinetworkPolicyTracker( Context c, Handler h, Runnable r) { - final WrappedAvoidBadWifiTracker tracker = new WrappedAvoidBadWifiTracker(c, h, r); + final WrappedMultinetworkPolicyTracker tracker = new WrappedMultinetworkPolicyTracker(c, h, r); return tracker; } - public WrappedAvoidBadWifiTracker getAvoidBadWifiTracker() { - return (WrappedAvoidBadWifiTracker) mAvoidBadWifiTracker; + public WrappedMultinetworkPolicyTracker getMultinetworkPolicyTracker() { + return (WrappedMultinetworkPolicyTracker) mMultinetworkPolicyTracker; } @Override @@ -695,22 +683,6 @@ public class ConnectivityServiceTest extends AndroidTestCase { } } - private interface Criteria { - public boolean get(); - } - - /** - * Wait up to 500ms for {@code criteria.get()} to become true, polling. - * Fails if 500ms goes by before {@code criteria.get()} to become true. - */ - static private void waitFor(Criteria criteria) { - int delays = 0; - while (!criteria.get()) { - sleepFor(50); - if (++delays == 10) fail(); - } - } - /** * Wait up to TIMEOUT_MS for {@code conditionVariable} to open. * Fails if TIMEOUT_MS goes by before {@code conditionVariable} opens. @@ -846,8 +818,9 @@ public class ConnectivityServiceTest extends AndroidTestCase { assertTrue(mCm.getAllNetworks()[0].equals(mCellNetworkAgent.getNetwork()) || mCm.getAllNetworks()[1].equals(mCellNetworkAgent.getNetwork())); // Test cellular linger timeout. - waitFor(new Criteria() { - public boolean get() { return mCm.getAllNetworks().length == 1; } }); + waitFor(mCellNetworkAgent.getDisconnectedCV()); + mService.waitForIdle(); + assertEquals(1, mCm.getAllNetworks().length); verifyActiveNetwork(TRANSPORT_WIFI); assertEquals(1, mCm.getAllNetworks().length); assertEquals(mCm.getAllNetworks()[0], mCm.getActiveNetwork()); @@ -1622,8 +1595,8 @@ public class ConnectivityServiceTest extends AndroidTestCase { ConditionVariable cv = mCellNetworkAgent.getDisconnectedCV(); mCellNetworkAgent.connectWithoutInternet(); waitFor(cv); - waitFor(new Criteria() { - public boolean get() { return mCm.getAllNetworks().length == 0; } }); + mService.waitForIdle(); + assertEquals(0, mCm.getAllNetworks().length); verifyNoNetwork(); // Test bringing up validated WiFi. mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); @@ -1982,7 +1955,6 @@ public class ConnectivityServiceTest extends AndroidTestCase { // Disconnect wifi and check that cell is foreground again. mWiFiNetworkAgent.disconnect(); - mService.waitForIdle(); callback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent); fgCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent); fgCallback.expectCallback(CallbackState.AVAILABLE, mCellNetworkAgent); @@ -2152,7 +2124,7 @@ public class ConnectivityServiceTest extends AndroidTestCase { @SmallTest public void testAvoidBadWifiSetting() throws Exception { final ContentResolver cr = mServiceContext.getContentResolver(); - final WrappedAvoidBadWifiTracker tracker = mService.getAvoidBadWifiTracker(); + final WrappedMultinetworkPolicyTracker tracker = mService.getMultinetworkPolicyTracker(); final String settingName = Settings.Global.NETWORK_AVOID_BAD_WIFI; tracker.configRestrictsAvoidBadWifi = false; @@ -2162,7 +2134,7 @@ public class ConnectivityServiceTest extends AndroidTestCase { tracker.reevaluate(); mService.waitForIdle(); String msg = String.format("config=false, setting=%s", values[i]); - assertEventuallyTrue(() -> mService.avoidBadWifi(), 50); + assertTrue(mService.avoidBadWifi()); assertFalse(msg, tracker.shouldNotifyWifiUnvalidated()); } @@ -2171,26 +2143,26 @@ public class ConnectivityServiceTest extends AndroidTestCase { Settings.Global.putInt(cr, settingName, 0); tracker.reevaluate(); mService.waitForIdle(); - assertEventuallyTrue(() -> !mService.avoidBadWifi(), 50); + assertFalse(mService.avoidBadWifi()); assertFalse(tracker.shouldNotifyWifiUnvalidated()); Settings.Global.putInt(cr, settingName, 1); tracker.reevaluate(); mService.waitForIdle(); - assertEventuallyTrue(() -> mService.avoidBadWifi(), 50); + assertTrue(mService.avoidBadWifi()); assertFalse(tracker.shouldNotifyWifiUnvalidated()); Settings.Global.putString(cr, settingName, null); tracker.reevaluate(); mService.waitForIdle(); - assertEventuallyTrue(() -> !mService.avoidBadWifi(), 50); + assertFalse(mService.avoidBadWifi()); assertTrue(tracker.shouldNotifyWifiUnvalidated()); } @SmallTest public void testAvoidBadWifi() throws Exception { final ContentResolver cr = mServiceContext.getContentResolver(); - final WrappedAvoidBadWifiTracker tracker = mService.getAvoidBadWifiTracker(); + final WrappedMultinetworkPolicyTracker tracker = mService.getMultinetworkPolicyTracker(); // Pretend we're on a carrier that restricts switching away from bad wifi. tracker.configRestrictsAvoidBadWifi = true; @@ -2404,17 +2376,6 @@ public class ConnectivityServiceTest extends AndroidTestCase { networkCallback.assertNoCallback(); } - public void assertEventuallyTrue(BooleanSupplier fn, long maxWaitingTimeMs) { - long start = SystemClock.elapsedRealtime(); - while (SystemClock.elapsedRealtime() <= start + maxWaitingTimeMs) { - if (fn.getAsBoolean()) { - return; - } - sleepFor(15); - } - assertTrue(fn.getAsBoolean()); - } - private static class TestKeepaliveCallback extends PacketKeepaliveCallback { public static enum CallbackType { ON_STARTED, ON_STOPPED, ON_ERROR }; @@ -2575,12 +2536,13 @@ public class ConnectivityServiceTest extends AndroidTestCase { ka = mCm.startNattKeepalive(myNet, 25, callback, myIPv4, 12345, dstIPv4); callback.expectStarted(); mWiFiNetworkAgent.disconnect(); + waitFor(mWiFiNetworkAgent.getDisconnectedCV()); callback.expectError(PacketKeepalive.ERROR_INVALID_NETWORK); // ... and that stopping it after that has no adverse effects. - // TODO: investigate assertEventuallyTrue is needed and waitForIdle() is not enough + mService.waitForIdle(); final Network myNetAlias = myNet; - assertEventuallyTrue(() -> mCm.getNetworkCapabilities(myNetAlias) == null, 100); + assertNull(mCm.getNetworkCapabilities(myNetAlias)); ka.stop(); // Reconnect. @@ -2592,6 +2554,7 @@ public class ConnectivityServiceTest extends AndroidTestCase { callback.expectStarted(); ka.stop(); mWiFiNetworkAgent.disconnect(); + waitFor(mWiFiNetworkAgent.getDisconnectedCV()); mService.waitForIdle(); callback.expectStopped(); diff --git a/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java b/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java index b8c739b64090..3ed56dff3f83 100644 --- a/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java +++ b/tests/net/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java @@ -23,7 +23,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import android.content.Context; import android.net.ConnectivityManager; @@ -40,6 +46,7 @@ import org.junit.Before; import org.junit.runner.RunWith; import org.junit.Test; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.HashMap; @@ -64,7 +71,7 @@ public class UpstreamNetworkMonitorTest { reset(mContext); reset(mCS); - mCM = new TestConnectivityManager(mContext, mCS); + mCM = spy(new TestConnectivityManager(mContext, mCS)); mUNM = new UpstreamNetworkMonitor(null, EVENT_UNM_UPDATE, (ConnectivityManager) mCM); } @@ -126,6 +133,42 @@ public class UpstreamNetworkMonitorTest { } @Test + public void testDuplicateMobileRequestsIgnored() throws Exception { + assertFalse(mUNM.mobileNetworkRequested()); + assertEquals(0, mCM.requested.size()); + + mUNM.start(); + verify(mCM, Mockito.times(1)).registerNetworkCallback( + any(NetworkRequest.class), any(NetworkCallback.class)); + verify(mCM, Mockito.times(1)).registerDefaultNetworkCallback(any(NetworkCallback.class)); + assertFalse(mUNM.mobileNetworkRequested()); + assertEquals(0, mCM.requested.size()); + + mUNM.updateMobileRequiresDun(true); + mUNM.registerMobileNetworkRequest(); + verify(mCM, Mockito.times(1)).requestNetwork( + any(NetworkRequest.class), any(NetworkCallback.class), anyInt(), anyInt()); + + assertTrue(mUNM.mobileNetworkRequested()); + assertUpstreamTypeRequested(TYPE_MOBILE_DUN); + assertTrue(mCM.isDunRequested()); + + // Try a few things that must not result in any state change. + mUNM.registerMobileNetworkRequest(); + mUNM.updateMobileRequiresDun(true); + mUNM.registerMobileNetworkRequest(); + + assertTrue(mUNM.mobileNetworkRequested()); + assertUpstreamTypeRequested(TYPE_MOBILE_DUN); + assertTrue(mCM.isDunRequested()); + + mUNM.stop(); + verify(mCM, times(3)).unregisterNetworkCallback(any(NetworkCallback.class)); + + verifyNoMoreInteractions(mCM); + } + + @Test public void testRequestsDunNetwork() throws Exception { assertFalse(mUNM.mobileNetworkRequested()); assertEquals(0, mCM.requested.size()); @@ -149,7 +192,7 @@ public class UpstreamNetworkMonitorTest { } @Test - public void testUpdateMobileRequiredDun() throws Exception { + public void testUpdateMobileRequiresDun() throws Exception { mUNM.start(); // Test going from no-DUN to DUN correctly re-registers callbacks. @@ -180,7 +223,7 @@ public class UpstreamNetworkMonitorTest { mCM.legacyTypeMap.values().iterator().next()); } - private static class TestConnectivityManager extends ConnectivityManager { + public static class TestConnectivityManager extends ConnectivityManager { public Set<NetworkCallback> trackingDefault = new HashSet<>(); public Map<NetworkCallback, NetworkRequest> listening = new HashMap<>(); public Map<NetworkCallback, NetworkRequest> requested = new HashMap<>(); diff --git a/wifi/java/android/net/wifi/WifiNetworkScoreCache.java b/wifi/java/android/net/wifi/WifiNetworkScoreCache.java index 9dd118bdbc55..35d7a12ccd79 100755 --- a/wifi/java/android/net/wifi/WifiNetworkScoreCache.java +++ b/wifi/java/android/net/wifi/WifiNetworkScoreCache.java @@ -19,16 +19,16 @@ package android.net.wifi; import android.Manifest.permission; import android.annotation.NonNull; import android.annotation.Nullable; -import android.annotation.SystemApi; import android.content.Context; -import android.os.Handler; import android.net.INetworkScoreCache; import android.net.NetworkKey; import android.net.ScoredNetwork; +import android.os.Handler; +import android.os.Process; import android.util.Log; -import com.android.internal.util.Preconditions; import com.android.internal.annotations.GuardedBy; +import com.android.internal.util.Preconditions; import java.io.FileDescriptor; import java.io.PrintWriter; @@ -76,7 +76,7 @@ public class WifiNetworkScoreCache extends INetworkScoreCache.Stub { public WifiNetworkScoreCache(Context context, @Nullable CacheListener listener) { mContext = context.getApplicationContext(); mListener = listener; - mNetworkCache = new HashMap<String, ScoredNetwork>(); + mNetworkCache = new HashMap<>(); } @Override public final void updateScores(List<ScoredNetwork> networks) { @@ -210,7 +210,9 @@ public class WifiNetworkScoreCache extends INetworkScoreCache.Stub { @Override protected final void dump(FileDescriptor fd, PrintWriter writer, String[] args) { mContext.enforceCallingOrSelfPermission(permission.DUMP, TAG); - writer.println("WifiNetworkScoreCache"); + String header = String.format("WifiNetworkScoreCache (%s/%d)", + mContext.getPackageName(), Process.myUid()); + writer.println(header); writer.println(" All score curves:"); for (Map.Entry<String, ScoredNetwork> entry : mNetworkCache.entrySet()) { ScoredNetwork scoredNetwork = entry.getValue(); diff --git a/wifi/java/android/net/wifi/hotspot2/ConfigBuilder.java b/wifi/java/android/net/wifi/hotspot2/ConfigBuilder.java index 96db5d02679e..78b335d56196 100644 --- a/wifi/java/android/net/wifi/hotspot2/ConfigBuilder.java +++ b/wifi/java/android/net/wifi/hotspot2/ConfigBuilder.java @@ -175,7 +175,7 @@ public final class ConfigBuilder { } // Credential is needed for storing the certificates and private client key. - if (config.credential == null) { + if (config.getCredential() == null) { throw new IOException("Passpoint profile missing credential"); } @@ -183,7 +183,7 @@ public final class ConfigBuilder { byte[] caCertData = mimeParts.get(TYPE_CA_CERT); if (caCertData != null) { try { - config.credential.caCertificate = parseCACert(caCertData); + config.getCredential().setCaCertificate(parseCACert(caCertData)); } catch (CertificateException e) { throw new IOException("Failed to parse CA Certificate"); } @@ -194,9 +194,9 @@ public final class ConfigBuilder { if (pkcs12Data != null) { try { Pair<PrivateKey, List<X509Certificate>> clientKey = parsePkcs12(pkcs12Data); - config.credential.clientPrivateKey = clientKey.first; - config.credential.clientCertificateChain = - clientKey.second.toArray(new X509Certificate[clientKey.second.size()]); + config.getCredential().setClientPrivateKey(clientKey.first); + config.getCredential().setClientCertificateChain( + clientKey.second.toArray(new X509Certificate[clientKey.second.size()])); } catch(GeneralSecurityException | IOException e) { throw new IOException("Failed to parse PCKS12 string"); } diff --git a/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java b/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java index f1174b677dcd..c2b307d6a6fc 100644 --- a/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java +++ b/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java @@ -30,6 +30,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * Class representing Passpoint configuration. This contains configurations specified in @@ -58,21 +59,58 @@ public final class PasspointConfiguration implements Parcelable { */ private static final int NULL_VALUE = -1; - public HomeSP homeSp = null; - public Credential credential = null; - public Policy policy = null; + /** + * Configurations under HomeSP subtree. + */ + private HomeSP mHomeSp = null; + public void setHomeSp(HomeSP homeSp) { mHomeSp = homeSp; } + public HomeSP getHomeSp() { return mHomeSp; } + + /** + * Configurations under Credential subtree. + */ + private Credential mCredential = null; + public void setCredential(Credential credential) { + mCredential = credential; + } + public Credential getCredential() { + return mCredential; + } + + /** + * Configurations under Policy subtree. + */ + private Policy mPolicy = null; + public void setPolicy(Policy policy) { + mPolicy = policy; + } + public Policy getPolicy() { + return mPolicy; + } /** * Meta data for performing subscription update. */ - public UpdateParameter subscriptionUpdate = null; + private UpdateParameter mSubscriptionUpdate = null; + public void setSubscriptionUpdate(UpdateParameter subscriptionUpdate) { + mSubscriptionUpdate = subscriptionUpdate; + } + public UpdateParameter getSubscriptionUpdate() { + return mSubscriptionUpdate; + } /** * List of HTTPS URL for retrieving trust root certificate and the corresponding SHA-256 * fingerprint of the certificate. The certificates are used for verifying AAA server's * identity during EAP authentication. */ - public Map<String, byte[]> trustRootCertList = null; + private Map<String, byte[]> mTrustRootCertList = null; + public void setTrustRootCertList(Map<String, byte[]> trustRootCertList) { + mTrustRootCertList = trustRootCertList; + } + public Map<String, byte[]> getTrustRootCertList() { + return mTrustRootCertList; + } /** * Set by the subscription server, updated every time the configuration is updated by @@ -80,14 +118,26 @@ public final class PasspointConfiguration implements Parcelable { * * Use Integer.MIN_VALUE to indicate unset value. */ - public int updateIdentifier = Integer.MIN_VALUE; + private int mUpdateIdentifier = Integer.MIN_VALUE; + public void setUpdateIdentifier(int updateIdentifier) { + mUpdateIdentifier = updateIdentifier; + } + public int getUpdateIdentififer() { + return mUpdateIdentifier; + } /** * The priority of the credential. * * Use Integer.MIN_VALUE to indicate unset value. */ - public int credentialPriority = Integer.MIN_VALUE; + private int mCredentialPriority = Integer.MIN_VALUE; + public void setCredentialPriority(int credentialPriority) { + mCredentialPriority = credentialPriority; + } + public int getCredentialPriority() { + return mCredentialPriority; + } /** * The time this subscription is created. It is in the format of number @@ -95,7 +145,13 @@ public final class PasspointConfiguration implements Parcelable { * * Use Long.MIN_VALUE to indicate unset value. */ - public long subscriptionCreationTimeInMs = Long.MIN_VALUE; + private long mSubscriptionCreationTimeInMs = Long.MIN_VALUE; + public void setSubscriptionCreationTimeInMs(long subscriptionCreationTimeInMs) { + mSubscriptionCreationTimeInMs = subscriptionCreationTimeInMs; + } + public long getSubscriptionCreationTimeInMs() { + return mSubscriptionCreationTimeInMs; + } /** * The time this subscription will expire. It is in the format of number @@ -103,20 +159,38 @@ public final class PasspointConfiguration implements Parcelable { * * Use Long.MIN_VALUE to indicate unset value. */ - public long subscriptionExpirationTimeInMs = Long.MIN_VALUE; + private long mSubscriptionExpirationTimeInMs = Long.MIN_VALUE; + public void setSubscriptionExpirationTimeInMs(long subscriptionExpirationTimeInMs) { + mSubscriptionExpirationTimeInMs = subscriptionExpirationTimeInMs; + } + public long getSubscriptionExpirationTimeInMs() { + return mSubscriptionExpirationTimeInMs; + } /** * The type of the subscription. This is defined by the provider and the value is provider * specific. */ - public String subscriptionType = null; + private String mSubscriptionType = null; + public void setSubscriptionType(String subscriptionType) { + mSubscriptionType = subscriptionType; + } + public String getSubscriptionType() { + return mSubscriptionType; + } /** * The time period for usage statistics accumulation. A value of zero means that usage * statistics are not accumulated on a periodic basis (e.g., a one-time limit for * “pay as you go” - PAYG service). A non-zero value specifies the usage interval in minutes. */ - public long usageLimitUsageTimePeriodInMinutes = Long.MIN_VALUE; + private long mUsageLimitUsageTimePeriodInMinutes = Long.MIN_VALUE; + public void setUsageLimitUsageTimePeriodInMinutes(long usageLimitUsageTimePeriodInMinutes) { + mUsageLimitUsageTimePeriodInMinutes = usageLimitUsageTimePeriodInMinutes; + } + public long getUsageLimitUsageTimePeriodInMinutes() { + return mUsageLimitUsageTimePeriodInMinutes; + } /** * The time at which usage statistic accumulation begins. It is in the format of number @@ -124,7 +198,13 @@ public final class PasspointConfiguration implements Parcelable { * * Use Long.MIN_VALUE to indicate unset value. */ - public long usageLimitStartTimeInMs = Long.MIN_VALUE; + private long mUsageLimitStartTimeInMs = Long.MIN_VALUE; + public void setUsageLimitStartTimeInMs(long usageLimitStartTimeInMs) { + mUsageLimitStartTimeInMs = usageLimitStartTimeInMs; + } + public long getUsageLimitStartTimeInMs() { + return mUsageLimitStartTimeInMs; + } /** * The cumulative data limit in megabytes for the {@link #usageLimitUsageTimePeriodInMinutes}. @@ -132,14 +212,25 @@ public final class PasspointConfiguration implements Parcelable { * * Use Long.MIN_VALUE to indicate unset value. */ - public long usageLimitDataLimit = Long.MIN_VALUE; + private long mUsageLimitDataLimit = Long.MIN_VALUE; + public void setUsageLimitDataLimit(long usageLimitDataLimit) { + mUsageLimitDataLimit = usageLimitDataLimit; + } + public long getUsageLimitDataLimit() { + return mUsageLimitDataLimit; + } /** * The cumulative time limit in minutes for the {@link #usageLimitUsageTimePeriodInMinutes}. * A value of zero indicate unlimited time usage. */ - public long usageLimitTimeLimitInMinutes = Long.MIN_VALUE; - + private long mUsageLimitTimeLimitInMinutes = Long.MIN_VALUE; + public void setUsageLimitTimeLimitInMinutes(long usageLimitTimeLimitInMinutes) { + mUsageLimitTimeLimitInMinutes = usageLimitTimeLimitInMinutes; + } + public long getUsageLimitTimeLimitInMinutes() { + return mUsageLimitTimeLimitInMinutes; + } /** * Constructor for creating PasspointConfiguration with default values. @@ -156,30 +247,30 @@ public final class PasspointConfiguration implements Parcelable { return; } - if (source.homeSp != null) { - homeSp = new HomeSP(source.homeSp); + if (source.mHomeSp != null) { + mHomeSp = new HomeSP(source.mHomeSp); } - if (source.credential != null) { - credential = new Credential(source.credential); + if (source.mCredential != null) { + mCredential = new Credential(source.mCredential); } - if (source.policy != null) { - policy = new Policy(source.policy); + if (source.mPolicy != null) { + mPolicy = new Policy(source.mPolicy); } - if (source.trustRootCertList != null) { - trustRootCertList = Collections.unmodifiableMap(source.trustRootCertList); + if (source.mTrustRootCertList != null) { + mTrustRootCertList = Collections.unmodifiableMap(source.mTrustRootCertList); } - if (source.subscriptionUpdate != null) { - subscriptionUpdate = new UpdateParameter(source.subscriptionUpdate); + if (source.mSubscriptionUpdate != null) { + mSubscriptionUpdate = new UpdateParameter(source.mSubscriptionUpdate); } - updateIdentifier = source.updateIdentifier; - credentialPriority = source.credentialPriority; - subscriptionCreationTimeInMs = source.subscriptionCreationTimeInMs; - subscriptionExpirationTimeInMs = source.subscriptionExpirationTimeInMs; - subscriptionType = source.subscriptionType; - usageLimitDataLimit = source.usageLimitDataLimit; - usageLimitStartTimeInMs = source.usageLimitStartTimeInMs; - usageLimitTimeLimitInMinutes = source.usageLimitTimeLimitInMinutes; - usageLimitUsageTimePeriodInMinutes = source.usageLimitUsageTimePeriodInMinutes; + mUpdateIdentifier = source.mUpdateIdentifier; + mCredentialPriority = source.mCredentialPriority; + mSubscriptionCreationTimeInMs = source.mSubscriptionCreationTimeInMs; + mSubscriptionExpirationTimeInMs = source.mSubscriptionExpirationTimeInMs; + mSubscriptionType = source.mSubscriptionType; + mUsageLimitDataLimit = source.mUsageLimitDataLimit; + mUsageLimitStartTimeInMs = source.mUsageLimitStartTimeInMs; + mUsageLimitTimeLimitInMinutes = source.mUsageLimitTimeLimitInMinutes; + mUsageLimitUsageTimePeriodInMinutes = source.mUsageLimitUsageTimePeriodInMinutes; } @Override @@ -189,20 +280,20 @@ public final class PasspointConfiguration implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeParcelable(homeSp, flags); - dest.writeParcelable(credential, flags); - dest.writeParcelable(policy, flags); - dest.writeParcelable(subscriptionUpdate, flags); - writeTrustRootCerts(dest, trustRootCertList); - dest.writeInt(updateIdentifier); - dest.writeInt(credentialPriority); - dest.writeLong(subscriptionCreationTimeInMs); - dest.writeLong(subscriptionExpirationTimeInMs); - dest.writeString(subscriptionType); - dest.writeLong(usageLimitUsageTimePeriodInMinutes); - dest.writeLong(usageLimitStartTimeInMs); - dest.writeLong(usageLimitDataLimit); - dest.writeLong(usageLimitTimeLimitInMinutes); + dest.writeParcelable(mHomeSp, flags); + dest.writeParcelable(mCredential, flags); + dest.writeParcelable(mPolicy, flags); + dest.writeParcelable(mSubscriptionUpdate, flags); + writeTrustRootCerts(dest, mTrustRootCertList); + dest.writeInt(mUpdateIdentifier); + dest.writeInt(mCredentialPriority); + dest.writeLong(mSubscriptionCreationTimeInMs); + dest.writeLong(mSubscriptionExpirationTimeInMs); + dest.writeString(mSubscriptionType); + dest.writeLong(mUsageLimitUsageTimePeriodInMinutes); + dest.writeLong(mUsageLimitStartTimeInMs); + dest.writeLong(mUsageLimitDataLimit); + dest.writeLong(mUsageLimitTimeLimitInMinutes); } @Override @@ -214,22 +305,30 @@ public final class PasspointConfiguration implements Parcelable { return false; } PasspointConfiguration that = (PasspointConfiguration) thatObject; - return (homeSp == null ? that.homeSp == null : homeSp.equals(that.homeSp)) - && (credential == null ? that.credential == null - : credential.equals(that.credential)) - && (policy == null ? that.policy == null : policy.equals(that.policy)) - && (subscriptionUpdate == null ? that.subscriptionUpdate == null - : subscriptionUpdate.equals(that.subscriptionUpdate)) - && isTrustRootCertListEquals(trustRootCertList, that.trustRootCertList) - && updateIdentifier == that.updateIdentifier - && credentialPriority == that.credentialPriority - && subscriptionCreationTimeInMs == that.subscriptionCreationTimeInMs - && subscriptionExpirationTimeInMs == that.subscriptionExpirationTimeInMs - && TextUtils.equals(subscriptionType, that.subscriptionType) - && usageLimitUsageTimePeriodInMinutes == that.usageLimitUsageTimePeriodInMinutes - && usageLimitStartTimeInMs == that.usageLimitStartTimeInMs - && usageLimitDataLimit == that.usageLimitDataLimit - && usageLimitTimeLimitInMinutes == that .usageLimitTimeLimitInMinutes; + return (mHomeSp == null ? that.mHomeSp == null : mHomeSp.equals(that.mHomeSp)) + && (mCredential == null ? that.mCredential == null + : mCredential.equals(that.mCredential)) + && (mPolicy == null ? that.mPolicy == null : mPolicy.equals(that.mPolicy)) + && (mSubscriptionUpdate == null ? that.mSubscriptionUpdate == null + : mSubscriptionUpdate.equals(that.mSubscriptionUpdate)) + && isTrustRootCertListEquals(mTrustRootCertList, that.mTrustRootCertList) + && mUpdateIdentifier == that.mUpdateIdentifier + && mCredentialPriority == that.mCredentialPriority + && mSubscriptionCreationTimeInMs == that.mSubscriptionCreationTimeInMs + && mSubscriptionExpirationTimeInMs == that.mSubscriptionExpirationTimeInMs + && TextUtils.equals(mSubscriptionType, that.mSubscriptionType) + && mUsageLimitUsageTimePeriodInMinutes == that.mUsageLimitUsageTimePeriodInMinutes + && mUsageLimitStartTimeInMs == that.mUsageLimitStartTimeInMs + && mUsageLimitDataLimit == that.mUsageLimitDataLimit + && mUsageLimitTimeLimitInMinutes == that.mUsageLimitTimeLimitInMinutes; + } + + @Override + public int hashCode() { + return Objects.hash(mHomeSp, mCredential, mPolicy, mSubscriptionUpdate, mTrustRootCertList, + mUpdateIdentifier, mCredentialPriority, mSubscriptionCreationTimeInMs, + mSubscriptionExpirationTimeInMs, mUsageLimitUsageTimePeriodInMinutes, + mUsageLimitStartTimeInMs, mUsageLimitDataLimit, mUsageLimitTimeLimitInMinutes); } /** @@ -238,20 +337,20 @@ public final class PasspointConfiguration implements Parcelable { * @return true on success or false on failure */ public boolean validate() { - if (homeSp == null || !homeSp.validate()) { + if (mHomeSp == null || !mHomeSp.validate()) { return false; } - if (credential == null || !credential.validate()) { + if (mCredential == null || !mCredential.validate()) { return false; } - if (policy != null && !policy.validate()) { + if (mPolicy != null && !mPolicy.validate()) { return false; } - if (subscriptionUpdate != null && !subscriptionUpdate.validate()) { + if (mSubscriptionUpdate != null && !mSubscriptionUpdate.validate()) { return false; } - if (trustRootCertList != null) { - for (Map.Entry<String, byte[]> entry : trustRootCertList.entrySet()) { + if (mTrustRootCertList != null) { + for (Map.Entry<String, byte[]> entry : mTrustRootCertList.entrySet()) { String url = entry.getKey(); byte[] certFingerprint = entry.getValue(); if (TextUtils.isEmpty(url)) { @@ -283,20 +382,20 @@ public final class PasspointConfiguration implements Parcelable { @Override public PasspointConfiguration createFromParcel(Parcel in) { PasspointConfiguration config = new PasspointConfiguration(); - config.homeSp = in.readParcelable(null); - config.credential = in.readParcelable(null); - config.policy = in.readParcelable(null); - config.subscriptionUpdate = in.readParcelable(null); - config.trustRootCertList = readTrustRootCerts(in); - config.updateIdentifier = in.readInt(); - config.credentialPriority = in.readInt(); - config.subscriptionCreationTimeInMs = in.readLong(); - config.subscriptionExpirationTimeInMs = in.readLong(); - config.subscriptionType = in.readString(); - config.usageLimitUsageTimePeriodInMinutes = in.readLong(); - config.usageLimitStartTimeInMs = in.readLong(); - config.usageLimitDataLimit = in.readLong(); - config.usageLimitTimeLimitInMinutes = in.readLong(); + config.setHomeSp(in.readParcelable(null)); + config.setCredential(in.readParcelable(null)); + config.setPolicy(in.readParcelable(null)); + config.setSubscriptionUpdate(in.readParcelable(null)); + config.setTrustRootCertList(readTrustRootCerts(in)); + config.setUpdateIdentifier(in.readInt()); + config.setCredentialPriority(in.readInt()); + config.setSubscriptionCreationTimeInMs(in.readLong()); + config.setSubscriptionExpirationTimeInMs(in.readLong()); + config.setSubscriptionType(in.readString()); + config.setUsageLimitUsageTimePeriodInMinutes(in.readLong()); + config.setUsageLimitStartTimeInMs(in.readLong()); + config.setUsageLimitDataLimit(in.readLong()); + config.setUsageLimitTimeLimitInMinutes(in.readLong()); return config; } diff --git a/wifi/java/android/net/wifi/hotspot2/omadm/PPSMOParser.java b/wifi/java/android/net/wifi/hotspot2/omadm/PPSMOParser.java index 22b0f977d3e8..24672d45f47a 100644 --- a/wifi/java/android/net/wifi/hotspot2/omadm/PPSMOParser.java +++ b/wifi/java/android/net/wifi/hotspot2/omadm/PPSMOParser.java @@ -450,7 +450,7 @@ public final class PPSMOParser { } } if (config != null && updateIdentifier != Integer.MIN_VALUE) { - config.updateIdentifier = updateIdentifier; + config.setUpdateIdentifier(updateIdentifier); } return config; } @@ -606,25 +606,25 @@ public final class PPSMOParser { for (PPSNode child : root.getChildren()) { switch(child.getName()) { case NODE_HOMESP: - config.homeSp = parseHomeSP(child); + config.setHomeSp(parseHomeSP(child)); break; case NODE_CREDENTIAL: - config.credential = parseCredential(child); + config.setCredential(parseCredential(child)); break; case NODE_POLICY: - config.policy = parsePolicy(child); + config.setPolicy(parsePolicy(child)); break; case NODE_AAA_SERVER_TRUST_ROOT: - config.trustRootCertList = parseAAAServerTrustRootList(child); + config.setTrustRootCertList(parseAAAServerTrustRootList(child)); break; case NODE_SUBSCRIPTION_UPDATE: - config.subscriptionUpdate = parseUpdateParameter(child); + config.setSubscriptionUpdate(parseUpdateParameter(child)); break; case NODE_SUBSCRIPTION_PARAMETER: parseSubscriptionParameter(child, config); break; case NODE_CREDENTIAL_PRIORITY: - config.credentialPriority = parseInteger(getPpsNodeValue(child)); + config.setCredentialPriority(parseInteger(getPpsNodeValue(child))); break; default: throw new ParsingException("Unknown node: " + child.getName()); @@ -649,28 +649,28 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_FQDN: - homeSp.fqdn = getPpsNodeValue(child); + homeSp.setFqdn(getPpsNodeValue(child)); break; case NODE_FRIENDLY_NAME: - homeSp.friendlyName = getPpsNodeValue(child); + homeSp.setFriendlyName(getPpsNodeValue(child)); break; case NODE_ROAMING_CONSORTIUM_OI: - homeSp.roamingConsortiumOIs = - parseRoamingConsortiumOI(getPpsNodeValue(child)); + homeSp.setRoamingConsortiumOIs( + parseRoamingConsortiumOI(getPpsNodeValue(child))); break; case NODE_ICON_URL: - homeSp.iconUrl = getPpsNodeValue(child); + homeSp.setIconUrl(getPpsNodeValue(child)); break; case NODE_NETWORK_ID: - homeSp.homeNetworkIds = parseNetworkIds(child); + homeSp.setHomeNetworkIds(parseNetworkIds(child)); break; case NODE_HOME_OI_LIST: Pair<List<Long>, List<Long>> homeOIs = parseHomeOIList(child); - homeSp.matchAllOIs = convertFromLongList(homeOIs.first); - homeSp.matchAnyOIs = convertFromLongList(homeOIs.second); + homeSp.setMatchAllOIs(convertFromLongList(homeOIs.first)); + homeSp.setMatchAnyOIs(convertFromLongList(homeOIs.second)); break; case NODE_OTHER_HOME_PARTNERS: - homeSp.otherHomePartners = parseOtherHomePartners(child); + homeSp.setOtherHomePartners(parseOtherHomePartners(child)); break; default: throw new ParsingException("Unknown node under HomeSP: " + child.getName()); @@ -894,26 +894,26 @@ public final class PPSMOParser { for (PPSNode child: node.getChildren()) { switch (child.getName()) { case NODE_CREATION_DATE: - credential.creationTimeInMs = parseDate(getPpsNodeValue(child)); + credential.setCreationTimeInMs(parseDate(getPpsNodeValue(child))); break; case NODE_EXPIRATION_DATE: - credential.expirationTimeInMs = parseDate(getPpsNodeValue(child)); + credential.setExpirationTimeInMs(parseDate(getPpsNodeValue(child))); break; case NODE_USERNAME_PASSWORD: - credential.userCredential = parseUserCredential(child); + credential.setUserCredential(parseUserCredential(child)); break; case NODE_DIGITAL_CERTIFICATE: - credential.certCredential = parseCertificateCredential(child); + credential.setCertCredential(parseCertificateCredential(child)); break; case NODE_REALM: - credential.realm = getPpsNodeValue(child); + credential.setRealm(getPpsNodeValue(child)); break; case NODE_CHECK_AAA_SERVER_CERT_STATUS: - credential.checkAAAServerCertStatus = - Boolean.parseBoolean(getPpsNodeValue(child)); + credential.setCheckAAAServerCertStatus( + Boolean.parseBoolean(getPpsNodeValue(child))); break; case NODE_SIM: - credential.simCredential = parseSimCredential(child); + credential.setSimCredential(parseSimCredential(child)); break; default: throw new ParsingException("Unknown node under Credential: " + @@ -941,19 +941,19 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_USERNAME: - userCred.username = getPpsNodeValue(child); + userCred.setUsername(getPpsNodeValue(child)); break; case NODE_PASSWORD: - userCred.password = getPpsNodeValue(child); + userCred.setPassword(getPpsNodeValue(child)); break; case NODE_MACHINE_MANAGED: - userCred.machineManaged = Boolean.parseBoolean(getPpsNodeValue(child)); + userCred.setMachineManaged(Boolean.parseBoolean(getPpsNodeValue(child))); break; case NODE_SOFT_TOKEN_APP: - userCred.softTokenApp = getPpsNodeValue(child); + userCred.setSoftTokenApp(getPpsNodeValue(child)); break; case NODE_ABLE_TO_SHARE: - userCred.ableToShare = Boolean.parseBoolean(getPpsNodeValue(child)); + userCred.setAbleToShare(Boolean.parseBoolean(getPpsNodeValue(child))); break; case NODE_EAP_METHOD: parseEAPMethod(child, userCred); @@ -984,10 +984,10 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch(child.getName()) { case NODE_EAP_TYPE: - userCred.eapType = parseInteger(getPpsNodeValue(child)); + userCred.setEapType(parseInteger(getPpsNodeValue(child))); break; case NODE_INNER_METHOD: - userCred.nonEapInnerMethod = getPpsNodeValue(child); + userCred.setNonEapInnerMethod(getPpsNodeValue(child)); break; case NODE_VENDOR_ID: case NODE_VENDOR_TYPE: @@ -1022,10 +1022,10 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_CERTIFICATE_TYPE: - certCred.certType = getPpsNodeValue(child); + certCred.setCertType(getPpsNodeValue(child)); break; case NODE_CERT_SHA256_FINGERPRINT: - certCred.certSha256FingerPrint = parseHexString(getPpsNodeValue(child)); + certCred.setCertSha256Fingerprint(parseHexString(getPpsNodeValue(child))); break; default: throw new ParsingException("Unknown node under DigitalCertificate: " + @@ -1053,10 +1053,10 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_SIM_IMSI: - simCred.imsi = getPpsNodeValue(child); + simCred.setImsi(getPpsNodeValue(child)); break; case NODE_EAP_TYPE: - simCred.eapType = parseInteger(getPpsNodeValue(child)); + simCred.setEapType(parseInteger(getPpsNodeValue(child))); break; default: throw new ParsingException("Unknown node under SIM: " + child.getName()); @@ -1081,22 +1081,22 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_PREFERRED_ROAMING_PARTNER_LIST: - policy.preferredRoamingPartnerList = parsePreferredRoamingPartnerList(child); + policy.setPreferredRoamingPartnerList(parsePreferredRoamingPartnerList(child)); break; case NODE_MIN_BACKHAUL_THRESHOLD: parseMinBackhaulThreshold(child, policy); break; case NODE_POLICY_UPDATE: - policy.policyUpdate = parseUpdateParameter(child); + policy.setPolicyUpdate(parseUpdateParameter(child)); break; case NODE_SP_EXCLUSION_LIST: - policy.excludedSsidList = parseSpExclusionList(child); + policy.setExcludedSsidList(parseSpExclusionList(child)); break; case NODE_REQUIRED_PROTO_PORT_TUPLE: - policy.requiredProtoPortMap = parseRequiredProtoPortTuple(child); + policy.setRequiredProtoPortMap(parseRequiredProtoPortTuple(child)); break; case NODE_MAXIMUM_BSS_LOAD_VALUE: - policy.maximumBssLoadValue = parseInteger(getPpsNodeValue(child)); + policy.setMaximumBssLoadValue(parseInteger(getPpsNodeValue(child))); break; default: throw new ParsingException("Unknown node under Policy: " + child.getName()); @@ -1154,20 +1154,20 @@ public final class PPSMOParser { if (fqdnMatchArray.length != 2) { throw new ParsingException("Invalid FQDN_Match: " + fqdnMatch); } - roamingPartner.fqdn = fqdnMatchArray[0]; + roamingPartner.setFqdn(fqdnMatchArray[0]); if (TextUtils.equals(fqdnMatchArray[1], "exactMatch")) { - roamingPartner.fqdnExactMatch = true; + roamingPartner.setFqdnExactMatch(true); } else if (TextUtils.equals(fqdnMatchArray[1], "includeSubdomains")) { - roamingPartner.fqdnExactMatch = false; + roamingPartner.setFqdnExactMatch(false); } else { throw new ParsingException("Invalid FQDN_Match: " + fqdnMatch); } break; case NODE_PRIORITY: - roamingPartner.priority = parseInteger(getPpsNodeValue(child)); + roamingPartner.setPriority(parseInteger(getPpsNodeValue(child))); break; case NODE_COUNTRY: - roamingPartner.countries = getPpsNodeValue(child); + roamingPartner.setCountries(getPpsNodeValue(child)); break; default: throw new ParsingException("Unknown node under PreferredRoamingPartnerList " @@ -1234,11 +1234,11 @@ public final class PPSMOParser { } if (TextUtils.equals(networkType, "home")) { - policy.minHomeDownlinkBandwidth = downlinkBandwidth; - policy.minHomeUplinkBandwidth = uplinkBandwidth; + policy.setMinHomeDownlinkBandwidth(downlinkBandwidth); + policy.setMinHomeUplinkBandwidth(uplinkBandwidth); } else if (TextUtils.equals(networkType, "roaming")) { - policy.minRoamingDownlinkBandwidth = downlinkBandwidth; - policy.minRoamingUplinkBandwidth = uplinkBandwidth; + policy.setMinRoamingDownlinkBandwidth(downlinkBandwidth); + policy.setMinRoamingUplinkBandwidth(uplinkBandwidth); } else { throw new ParsingException("Invalid network type: " + networkType); } @@ -1264,26 +1264,26 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch(child.getName()) { case NODE_UPDATE_INTERVAL: - updateParam.updateIntervalInMinutes = parseLong(getPpsNodeValue(child), 10); + updateParam.setUpdateIntervalInMinutes(parseLong(getPpsNodeValue(child), 10)); break; case NODE_UPDATE_METHOD: - updateParam.updateMethod = getPpsNodeValue(child); + updateParam.setUpdateMethod(getPpsNodeValue(child)); break; case NODE_RESTRICTION: - updateParam.restriction = getPpsNodeValue(child); + updateParam.setRestriction(getPpsNodeValue(child)); break; case NODE_URI: - updateParam.serverUri = getPpsNodeValue(child); + updateParam.setServerUri(getPpsNodeValue(child)); break; case NODE_USERNAME_PASSWORD: Pair<String, String> usernamePassword = parseUpdateUserCredential(child); - updateParam.username = usernamePassword.first; - updateParam.base64EncodedPassword = usernamePassword.second; + updateParam.setUsername(usernamePassword.first); + updateParam.setBase64EncodedPassword(usernamePassword.second); break; case NODE_TRUST_ROOT: Pair<String, byte[]> trustRoot = parseTrustRoot(child); - updateParam.trustRootCertUrl = trustRoot.first; - updateParam.trustRootCertSha256Fingerprint = trustRoot.second; + updateParam.setTrustRootCertUrl(trustRoot.first); + updateParam.setTrustRootCertSha256Fingerprint(trustRoot.second); break; case NODE_OTHER: Log.d(TAG, "Ignore unsupported paramter: " + child.getName()); @@ -1508,13 +1508,13 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_CREATION_DATE: - config.subscriptionCreationTimeInMs = parseDate(getPpsNodeValue(child)); + config.setSubscriptionCreationTimeInMs(parseDate(getPpsNodeValue(child))); break; case NODE_EXPIRATION_DATE: - config.subscriptionExpirationTimeInMs = parseDate(getPpsNodeValue(child)); + config.setSubscriptionExpirationTimeInMs(parseDate(getPpsNodeValue(child))); break; case NODE_TYPE_OF_SUBSCRIPTION: - config.subscriptionType = getPpsNodeValue(child); + config.setSubscriptionType(getPpsNodeValue(child)); break; case NODE_USAGE_LIMITS: parseUsageLimits(child, config); @@ -1543,17 +1543,17 @@ public final class PPSMOParser { for (PPSNode child : node.getChildren()) { switch (child.getName()) { case NODE_DATA_LIMIT: - config.usageLimitDataLimit = parseLong(getPpsNodeValue(child), 10); + config.setUsageLimitDataLimit(parseLong(getPpsNodeValue(child), 10)); break; case NODE_START_DATE: - config.usageLimitStartTimeInMs = parseDate(getPpsNodeValue(child)); + config.setUsageLimitStartTimeInMs(parseDate(getPpsNodeValue(child))); break; case NODE_TIME_LIMIT: - config.usageLimitTimeLimitInMinutes = parseLong(getPpsNodeValue(child), 10); + config.setUsageLimitTimeLimitInMinutes(parseLong(getPpsNodeValue(child), 10)); break; case NODE_USAGE_TIME_PERIOD: - config.usageLimitUsageTimePeriodInMinutes = - parseLong(getPpsNodeValue(child), 10); + config.setUsageLimitUsageTimePeriodInMinutes( + parseLong(getPpsNodeValue(child), 10)); break; default: throw new ParsingException("Unknown node under UsageLimits" diff --git a/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java b/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java index e87698cb7ed1..959d5057e257 100644 --- a/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java +++ b/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java @@ -20,6 +20,7 @@ import android.text.TextUtils; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** * A class represent a node in an XML tree. Each node is an XML element. @@ -100,4 +101,9 @@ public class XMLNode { TextUtils.equals(mText, that.mText) && mChildren.equals(that.mChildren); } + + @Override + public int hashCode() { + return Objects.hash(mTag, mText, mChildren); + } } diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java index 3374f42dc118..ff93486dd25b 100644 --- a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java +++ b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java @@ -31,6 +31,7 @@ import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.HashSet; +import java.util.Objects; import java.util.Set; /** @@ -58,28 +59,52 @@ public final class Credential implements Parcelable { * of milliseconds since January 1, 1970, 00:00:00 GMT. * Using Long.MIN_VALUE to indicate unset value. */ - public long creationTimeInMs = Long.MIN_VALUE; + private long mCreationTimeInMs = Long.MIN_VALUE; + public void setCreationTimeInMs(long creationTimeInMs) { + mCreationTimeInMs = creationTimeInMs; + } + public long getCreationTimeInMs() { + return mCreationTimeInMs; + } /** * The time this credential will expire. It is in the format of number * of milliseconds since January 1, 1970, 00:00:00 GMT. * Using Long.MIN_VALUE to indicate unset value. */ - public long expirationTimeInMs = Long.MIN_VALUE; + private long mExpirationTimeInMs = Long.MIN_VALUE; + public void setExpirationTimeInMs(long expirationTimeInMs) { + mExpirationTimeInMs = expirationTimeInMs; + } + public long getExpirationTimeInMs() { + return mExpirationTimeInMs; + } /** * The realm associated with this credential. It will be used to determine * if this credential can be used to authenticate with a given hotspot by * comparing the realm specified in that hotspot's ANQP element. */ - public String realm = null; + private String mRealm = null; + public void setRealm(String realm) { + mRealm = realm; + } + public String getRealm() { + return mRealm; + } /** * When set to true, the device should check AAA (Authentication, Authorization, * and Accounting) server's certificate during EAP (Extensible Authentication * Protocol) authentication. */ - public boolean checkAAAServerCertStatus = false; + private boolean mCheckAAAServerCertStatus = false; + public void setCheckAAAServerCertStatus(boolean checkAAAServerCertStatus) { + mCheckAAAServerCertStatus = checkAAAServerCertStatus; + } + public boolean getCheckAAAServerStatus() { + return mCheckAAAServerCertStatus; + } /** * Username-password based credential. @@ -109,27 +134,57 @@ public final class Credential implements Parcelable { /** * Username of the credential. */ - public String username = null; + private String mUsername = null; + public void setUsername(String username) { + mUsername = username; + } + public String getUsername() { + return mUsername; + } /** * Base64-encoded password. */ - public String password = null; + private String mPassword = null; + public void setPassword(String password) { + mPassword = password; + } + public String getPassword() { + return mPassword; + } /** * Flag indicating if the password is machine managed. */ - public boolean machineManaged = false; + private boolean mMachineManaged = false; + public void setMachineManaged(boolean machineManaged) { + mMachineManaged = machineManaged; + } + public boolean getMachineManaged() { + return mMachineManaged; + } /** * The name of the application used to generate the password. */ - public String softTokenApp = null; + private String mSoftTokenApp = null; + public void setSoftTokenApp(String softTokenApp) { + mSoftTokenApp = softTokenApp; + } + public String getSoftTokenApp() { + return mSoftTokenApp; + } /** * Flag indicating if this credential is usable on other mobile devices as well. */ - public boolean ableToShare = false; + private boolean mAbleToShare = false; + public void setAbleToShare(boolean ableToShare) { + mAbleToShare = ableToShare; + } + public boolean getAbleToShare() { + return mAbleToShare; + } /** * EAP (Extensible Authentication Protocol) method type. @@ -137,12 +192,24 @@ public final class Credential implements Parcelable { * for valid values. * Using Integer.MIN_VALUE to indicate unset value. */ - public int eapType = Integer.MIN_VALUE; + private int mEapType = Integer.MIN_VALUE; + public void setEapType(int eapType) { + mEapType = eapType; + } + public int getEapType() { + return mEapType; + } /** * Non-EAP inner authentication method. */ - public String nonEapInnerMethod = null; + private String mNonEapInnerMethod = null; + public void setNonEapInnerMethod(String nonEapInnerMethod) { + mNonEapInnerMethod = nonEapInnerMethod; + } + public String getNonEapInnerMethod() { + return mNonEapInnerMethod; + } /** * Constructor for creating UserCredential with default values. @@ -156,13 +223,13 @@ public final class Credential implements Parcelable { */ public UserCredential(UserCredential source) { if (source != null) { - username = source.username; - password = source.password; - machineManaged = source.machineManaged; - softTokenApp = source.softTokenApp; - ableToShare = source.ableToShare; - eapType = source.eapType; - nonEapInnerMethod = source.nonEapInnerMethod; + mUsername = source.mUsername; + mPassword = source.mPassword; + mMachineManaged = source.mMachineManaged; + mSoftTokenApp = source.mSoftTokenApp; + mAbleToShare = source.mAbleToShare; + mEapType = source.mEapType; + mNonEapInnerMethod = source.mNonEapInnerMethod; } } @@ -173,13 +240,13 @@ public final class Credential implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeString(username); - dest.writeString(password); - dest.writeInt(machineManaged ? 1 : 0); - dest.writeString(softTokenApp); - dest.writeInt(ableToShare ? 1 : 0); - dest.writeInt(eapType); - dest.writeString(nonEapInnerMethod); + dest.writeString(mUsername); + dest.writeString(mPassword); + dest.writeInt(mMachineManaged ? 1 : 0); + dest.writeString(mSoftTokenApp); + dest.writeInt(mAbleToShare ? 1 : 0); + dest.writeInt(mEapType); + dest.writeString(mNonEapInnerMethod); } @Override @@ -192,13 +259,19 @@ public final class Credential implements Parcelable { } UserCredential that = (UserCredential) thatObject; - return TextUtils.equals(username, that.username) - && TextUtils.equals(password, that.password) - && machineManaged == that.machineManaged - && TextUtils.equals(softTokenApp, that.softTokenApp) - && ableToShare == that.ableToShare - && eapType == that.eapType - && TextUtils.equals(nonEapInnerMethod, that.nonEapInnerMethod); + return TextUtils.equals(mUsername, that.mUsername) + && TextUtils.equals(mPassword, that.mPassword) + && mMachineManaged == that.mMachineManaged + && TextUtils.equals(mSoftTokenApp, that.mSoftTokenApp) + && mAbleToShare == that.mAbleToShare + && mEapType == that.mEapType + && TextUtils.equals(mNonEapInnerMethod, that.mNonEapInnerMethod); + } + + @Override + public int hashCode() { + return Objects.hash(mUsername, mPassword, mMachineManaged, mSoftTokenApp, + mAbleToShare, mEapType, mNonEapInnerMethod); } /** @@ -207,35 +280,35 @@ public final class Credential implements Parcelable { * @return true on success or false on failure */ public boolean validate() { - if (TextUtils.isEmpty(username)) { + if (TextUtils.isEmpty(mUsername)) { Log.d(TAG, "Missing username"); return false; } - if (username.getBytes(StandardCharsets.UTF_8).length > MAX_USERNAME_BYTES) { + if (mUsername.getBytes(StandardCharsets.UTF_8).length > MAX_USERNAME_BYTES) { Log.d(TAG, "username exceeding maximum length: " - + username.getBytes(StandardCharsets.UTF_8).length); + + mUsername.getBytes(StandardCharsets.UTF_8).length); return false; } - if (TextUtils.isEmpty(password)) { + if (TextUtils.isEmpty(mPassword)) { Log.d(TAG, "Missing password"); return false; } - if (password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) { + if (mPassword.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) { Log.d(TAG, "password exceeding maximum length: " - + password.getBytes(StandardCharsets.UTF_8).length); + + mPassword.getBytes(StandardCharsets.UTF_8).length); return false; } // Only supports EAP-TTLS for user credential. - if (eapType != EAPConstants.EAP_TTLS) { - Log.d(TAG, "Invalid EAP Type for user credential: " + eapType); + if (mEapType != EAPConstants.EAP_TTLS) { + Log.d(TAG, "Invalid EAP Type for user credential: " + mEapType); return false; } // Verify Non-EAP inner method for EAP-TTLS. - if (!SUPPORTED_AUTH.contains(nonEapInnerMethod)) { - Log.d(TAG, "Invalid non-EAP inner method for EAP-TTLS: " + nonEapInnerMethod); + if (!SUPPORTED_AUTH.contains(mNonEapInnerMethod)) { + Log.d(TAG, "Invalid non-EAP inner method for EAP-TTLS: " + mNonEapInnerMethod); return false; } return true; @@ -246,13 +319,13 @@ public final class Credential implements Parcelable { @Override public UserCredential createFromParcel(Parcel in) { UserCredential userCredential = new UserCredential(); - userCredential.username = in.readString(); - userCredential.password = in.readString(); - userCredential.machineManaged = in.readInt() != 0; - userCredential.softTokenApp = in.readString(); - userCredential.ableToShare = in.readInt() != 0; - userCredential.eapType = in.readInt(); - userCredential.nonEapInnerMethod = in.readString(); + userCredential.setUsername(in.readString()); + userCredential.setPassword(in.readString()); + userCredential.setMachineManaged(in.readInt() != 0); + userCredential.setSoftTokenApp(in.readString()); + userCredential.setAbleToShare(in.readInt() != 0); + userCredential.setEapType(in.readInt()); + userCredential.setNonEapInnerMethod(in.readString()); return userCredential; } @@ -262,7 +335,13 @@ public final class Credential implements Parcelable { } }; } - public UserCredential userCredential = null; + private UserCredential mUserCredential = null; + public void setUserCredential(UserCredential userCredential) { + mUserCredential = userCredential; + } + public UserCredential getUserCredential() { + return mUserCredential; + } /** * Certificate based credential. This is used for EAP-TLS. @@ -282,12 +361,24 @@ public final class Credential implements Parcelable { /** * Certificate type. */ - public String certType = null; + private String mCertType = null; + public void setCertType(String certType) { + mCertType = certType; + } + public String getCertType() { + return mCertType; + } /** * The SHA-256 fingerprint of the certificate. */ - public byte[] certSha256FingerPrint = null; + private byte[] mCertSha256Fingerprint = null; + public void setCertSha256Fingerprint(byte[] certSha256Fingerprint) { + mCertSha256Fingerprint = certSha256Fingerprint; + } + public byte[] getCertSha256Fingerprint() { + return mCertSha256Fingerprint; + } /** * Constructor for creating CertificateCredential with default values. @@ -301,10 +392,10 @@ public final class Credential implements Parcelable { */ public CertificateCredential(CertificateCredential source) { if (source != null) { - certType = source.certType; - if (source.certSha256FingerPrint != null) { - certSha256FingerPrint = Arrays.copyOf(source.certSha256FingerPrint, - source.certSha256FingerPrint.length); + mCertType = source.mCertType; + if (source.mCertSha256Fingerprint != null) { + mCertSha256Fingerprint = Arrays.copyOf(source.mCertSha256Fingerprint, + source.mCertSha256Fingerprint.length); } } } @@ -316,8 +407,8 @@ public final class Credential implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeString(certType); - dest.writeByteArray(certSha256FingerPrint); + dest.writeString(mCertType); + dest.writeByteArray(mCertSha256Fingerprint); } @Override @@ -330,8 +421,13 @@ public final class Credential implements Parcelable { } CertificateCredential that = (CertificateCredential) thatObject; - return TextUtils.equals(certType, that.certType) - && Arrays.equals(certSha256FingerPrint, that.certSha256FingerPrint); + return TextUtils.equals(mCertType, that.mCertType) + && Arrays.equals(mCertSha256Fingerprint, that.mCertSha256Fingerprint); + } + + @Override + public int hashCode() { + return Objects.hash(mCertType, mCertSha256Fingerprint); } /** @@ -340,12 +436,12 @@ public final class Credential implements Parcelable { * @return true on success or false on failure */ public boolean validate() { - if (!TextUtils.equals(CERT_TYPE_X509V3, certType)) { - Log.d(TAG, "Unsupported certificate type: " + certType); + if (!TextUtils.equals(CERT_TYPE_X509V3, mCertType)) { + Log.d(TAG, "Unsupported certificate type: " + mCertType); return false; } - if (certSha256FingerPrint == null - || certSha256FingerPrint.length != CERT_SHA256_FINGER_PRINT_LENGTH) { + if (mCertSha256Fingerprint == null + || mCertSha256Fingerprint.length != CERT_SHA256_FINGER_PRINT_LENGTH) { Log.d(TAG, "Invalid SHA-256 fingerprint"); return false; } @@ -357,8 +453,8 @@ public final class Credential implements Parcelable { @Override public CertificateCredential createFromParcel(Parcel in) { CertificateCredential certCredential = new CertificateCredential(); - certCredential.certType = in.readString(); - certCredential.certSha256FingerPrint = in.createByteArray(); + certCredential.setCertType(in.readString()); + certCredential.setCertSha256Fingerprint(in.createByteArray()); return certCredential; } @@ -368,7 +464,13 @@ public final class Credential implements Parcelable { } }; } - public CertificateCredential certCredential = null; + private CertificateCredential mCertCredential = null; + public void setCertCredential(CertificateCredential certCredential) { + mCertCredential = certCredential; + } + public CertificateCredential getCertCredential() { + return mCertCredential; + } /** * SIM (Subscriber Identify Module) based credential. @@ -378,14 +480,20 @@ public final class Credential implements Parcelable { /** * Maximum string length for IMSI. */ - public static final int MAX_IMSI_LENGTH = 15; + private static final int MAX_IMSI_LENGTH = 15; /** * International Mobile Subscriber Identity, is used to identify the user * of a cellular network and is a unique identification associated with all * cellular networks */ - public String imsi = null; + private String mImsi = null; + public void setImsi(String imsi) { + mImsi = imsi; + } + public String getImsi() { + return mImsi; + } /** * EAP (Extensible Authentication Protocol) method type for using SIM credential. @@ -393,7 +501,13 @@ public final class Credential implements Parcelable { * for valid values. * Using Integer.MIN_VALUE to indicate unset value. */ - public int eapType = Integer.MIN_VALUE; + private int mEapType = Integer.MIN_VALUE; + public void setEapType(int eapType) { + mEapType = eapType; + } + public int getEapType() { + return mEapType; + } /** * Constructor for creating SimCredential with default values. @@ -407,8 +521,8 @@ public final class Credential implements Parcelable { */ public SimCredential(SimCredential source) { if (source != null) { - imsi = source.imsi; - eapType = source.eapType; + mImsi = source.mImsi; + mEapType = source.mEapType; } } @@ -427,14 +541,19 @@ public final class Credential implements Parcelable { } SimCredential that = (SimCredential) thatObject; - return TextUtils.equals(imsi, that.imsi) - && eapType == that.eapType; + return TextUtils.equals(mImsi, that.mImsi) + && mEapType == that.mEapType; + } + + @Override + public int hashCode() { + return Objects.hash(mImsi, mEapType); } @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeString(imsi); - dest.writeInt(eapType); + dest.writeString(mImsi); + dest.writeInt(mEapType); } /** @@ -449,9 +568,9 @@ public final class Credential implements Parcelable { if (!verifyImsi()) { return false; } - if (eapType != EAPConstants.EAP_SIM && eapType != EAPConstants.EAP_AKA - && eapType != EAPConstants.EAP_AKA_PRIME) { - Log.d(TAG, "Invalid EAP Type for SIM credential: " + eapType); + if (mEapType != EAPConstants.EAP_SIM && mEapType != EAPConstants.EAP_AKA + && mEapType != EAPConstants.EAP_AKA_PRIME) { + Log.d(TAG, "Invalid EAP Type for SIM credential: " + mEapType); return false; } return true; @@ -462,8 +581,8 @@ public final class Credential implements Parcelable { @Override public SimCredential createFromParcel(Parcel in) { SimCredential simCredential = new SimCredential(); - simCredential.imsi = in.readString(); - simCredential.eapType = in.readInt(); + simCredential.setImsi(in.readString()); + simCredential.setEapType(in.readInt()); return simCredential; } @@ -481,51 +600,75 @@ public final class Credential implements Parcelable { * @return true if IMSI is valid, false otherwise. */ private boolean verifyImsi() { - if (TextUtils.isEmpty(imsi)) { + if (TextUtils.isEmpty(mImsi)) { Log.d(TAG, "Missing IMSI"); return false; } - if (imsi.length() > MAX_IMSI_LENGTH) { - Log.d(TAG, "IMSI exceeding maximum length: " + imsi.length()); + if (mImsi.length() > MAX_IMSI_LENGTH) { + Log.d(TAG, "IMSI exceeding maximum length: " + mImsi.length()); return false; } // Locate the first non-digit character. int nonDigit; char stopChar = '\0'; - for (nonDigit = 0; nonDigit < imsi.length(); nonDigit++) { - stopChar = imsi.charAt(nonDigit); + for (nonDigit = 0; nonDigit < mImsi.length(); nonDigit++) { + stopChar = mImsi.charAt(nonDigit); if (stopChar < '0' || stopChar > '9') { break; } } - if (nonDigit == imsi.length()) { + if (nonDigit == mImsi.length()) { return true; } - else if (nonDigit == imsi.length()-1 && stopChar == '*') { + else if (nonDigit == mImsi.length()-1 && stopChar == '*') { // Prefix matching. return true; } return false; } } - public SimCredential simCredential = null; + private SimCredential mSimCredential = null; + public void setSimCredential(SimCredential simCredential) { + mSimCredential = simCredential; + } + public SimCredential getSimCredential() { + return mSimCredential; + } /** * CA (Certificate Authority) X509 certificate. */ - public X509Certificate caCertificate = null; + private X509Certificate mCaCertificate = null; + public void setCaCertificate(X509Certificate caCertificate) { + mCaCertificate = caCertificate; + } + public X509Certificate getCaCertificate() { + return mCaCertificate; + } /** * Client side X509 certificate chain. */ - public X509Certificate[] clientCertificateChain = null; + private X509Certificate[] mClientCertificateChain = null; + public void setClientCertificateChain(X509Certificate[] certificateChain) { + mClientCertificateChain = certificateChain; + } + public X509Certificate[] getClientCertificateChain() { + return mClientCertificateChain; + } /** * Client side private key. */ - public PrivateKey clientPrivateKey = null; + private PrivateKey mClientPrivateKey = null; + public void setClientPrivateKey(PrivateKey clientPrivateKey) { + mClientPrivateKey = clientPrivateKey; + } + public PrivateKey getClientPrivateKey() { + return mClientPrivateKey; + } /** * Constructor for creating Credential with default values. @@ -539,25 +682,25 @@ public final class Credential implements Parcelable { */ public Credential(Credential source) { if (source != null) { - creationTimeInMs = source.creationTimeInMs; - expirationTimeInMs = source.expirationTimeInMs; - realm = source.realm; - checkAAAServerCertStatus = source.checkAAAServerCertStatus; - if (source.userCredential != null) { - userCredential = new UserCredential(source.userCredential); + mCreationTimeInMs = source.mCreationTimeInMs; + mExpirationTimeInMs = source.mExpirationTimeInMs; + mRealm = source.mRealm; + mCheckAAAServerCertStatus = source.mCheckAAAServerCertStatus; + if (source.mUserCredential != null) { + mUserCredential = new UserCredential(source.mUserCredential); } - if (source.certCredential != null) { - certCredential = new CertificateCredential(source.certCredential); + if (source.mCertCredential != null) { + mCertCredential = new CertificateCredential(source.mCertCredential); } - if (source.simCredential != null) { - simCredential = new SimCredential(source.simCredential); + if (source.mSimCredential != null) { + mSimCredential = new SimCredential(source.mSimCredential); } - if (source.clientCertificateChain != null) { - clientCertificateChain = Arrays.copyOf(source.clientCertificateChain, - source.clientCertificateChain.length); + if (source.mClientCertificateChain != null) { + mClientCertificateChain = Arrays.copyOf(source.mClientCertificateChain, + source.mClientCertificateChain.length); } - caCertificate = source.caCertificate; - clientPrivateKey = source.clientPrivateKey; + mCaCertificate = source.mCaCertificate; + mClientPrivateKey = source.mClientPrivateKey; } } @@ -568,16 +711,16 @@ public final class Credential implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeLong(creationTimeInMs); - dest.writeLong(expirationTimeInMs); - dest.writeString(realm); - dest.writeInt(checkAAAServerCertStatus ? 1 : 0); - dest.writeParcelable(userCredential, flags); - dest.writeParcelable(certCredential, flags); - dest.writeParcelable(simCredential, flags); - ParcelUtil.writeCertificate(dest, caCertificate); - ParcelUtil.writeCertificates(dest, clientCertificateChain); - ParcelUtil.writePrivateKey(dest, clientPrivateKey); + dest.writeLong(mCreationTimeInMs); + dest.writeLong(mExpirationTimeInMs); + dest.writeString(mRealm); + dest.writeInt(mCheckAAAServerCertStatus ? 1 : 0); + dest.writeParcelable(mUserCredential, flags); + dest.writeParcelable(mCertCredential, flags); + dest.writeParcelable(mSimCredential, flags); + ParcelUtil.writeCertificate(dest, mCaCertificate); + ParcelUtil.writeCertificates(dest, mClientCertificateChain); + ParcelUtil.writePrivateKey(dest, mClientPrivateKey); } @Override @@ -590,19 +733,26 @@ public final class Credential implements Parcelable { } Credential that = (Credential) thatObject; - return TextUtils.equals(realm, that.realm) - && creationTimeInMs == that.creationTimeInMs - && expirationTimeInMs == that.expirationTimeInMs - && checkAAAServerCertStatus == that.checkAAAServerCertStatus - && (userCredential == null ? that.userCredential == null - : userCredential.equals(that.userCredential)) - && (certCredential == null ? that.certCredential == null - : certCredential.equals(that.certCredential)) - && (simCredential == null ? that.simCredential == null - : simCredential.equals(that.simCredential)) - && isX509CertificateEquals(caCertificate, that.caCertificate) - && isX509CertificatesEquals(clientCertificateChain, that.clientCertificateChain) - && isPrivateKeyEquals(clientPrivateKey, that.clientPrivateKey); + return TextUtils.equals(mRealm, that.mRealm) + && mCreationTimeInMs == that.mCreationTimeInMs + && mExpirationTimeInMs == that.mExpirationTimeInMs + && mCheckAAAServerCertStatus == that.mCheckAAAServerCertStatus + && (mUserCredential == null ? that.mUserCredential == null + : mUserCredential.equals(that.mUserCredential)) + && (mCertCredential == null ? that.mCertCredential == null + : mCertCredential.equals(that.mCertCredential)) + && (mSimCredential == null ? that.mSimCredential == null + : mSimCredential.equals(that.mSimCredential)) + && isX509CertificateEquals(mCaCertificate, that.mCaCertificate) + && isX509CertificatesEquals(mClientCertificateChain, that.mClientCertificateChain) + && isPrivateKeyEquals(mClientPrivateKey, that.mClientPrivateKey); + } + + @Override + public int hashCode() { + return Objects.hash(mRealm, mCreationTimeInMs, mExpirationTimeInMs, + mCheckAAAServerCertStatus, mUserCredential, mCertCredential, mSimCredential, + mCaCertificate, mClientCertificateChain, mClientPrivateKey); } /** @@ -611,26 +761,26 @@ public final class Credential implements Parcelable { * @return true on success or false on failure */ public boolean validate() { - if (TextUtils.isEmpty(realm)) { + if (TextUtils.isEmpty(mRealm)) { Log.d(TAG, "Missing realm"); return false; } - if (realm.getBytes(StandardCharsets.UTF_8).length > MAX_REALM_BYTES) { + if (mRealm.getBytes(StandardCharsets.UTF_8).length > MAX_REALM_BYTES) { Log.d(TAG, "realm exceeding maximum length: " - + realm.getBytes(StandardCharsets.UTF_8).length); + + mRealm.getBytes(StandardCharsets.UTF_8).length); return false; } // Verify the credential. - if (userCredential != null) { + if (mUserCredential != null) { if (!verifyUserCredential()) { return false; } - } else if (certCredential != null) { + } else if (mCertCredential != null) { if (!verifyCertCredential()) { return false; } - } else if (simCredential != null) { + } else if (mSimCredential != null) { if (!verifySimCredential()) { return false; } @@ -647,16 +797,16 @@ public final class Credential implements Parcelable { @Override public Credential createFromParcel(Parcel in) { Credential credential = new Credential(); - credential.creationTimeInMs = in.readLong(); - credential.expirationTimeInMs = in.readLong(); - credential.realm = in.readString(); - credential.checkAAAServerCertStatus = in.readInt() != 0; - credential.userCredential = in.readParcelable(null); - credential.certCredential = in.readParcelable(null); - credential.simCredential = in.readParcelable(null); - credential.caCertificate = ParcelUtil.readCertificate(in); - credential.clientCertificateChain = ParcelUtil.readCertificates(in); - credential.clientPrivateKey = ParcelUtil.readPrivateKey(in); + credential.setCreationTimeInMs(in.readLong()); + credential.setExpirationTimeInMs(in.readLong()); + credential.setRealm(in.readString()); + credential.setCheckAAAServerCertStatus(in.readInt() != 0); + credential.setUserCredential(in.readParcelable(null)); + credential.setCertCredential(in.readParcelable(null)); + credential.setSimCredential(in.readParcelable(null)); + credential.setCaCertificate(ParcelUtil.readCertificate(in)); + credential.setClientCertificateChain(ParcelUtil.readCertificates(in)); + credential.setClientPrivateKey(ParcelUtil.readPrivateKey(in)); return credential; } @@ -672,18 +822,18 @@ public final class Credential implements Parcelable { * @return true if user credential is valid, false otherwise. */ private boolean verifyUserCredential() { - if (userCredential == null) { + if (mUserCredential == null) { Log.d(TAG, "Missing user credential"); return false; } - if (certCredential != null || simCredential != null) { + if (mCertCredential != null || mSimCredential != null) { Log.d(TAG, "Contained more than one type of credential"); return false; } - if (!userCredential.validate()) { + if (!mUserCredential.validate()) { return false; } - if (caCertificate == null) { + if (mCaCertificate == null) { Log.d(TAG, "Missing CA Certificate for user credential"); return false; } @@ -697,32 +847,32 @@ public final class Credential implements Parcelable { * @return true if certificate credential is valid, false otherwise. */ private boolean verifyCertCredential() { - if (certCredential == null) { + if (mCertCredential == null) { Log.d(TAG, "Missing certificate credential"); return false; } - if (userCredential != null || simCredential != null) { + if (mUserCredential != null || mSimCredential != null) { Log.d(TAG, "Contained more than one type of credential"); return false; } - if (!certCredential.validate()) { + if (!mCertCredential.validate()) { return false; } // Verify required key and certificates for certificate credential. - if (caCertificate == null) { + if (mCaCertificate == null) { Log.d(TAG, "Missing CA Certificate for certificate credential"); return false; } - if (clientPrivateKey == null) { + if (mClientPrivateKey == null) { Log.d(TAG, "Missing client private key for certificate credential"); return false; } try { // Verify SHA-256 fingerprint for client certificate. - if (!verifySha256Fingerprint(clientCertificateChain, - certCredential.certSha256FingerPrint)) { + if (!verifySha256Fingerprint(mClientCertificateChain, + mCertCredential.getCertSha256Fingerprint())) { Log.d(TAG, "SHA-256 fingerprint mismatch"); return false; } @@ -740,15 +890,15 @@ public final class Credential implements Parcelable { * @return true if SIM credential is valid, false otherwise. */ private boolean verifySimCredential() { - if (simCredential == null) { + if (mSimCredential == null) { Log.d(TAG, "Missing SIM credential"); return false; } - if (userCredential != null || certCredential != null) { + if (mUserCredential != null || mCertCredential != null) { Log.d(TAG, "Contained more than one type of credential"); return false; } - return simCredential.validate(); + return mSimCredential.validate(); } private static boolean isPrivateKeyEquals(PrivateKey key1, PrivateKey key2) { diff --git a/wifi/java/android/net/wifi/hotspot2/pps/HomeSP.java b/wifi/java/android/net/wifi/hotspot2/pps/HomeSP.java index 4ddf21099751..8b3b79c861af 100644 --- a/wifi/java/android/net/wifi/hotspot2/pps/HomeSP.java +++ b/wifi/java/android/net/wifi/hotspot2/pps/HomeSP.java @@ -26,6 +26,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * Class representing HomeSP subtree in PerProviderSubscription (PPS) @@ -52,17 +53,35 @@ public final class HomeSP implements Parcelable { /** * FQDN (Fully Qualified Domain Name) of this home service provider. */ - public String fqdn = null; + private String mFqdn = null; + public void setFqdn(String fqdn) { + mFqdn = fqdn; + } + public String getFqdn() { + return mFqdn; + } /** * Friendly name of this home service provider. */ - public String friendlyName = null; + private String mFriendlyName = null; + public void setFriendlyName(String friendlyName) { + mFriendlyName = friendlyName; + } + public String getFriendlyName() { + return mFriendlyName; + } /** * Icon URL of this home service provider. */ - public String iconUrl = null; + private String mIconUrl = null; + public void setIconUrl(String iconUrl) { + mIconUrl = iconUrl; + } + public String getIconUrl() { + return mIconUrl; + } /** * <SSID, HESSID> duple of the networks that are consider home networks. @@ -71,7 +90,13 @@ public final class HomeSP implements Parcelable { * all nodes in the PSS MO are encoded using UTF-8 unless stated otherwise. Thus, the SSID * string is assumed to be encoded using UTF-8. */ - public Map<String, Long> homeNetworkIds = null; + private Map<String, Long> mHomeNetworkIds = null; + public void setHomeNetworkIds(Map<String, Long> homeNetworkIds) { + mHomeNetworkIds = homeNetworkIds; + } + public Map<String, Long> getHomeNetworkIds() { + return mHomeNetworkIds; + } /** * Used for determining if this provider is a member of a given Hotspot provider. @@ -83,7 +108,13 @@ public final class HomeSP implements Parcelable { * Refer to HomeSP/HomeOIList subtree in PerProviderSubscription (PPS) Management Object * (MO) tree for more detail. */ - public long[] matchAllOIs = null; + private long[] mMatchAllOIs = null; + public void setMatchAllOIs(long[] matchAllOIs) { + mMatchAllOIs = matchAllOIs; + } + public long[] getMatchAllOIs() { + return mMatchAllOIs; + } /** * Used for determining if this provider is a member of a given Hotspot provider. @@ -92,13 +123,19 @@ public final class HomeSP implements Parcelable { * of that Hotspot provider (e.g. successful authentication with such Hotspot * is possible). * - * {@link #matchAllOIs} will have precedence over this one, meaning this list will - * only be used for matching if {@link #matchAllOIs} is null or empty. + * {@link #mMatchAllOIs} will have precedence over this one, meaning this list will + * only be used for matching if {@link #mMatchAllOIs} is null or empty. * * Refer to HomeSP/HomeOIList subtree in PerProviderSubscription (PPS) Management Object * (MO) tree for more detail. */ - public long[] matchAnyOIs = null; + private long[] mMatchAnyOIs = null; + public void setMatchAnyOIs(long[] matchAnyOIs) { + mMatchAnyOIs = matchAnyOIs; + } + public long[] getMatchAnysOIs() { + return mMatchAnyOIs; + } /** * List of FQDN (Fully Qualified Domain Name) of partner providers. @@ -106,13 +143,25 @@ public final class HomeSP implements Parcelable { * This relationship is most likely achieved via a commercial agreement or * operator merges between the providers. */ - public String[] otherHomePartners = null; + private String[] mOtherHomePartners = null; + public void setOtherHomePartners(String[] otherHomePartners) { + mOtherHomePartners = otherHomePartners; + } + public String[] getOtherHomePartners() { + return mOtherHomePartners; + } /** * List of Organization Identifiers (OIs) identifying a roaming consortium of * which this provider is a member. */ - public long[] roamingConsortiumOIs = null; + private long[] mRoamingConsortiumOIs = null; + public void setRoamingConsortiumOIs(long[] roamingConsortiumOIs) { + mRoamingConsortiumOIs = roamingConsortiumOIs; + } + public long[] getRoamingConsortiumOIs() { + return mRoamingConsortiumOIs; + } /** * Constructor for creating HomeSP with default values. @@ -128,25 +177,25 @@ public final class HomeSP implements Parcelable { if (source == null) { return; } - fqdn = source.fqdn; - friendlyName = source.friendlyName; - iconUrl = source.iconUrl; - if (source.homeNetworkIds != null) { - homeNetworkIds = Collections.unmodifiableMap(source.homeNetworkIds); + mFqdn = source.mFqdn; + mFriendlyName = source.mFriendlyName; + mIconUrl = source.mIconUrl; + if (source.mHomeNetworkIds != null) { + mHomeNetworkIds = Collections.unmodifiableMap(source.mHomeNetworkIds); } - if (source.matchAllOIs != null) { - matchAllOIs = Arrays.copyOf(source.matchAllOIs, source.matchAllOIs.length); + if (source.mMatchAllOIs != null) { + mMatchAllOIs = Arrays.copyOf(source.mMatchAllOIs, source.mMatchAllOIs.length); } - if (source.matchAnyOIs != null) { - matchAnyOIs = Arrays.copyOf(source.matchAnyOIs, source.matchAnyOIs.length); + if (source.mMatchAnyOIs != null) { + mMatchAnyOIs = Arrays.copyOf(source.mMatchAnyOIs, source.mMatchAnyOIs.length); } - if (source.otherHomePartners != null) { - otherHomePartners = Arrays.copyOf(source.otherHomePartners, - source.otherHomePartners.length); + if (source.mOtherHomePartners != null) { + mOtherHomePartners = Arrays.copyOf(source.mOtherHomePartners, + source.mOtherHomePartners.length); } - if (source.roamingConsortiumOIs != null) { - roamingConsortiumOIs = Arrays.copyOf(source.roamingConsortiumOIs, - source.roamingConsortiumOIs.length); + if (source.mRoamingConsortiumOIs != null) { + mRoamingConsortiumOIs = Arrays.copyOf(source.mRoamingConsortiumOIs, + source.mRoamingConsortiumOIs.length); } } @@ -157,14 +206,14 @@ public final class HomeSP implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeString(fqdn); - dest.writeString(friendlyName); - dest.writeString(iconUrl); - writeHomeNetworkIds(dest, homeNetworkIds); - dest.writeLongArray(matchAllOIs); - dest.writeLongArray(matchAnyOIs); - dest.writeStringArray(otherHomePartners); - dest.writeLongArray(roamingConsortiumOIs); + dest.writeString(mFqdn); + dest.writeString(mFriendlyName); + dest.writeString(mIconUrl); + writeHomeNetworkIds(dest, mHomeNetworkIds); + dest.writeLongArray(mMatchAllOIs); + dest.writeLongArray(mMatchAnyOIs); + dest.writeStringArray(mOtherHomePartners); + dest.writeLongArray(mRoamingConsortiumOIs); } @Override @@ -177,15 +226,21 @@ public final class HomeSP implements Parcelable { } HomeSP that = (HomeSP) thatObject; - return TextUtils.equals(fqdn, that.fqdn) - && TextUtils.equals(friendlyName, that.friendlyName) - && TextUtils.equals(iconUrl, that.iconUrl) - && (homeNetworkIds == null ? that.homeNetworkIds == null - : homeNetworkIds.equals(that.homeNetworkIds)) - && Arrays.equals(matchAllOIs, that.matchAllOIs) - && Arrays.equals(matchAnyOIs, that.matchAnyOIs) - && Arrays.equals(otherHomePartners, that.otherHomePartners) - && Arrays.equals(roamingConsortiumOIs, that.roamingConsortiumOIs); + return TextUtils.equals(mFqdn, that.mFqdn) + && TextUtils.equals(mFriendlyName, that.mFriendlyName) + && TextUtils.equals(mIconUrl, that.mIconUrl) + && (mHomeNetworkIds == null ? that.mHomeNetworkIds == null + : mHomeNetworkIds.equals(that.mHomeNetworkIds)) + && Arrays.equals(mMatchAllOIs, that.mMatchAllOIs) + && Arrays.equals(mMatchAnyOIs, that.mMatchAnyOIs) + && Arrays.equals(mOtherHomePartners, that.mOtherHomePartners) + && Arrays.equals(mRoamingConsortiumOIs, that.mRoamingConsortiumOIs); + } + + @Override + public int hashCode() { + return Objects.hash(mFqdn, mFriendlyName, mIconUrl, mHomeNetworkIds, mMatchAllOIs, + mMatchAnyOIs, mOtherHomePartners, mRoamingConsortiumOIs); } /** @@ -194,17 +249,17 @@ public final class HomeSP implements Parcelable { * @return true on success or false on failure */ public boolean validate() { - if (TextUtils.isEmpty(fqdn)) { + if (TextUtils.isEmpty(mFqdn)) { Log.d(TAG, "Missing FQDN"); return false; } - if (TextUtils.isEmpty(friendlyName)) { + if (TextUtils.isEmpty(mFriendlyName)) { Log.d(TAG, "Missing friendly name"); return false; } // Verify SSIDs specified in the NetworkID - if (homeNetworkIds != null) { - for (Map.Entry<String, Long> entry : homeNetworkIds.entrySet()) { + if (mHomeNetworkIds != null) { + for (Map.Entry<String, Long> entry : mHomeNetworkIds.entrySet()) { if (entry.getKey() == null || entry.getKey().getBytes(StandardCharsets.UTF_8).length > MAX_SSID_BYTES) { Log.d(TAG, "Invalid SSID in HomeNetworkIDs"); @@ -220,14 +275,14 @@ public final class HomeSP implements Parcelable { @Override public HomeSP createFromParcel(Parcel in) { HomeSP homeSp = new HomeSP(); - homeSp.fqdn = in.readString(); - homeSp.friendlyName = in.readString(); - homeSp.iconUrl = in.readString(); - homeSp.homeNetworkIds = readHomeNetworkIds(in); - homeSp.matchAllOIs = in.createLongArray(); - homeSp.matchAnyOIs = in.createLongArray(); - homeSp.otherHomePartners = in.createStringArray(); - homeSp.roamingConsortiumOIs = in.createLongArray(); + homeSp.setFqdn(in.readString()); + homeSp.setFriendlyName(in.readString()); + homeSp.setIconUrl(in.readString()); + homeSp.setHomeNetworkIds(readHomeNetworkIds(in)); + homeSp.setMatchAllOIs(in.createLongArray()); + homeSp.setMatchAnyOIs(in.createLongArray()); + homeSp.setOtherHomePartners(in.createStringArray()); + homeSp.setRoamingConsortiumOIs(in.createLongArray()); return homeSp; } diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Policy.java b/wifi/java/android/net/wifi/hotspot2/pps/Policy.java index bc294025c142..ceaada4173de 100644 --- a/wifi/java/android/net/wifi/hotspot2/pps/Policy.java +++ b/wifi/java/android/net/wifi/hotspot2/pps/Policy.java @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; /** * Class representing Policy subtree in PerProviderSubscription (PPS) @@ -79,8 +80,20 @@ public final class Policy implements Parcelable { * * Using Long.MIN_VALUE to indicate unset value. */ - public long minHomeDownlinkBandwidth = Long.MIN_VALUE; - public long minHomeUplinkBandwidth = Long.MIN_VALUE; + private long mMinHomeDownlinkBandwidth = Long.MIN_VALUE; + public void setMinHomeDownlinkBandwidth(long minHomeDownlinkBandwidth) { + mMinHomeDownlinkBandwidth = minHomeDownlinkBandwidth; + } + public long getMinHomeDownlinkBandWidht() { + return mMinHomeDownlinkBandwidth; + } + private long mMinHomeUplinkBandwidth = Long.MIN_VALUE; + public void setMinHomeUplinkBandwidth(long minHomeUplinkBandwidth) { + mMinHomeUplinkBandwidth = minHomeUplinkBandwidth; + } + public long getMinHomeUplinkBandwidth() { + return mMinHomeUplinkBandwidth; + } /** * Minimum available downlink/uplink bandwidth (in kilobits per second) required when @@ -91,26 +104,56 @@ public final class Policy implements Parcelable { * * Using Long.MIN_VALUE to indicate unset value. */ - public long minRoamingDownlinkBandwidth = Long.MIN_VALUE; - public long minRoamingUplinkBandwidth = Long.MIN_VALUE; + private long mMinRoamingDownlinkBandwidth = Long.MIN_VALUE; + public void setMinRoamingDownlinkBandwidth(long minRoamingDownlinkBandwidth) { + mMinRoamingDownlinkBandwidth = minRoamingDownlinkBandwidth; + } + public long getMinRoamingDownlinkBandwidth() { + return mMinRoamingDownlinkBandwidth; + } + private long mMinRoamingUplinkBandwidth = Long.MIN_VALUE; + public void setMinRoamingUplinkBandwidth(long minRoamingUplinkBandwidth) { + mMinRoamingUplinkBandwidth = minRoamingUplinkBandwidth; + } + public long getMinRoamingUplinkBandwidth() { + return mMinRoamingUplinkBandwidth; + } /** * List of SSIDs that are not preferred by the Home SP. */ - public String[] excludedSsidList = null; + private String[] mExcludedSsidList = null; + public void setExcludedSsidList(String[] excludedSsidList) { + mExcludedSsidList = excludedSsidList; + } + public String[] getExcludedSsidList() { + return mExcludedSsidList; + } /** * List of IP protocol and port number required by one or more operator supported application. * The port string contained one or more port numbers delimited by ",". */ - public Map<Integer, String> requiredProtoPortMap = null; + private Map<Integer, String> mRequiredProtoPortMap = null; + public void setRequiredProtoPortMap(Map<Integer, String> requiredProtoPortMap) { + mRequiredProtoPortMap = requiredProtoPortMap; + } + public Map<Integer, String> getRequiredProtoPortMap() { + return mRequiredProtoPortMap; + } /** * This specifies the maximum acceptable BSS load policy. This is used to prevent device * from joining an AP whose channel is overly congested with traffic. * Using Integer.MIN_VALUE to indicate unset value. */ - public int maximumBssLoadValue = Integer.MIN_VALUE; + private int mMaximumBssLoadValue = Integer.MIN_VALUE; + public void setMaximumBssLoadValue(int maximumBssLoadValue) { + mMaximumBssLoadValue = maximumBssLoadValue; + } + public int getMaximumBssLoadValue() { + return mMaximumBssLoadValue; + } /** * Policy associated with a roaming provider. This specifies a priority associated @@ -122,7 +165,13 @@ public final class Policy implements Parcelable { /** * FQDN of the roaming partner. */ - public String fqdn = null; + private String mFqdn = null; + public void setFqdn(String fqdn) { + mFqdn = fqdn; + } + public String getFqdn() { + return mFqdn; + } /** * Flag indicating the exact match of FQDN is required for FQDN matching. @@ -130,27 +179,45 @@ public final class Policy implements Parcelable { * When this flag is set to false, sub-domain matching is used. For example, when * {@link #fqdn} s set to "example.com", "host.example.com" would be a match. */ - public boolean fqdnExactMatch = false; + private boolean mFqdnExactMatch = false; + public void setFqdnExactMatch(boolean fqdnExactMatch) { + mFqdnExactMatch = fqdnExactMatch; + } + public boolean getFqdnExactMatch() { + return mFqdnExactMatch; + } /** * Priority associated with this roaming partner policy. */ - public int priority = PREFERRED_ROAMING_PARTNER_DEFAULT_PRIORITY; + private int mPriority = PREFERRED_ROAMING_PARTNER_DEFAULT_PRIORITY; + public void setPriority(int priority) { + mPriority = priority; + } + public int getPriority() { + return mPriority; + } /** * A string contained One or more, comma delimited (i.e., ",") ISO/IEC 3166-1 two * character country strings or the country-independent value, "*". */ - public String countries = null; + private String mCountries = null; + public void setCountries(String countries) { + mCountries = countries; + } + public String getCountries() { + return mCountries; + } public RoamingPartner() {} public RoamingPartner(RoamingPartner source) { if (source != null) { - fqdn = source.fqdn; - fqdnExactMatch = source.fqdnExactMatch; - priority = source.priority; - countries = source.countries; + mFqdn = source.mFqdn; + mFqdnExactMatch = source.mFqdnExactMatch; + mPriority = source.mPriority; + mCountries = source.mCountries; } } @@ -161,10 +228,10 @@ public final class Policy implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeString(fqdn); - dest.writeInt(fqdnExactMatch ? 1 : 0); - dest.writeInt(priority); - dest.writeString(countries); + dest.writeString(mFqdn); + dest.writeInt(mFqdnExactMatch ? 1 : 0); + dest.writeInt(mPriority); + dest.writeString(mCountries); } @Override @@ -177,10 +244,15 @@ public final class Policy implements Parcelable { } RoamingPartner that = (RoamingPartner) thatObject; - return TextUtils.equals(fqdn, that.fqdn) - && fqdnExactMatch == that.fqdnExactMatch - && priority == that.priority - && TextUtils.equals(countries, that.countries); + return TextUtils.equals(mFqdn, that.mFqdn) + && mFqdnExactMatch == that.mFqdnExactMatch + && mPriority == that.mPriority + && TextUtils.equals(mCountries, that.mCountries); + } + + @Override + public int hashCode() { + return Objects.hash(mFqdn, mFqdnExactMatch, mPriority, mCountries); } /** @@ -189,11 +261,11 @@ public final class Policy implements Parcelable { * @return true on success */ public boolean validate() { - if (TextUtils.isEmpty(fqdn)) { + if (TextUtils.isEmpty(mFqdn)) { Log.d(TAG, "Missing FQDN"); return false; } - if (TextUtils.isEmpty(countries)) { + if (TextUtils.isEmpty(mCountries)) { Log.d(TAG, "Missing countries"); return false; } @@ -205,10 +277,10 @@ public final class Policy implements Parcelable { @Override public RoamingPartner createFromParcel(Parcel in) { RoamingPartner roamingPartner = new RoamingPartner(); - roamingPartner.fqdn = in.readString(); - roamingPartner.fqdnExactMatch = in.readInt() != 0; - roamingPartner.priority = in.readInt(); - roamingPartner.countries = in.readString(); + roamingPartner.setFqdn(in.readString()); + roamingPartner.setFqdnExactMatch(in.readInt() != 0); + roamingPartner.setPriority(in.readInt()); + roamingPartner.setCountries(in.readString()); return roamingPartner; } @@ -218,12 +290,24 @@ public final class Policy implements Parcelable { } }; } - public List<RoamingPartner> preferredRoamingPartnerList = null; + private List<RoamingPartner> mPreferredRoamingPartnerList = null; + public void setPreferredRoamingPartnerList(List<RoamingPartner> partnerList) { + mPreferredRoamingPartnerList = partnerList; + } + public List<RoamingPartner> getPreferredRoamingPartnerList() { + return mPreferredRoamingPartnerList; + } /** * Meta data used for policy update. */ - public UpdateParameter policyUpdate = null; + private UpdateParameter mPolicyUpdate = null; + public void setPolicyUpdate(UpdateParameter policyUpdate) { + mPolicyUpdate = policyUpdate; + } + public UpdateParameter getPolicyUpdate() { + return mPolicyUpdate; + } /** * Constructor for creating Policy with default values. @@ -239,24 +323,24 @@ public final class Policy implements Parcelable { if (source == null) { return; } - minHomeDownlinkBandwidth = source.minHomeDownlinkBandwidth; - minHomeUplinkBandwidth = source.minHomeUplinkBandwidth; - minRoamingDownlinkBandwidth = source.minRoamingDownlinkBandwidth; - minRoamingUplinkBandwidth = source.minRoamingUplinkBandwidth; - maximumBssLoadValue = source.maximumBssLoadValue; - if (source.excludedSsidList != null) { - excludedSsidList = Arrays.copyOf(source.excludedSsidList, - source.excludedSsidList.length); + mMinHomeDownlinkBandwidth = source.mMinHomeDownlinkBandwidth; + mMinHomeUplinkBandwidth = source.mMinHomeUplinkBandwidth; + mMinRoamingDownlinkBandwidth = source.mMinRoamingDownlinkBandwidth; + mMinRoamingUplinkBandwidth = source.mMinRoamingUplinkBandwidth; + mMaximumBssLoadValue = source.mMaximumBssLoadValue; + if (source.mExcludedSsidList != null) { + mExcludedSsidList = Arrays.copyOf(source.mExcludedSsidList, + source.mExcludedSsidList.length); } - if (source.requiredProtoPortMap != null) { - requiredProtoPortMap = Collections.unmodifiableMap(source.requiredProtoPortMap); + if (source.mRequiredProtoPortMap != null) { + mRequiredProtoPortMap = Collections.unmodifiableMap(source.mRequiredProtoPortMap); } - if (source.preferredRoamingPartnerList != null) { - preferredRoamingPartnerList = Collections.unmodifiableList( - source.preferredRoamingPartnerList); + if (source.mPreferredRoamingPartnerList != null) { + mPreferredRoamingPartnerList = Collections.unmodifiableList( + source.mPreferredRoamingPartnerList); } - if (source.policyUpdate != null) { - policyUpdate = new UpdateParameter(source.policyUpdate); + if (source.mPolicyUpdate != null) { + mPolicyUpdate = new UpdateParameter(source.mPolicyUpdate); } } @@ -267,15 +351,15 @@ public final class Policy implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeLong(minHomeDownlinkBandwidth); - dest.writeLong(minHomeUplinkBandwidth); - dest.writeLong(minRoamingDownlinkBandwidth); - dest.writeLong(minRoamingUplinkBandwidth); - dest.writeStringArray(excludedSsidList); - writeProtoPortMap(dest, requiredProtoPortMap); - dest.writeInt(maximumBssLoadValue); - writeRoamingPartnerList(dest, flags, preferredRoamingPartnerList); - dest.writeParcelable(policyUpdate, flags); + dest.writeLong(mMinHomeDownlinkBandwidth); + dest.writeLong(mMinHomeUplinkBandwidth); + dest.writeLong(mMinRoamingDownlinkBandwidth); + dest.writeLong(mMinRoamingUplinkBandwidth); + dest.writeStringArray(mExcludedSsidList); + writeProtoPortMap(dest, mRequiredProtoPortMap); + dest.writeInt(mMaximumBssLoadValue); + writeRoamingPartnerList(dest, flags, mPreferredRoamingPartnerList); + dest.writeParcelable(mPolicyUpdate, flags); } @Override @@ -288,18 +372,27 @@ public final class Policy implements Parcelable { } Policy that = (Policy) thatObject; - return minHomeDownlinkBandwidth == that.minHomeDownlinkBandwidth - && minHomeUplinkBandwidth == that.minHomeUplinkBandwidth - && minRoamingDownlinkBandwidth == that.minRoamingDownlinkBandwidth - && minRoamingUplinkBandwidth == that.minRoamingUplinkBandwidth - && Arrays.equals(excludedSsidList, that.excludedSsidList) - && (requiredProtoPortMap == null ? that.requiredProtoPortMap == null - : requiredProtoPortMap.equals(that.requiredProtoPortMap)) - && maximumBssLoadValue == that.maximumBssLoadValue - && (preferredRoamingPartnerList == null ? that.preferredRoamingPartnerList == null - : preferredRoamingPartnerList.equals(that.preferredRoamingPartnerList)) - && (policyUpdate == null ? that.policyUpdate == null - : policyUpdate.equals(that.policyUpdate)); + return mMinHomeDownlinkBandwidth == that.mMinHomeDownlinkBandwidth + && mMinHomeUplinkBandwidth == that.mMinHomeUplinkBandwidth + && mMinRoamingDownlinkBandwidth == that.mMinRoamingDownlinkBandwidth + && mMinRoamingUplinkBandwidth == that.mMinRoamingUplinkBandwidth + && Arrays.equals(mExcludedSsidList, that.mExcludedSsidList) + && (mRequiredProtoPortMap == null ? that.mRequiredProtoPortMap == null + : mRequiredProtoPortMap.equals(that.mRequiredProtoPortMap)) + && mMaximumBssLoadValue == that.mMaximumBssLoadValue + && (mPreferredRoamingPartnerList == null + ? that.mPreferredRoamingPartnerList == null + : mPreferredRoamingPartnerList.equals(that.mPreferredRoamingPartnerList)) + && (mPolicyUpdate == null ? that.mPolicyUpdate == null + : mPolicyUpdate.equals(that.mPolicyUpdate)); + } + + @Override + public int hashCode() { + return Objects.hash(mMinHomeDownlinkBandwidth, mMinHomeUplinkBandwidth, + mMinRoamingDownlinkBandwidth, mMinRoamingUplinkBandwidth, mExcludedSsidList, + mRequiredProtoPortMap, mMaximumBssLoadValue, mPreferredRoamingPartnerList, + mPolicyUpdate); } /** @@ -308,22 +401,22 @@ public final class Policy implements Parcelable { * @return true on success */ public boolean validate() { - if (policyUpdate == null) { + if (mPolicyUpdate == null) { Log.d(TAG, "PolicyUpdate not specified"); return false; } - if (!policyUpdate.validate()) { + if (!mPolicyUpdate.validate()) { return false; } // Validate SSID exclusion list. - if (excludedSsidList != null) { - if (excludedSsidList.length > MAX_EXCLUSION_SSIDS) { + if (mExcludedSsidList != null) { + if (mExcludedSsidList.length > MAX_EXCLUSION_SSIDS) { Log.d(TAG, "SSID exclusion list size exceeded the max: " - + excludedSsidList.length); + + mExcludedSsidList.length); return false; } - for (String ssid : excludedSsidList) { + for (String ssid : mExcludedSsidList) { if (ssid.getBytes(StandardCharsets.UTF_8).length > MAX_SSID_BYTES) { Log.d(TAG, "Invalid SSID: " + ssid); return false; @@ -331,8 +424,8 @@ public final class Policy implements Parcelable { } } // Validate required protocol to port map. - if (requiredProtoPortMap != null) { - for (Map.Entry<Integer, String> entry : requiredProtoPortMap.entrySet()) { + if (mRequiredProtoPortMap != null) { + for (Map.Entry<Integer, String> entry : mRequiredProtoPortMap.entrySet()) { String portNumber = entry.getValue(); if (portNumber.getBytes(StandardCharsets.UTF_8).length > MAX_PORT_STRING_BYTES) { Log.d(TAG, "PortNumber string bytes exceeded the max: " + portNumber); @@ -341,8 +434,8 @@ public final class Policy implements Parcelable { } } // Validate preferred roaming partner list. - if (preferredRoamingPartnerList != null) { - for (RoamingPartner partner : preferredRoamingPartnerList) { + if (mPreferredRoamingPartnerList != null) { + for (RoamingPartner partner : mPreferredRoamingPartnerList) { if (!partner.validate()) { return false; } @@ -356,15 +449,15 @@ public final class Policy implements Parcelable { @Override public Policy createFromParcel(Parcel in) { Policy policy = new Policy(); - policy.minHomeDownlinkBandwidth = in.readLong(); - policy.minHomeUplinkBandwidth = in.readLong(); - policy.minRoamingDownlinkBandwidth = in.readLong(); - policy.minRoamingUplinkBandwidth = in.readLong(); - policy.excludedSsidList = in.createStringArray(); - policy.requiredProtoPortMap = readProtoPortMap(in); - policy.maximumBssLoadValue = in.readInt(); - policy.preferredRoamingPartnerList = readRoamingPartnerList(in); - policy.policyUpdate = in.readParcelable(null); + policy.setMinHomeDownlinkBandwidth(in.readLong()); + policy.setMinHomeUplinkBandwidth(in.readLong()); + policy.setMinRoamingDownlinkBandwidth(in.readLong()); + policy.setMinRoamingUplinkBandwidth(in.readLong()); + policy.setExcludedSsidList(in.createStringArray()); + policy.setRequiredProtoPortMap(readProtoPortMap(in)); + policy.setMaximumBssLoadValue(in.readInt()); + policy.setPreferredRoamingPartnerList(readRoamingPartnerList(in)); + policy.setPolicyUpdate(in.readParcelable(null)); return policy; } diff --git a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java index a390df72f061..17fbf9f0888c 100644 --- a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java +++ b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java @@ -24,6 +24,7 @@ import android.util.Log; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Objects; /** * Class representing configuration parameters for subscription or policy update in @@ -88,45 +89,93 @@ public final class UpdateParameter implements Parcelable { * * Using Long.MIN_VALUE to indicate unset value. */ - public long updateIntervalInMinutes = Long.MIN_VALUE; + private long mUpdateIntervalInMinutes = Long.MIN_VALUE; + public void setUpdateIntervalInMinutes(long updateIntervalInMinutes) { + mUpdateIntervalInMinutes = updateIntervalInMinutes; + } + public long getUpdateIntervalInMinutes() { + return mUpdateIntervalInMinutes; + } /** * The method used to update the policy. Permitted values are "OMA-DM-ClientInitiated" * and "SPP-ClientInitiated". */ - public String updateMethod = null; + private String mUpdateMethod = null; + public void setUpdateMethod(String updateMethod) { + mUpdateMethod = updateMethod; + } + public String getUpdateMethod() { + return mUpdateMethod; + } /** * This specifies the hotspots at which the subscription update is permitted. Permitted * values are "HomeSP", "RoamingPartner", or "Unrestricted"; */ - public String restriction = null; + private String mRestriction = null; + public void setRestriction(String restriction) { + mRestriction = restriction; + } + public String getRestriction() { + return mRestriction; + } /** * The URI of the update server. */ - public String serverUri = null; + private String mServerUri = null; + public void setServerUri(String serverUri) { + mServerUri = serverUri; + } + public String getServerUri() { + return mServerUri; + } /** * Username used to authenticate with the policy server. */ - public String username = null; + private String mUsername = null; + public void setUsername(String username) { + mUsername = username; + } + public String getUsername() { + return mUsername; + } /** * Base64 encoded password used to authenticate with the policy server. */ - public String base64EncodedPassword = null; + private String mBase64EncodedPassword = null; + public void setBase64EncodedPassword(String password) { + mBase64EncodedPassword = password; + } + public String getBase64EncodedPassword() { + return mBase64EncodedPassword; + } /** * HTTPS URL for retrieving certificate for trust root. The trust root is used to validate * policy server's identity. */ - public String trustRootCertUrl = null; + private String mTrustRootCertUrl = null; + public void setTrustRootCertUrl(String trustRootCertUrl) { + mTrustRootCertUrl = trustRootCertUrl; + } + public String getTrustRootCertUrl() { + return mTrustRootCertUrl; + } /** * SHA-256 fingerprint of the certificate located at {@link #trustRootCertUrl} */ - public byte[] trustRootCertSha256Fingerprint = null; + private byte[] mTrustRootCertSha256Fingerprint = null; + public void setTrustRootCertSha256Fingerprint(byte[] fingerprint) { + mTrustRootCertSha256Fingerprint = fingerprint; + } + public byte[] getTrustRootCertSha256Fingerprint() { + return mTrustRootCertSha256Fingerprint; + } /** * Constructor for creating Policy with default values. @@ -142,16 +191,16 @@ public final class UpdateParameter implements Parcelable { if (source == null) { return; } - updateIntervalInMinutes = source.updateIntervalInMinutes; - updateMethod = source.updateMethod; - restriction = source.restriction; - serverUri = source.serverUri; - username = source.username; - base64EncodedPassword = source.base64EncodedPassword; - trustRootCertUrl = source.trustRootCertUrl; - if (source.trustRootCertSha256Fingerprint != null) { - trustRootCertSha256Fingerprint = Arrays.copyOf(source.trustRootCertSha256Fingerprint, - source.trustRootCertSha256Fingerprint.length); + mUpdateIntervalInMinutes = source.mUpdateIntervalInMinutes; + mUpdateMethod = source.mUpdateMethod; + mRestriction = source.mRestriction; + mServerUri = source.mServerUri; + mUsername = source.mUsername; + mBase64EncodedPassword = source.mBase64EncodedPassword; + mTrustRootCertUrl = source.mTrustRootCertUrl; + if (source.mTrustRootCertSha256Fingerprint != null) { + mTrustRootCertSha256Fingerprint = Arrays.copyOf(source.mTrustRootCertSha256Fingerprint, + source.mTrustRootCertSha256Fingerprint.length); } } @@ -162,14 +211,14 @@ public final class UpdateParameter implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeLong(updateIntervalInMinutes); - dest.writeString(updateMethod); - dest.writeString(restriction); - dest.writeString(serverUri); - dest.writeString(username); - dest.writeString(base64EncodedPassword); - dest.writeString(trustRootCertUrl); - dest.writeByteArray(trustRootCertSha256Fingerprint); + dest.writeLong(mUpdateIntervalInMinutes); + dest.writeString(mUpdateMethod); + dest.writeString(mRestriction); + dest.writeString(mServerUri); + dest.writeString(mUsername); + dest.writeString(mBase64EncodedPassword); + dest.writeString(mTrustRootCertUrl); + dest.writeByteArray(mTrustRootCertSha256Fingerprint); } @Override @@ -182,15 +231,22 @@ public final class UpdateParameter implements Parcelable { } UpdateParameter that = (UpdateParameter) thatObject; - return updateIntervalInMinutes == that.updateIntervalInMinutes - && TextUtils.equals(updateMethod, that.updateMethod) - && TextUtils.equals(restriction, that.restriction) - && TextUtils.equals(serverUri, that.serverUri) - && TextUtils.equals(username, that.username) - && TextUtils.equals(base64EncodedPassword, that.base64EncodedPassword) - && TextUtils.equals(trustRootCertUrl, that.trustRootCertUrl) - && Arrays.equals(trustRootCertSha256Fingerprint, - that.trustRootCertSha256Fingerprint); + return mUpdateIntervalInMinutes == that.mUpdateIntervalInMinutes + && TextUtils.equals(mUpdateMethod, that.mUpdateMethod) + && TextUtils.equals(mRestriction, that.mRestriction) + && TextUtils.equals(mServerUri, that.mServerUri) + && TextUtils.equals(mUsername, that.mUsername) + && TextUtils.equals(mBase64EncodedPassword, that.mBase64EncodedPassword) + && TextUtils.equals(mTrustRootCertUrl, that.mTrustRootCertUrl) + && Arrays.equals(mTrustRootCertSha256Fingerprint, + that.mTrustRootCertSha256Fingerprint); + } + + @Override + public int hashCode() { + return Objects.hash(mUpdateIntervalInMinutes, mUpdateMethod, mRestriction, mServerUri, + mUsername, mBase64EncodedPassword, mTrustRootCertUrl, + mTrustRootCertSha256Fingerprint); } /** @@ -199,81 +255,81 @@ public final class UpdateParameter implements Parcelable { * @return true on success */ public boolean validate() { - if (updateIntervalInMinutes == Long.MIN_VALUE) { + if (mUpdateIntervalInMinutes == Long.MIN_VALUE) { Log.d(TAG, "Update interval not specified"); return false; } // Update not applicable. - if (updateIntervalInMinutes == UPDATE_CHECK_INTERVAL_NEVER) { + if (mUpdateIntervalInMinutes == UPDATE_CHECK_INTERVAL_NEVER) { return true; } - if (!TextUtils.equals(updateMethod, UPDATE_METHOD_OMADM) - && !TextUtils.equals(updateMethod, UPDATE_METHOD_SSP)) { - Log.d(TAG, "Unknown update method: " + updateMethod); + if (!TextUtils.equals(mUpdateMethod, UPDATE_METHOD_OMADM) + && !TextUtils.equals(mUpdateMethod, UPDATE_METHOD_SSP)) { + Log.d(TAG, "Unknown update method: " + mUpdateMethod); return false; } - if (!TextUtils.equals(restriction, UPDATE_RESTRICTION_HOMESP) - && !TextUtils.equals(restriction, UPDATE_RESTRICTION_ROAMING_PARTNER) - && !TextUtils.equals(restriction, UPDATE_RESTRICTION_UNRESTRICTED)) { - Log.d(TAG, "Unknown restriction: " + restriction); + if (!TextUtils.equals(mRestriction, UPDATE_RESTRICTION_HOMESP) + && !TextUtils.equals(mRestriction, UPDATE_RESTRICTION_ROAMING_PARTNER) + && !TextUtils.equals(mRestriction, UPDATE_RESTRICTION_UNRESTRICTED)) { + Log.d(TAG, "Unknown restriction: " + mRestriction); return false; } - if (TextUtils.isEmpty(serverUri)) { + if (TextUtils.isEmpty(mServerUri)) { Log.d(TAG, "Missing update server URI"); return false; } - if (serverUri.getBytes(StandardCharsets.UTF_8).length > MAX_URI_BYTES) { + if (mServerUri.getBytes(StandardCharsets.UTF_8).length > MAX_URI_BYTES) { Log.d(TAG, "URI bytes exceeded the max: " - + serverUri.getBytes(StandardCharsets.UTF_8).length); + + mServerUri.getBytes(StandardCharsets.UTF_8).length); return false; } - if (TextUtils.isEmpty(username)) { + if (TextUtils.isEmpty(mUsername)) { Log.d(TAG, "Missing username"); return false; } - if (username.getBytes(StandardCharsets.UTF_8).length > MAX_USERNAME_BYTES) { + if (mUsername.getBytes(StandardCharsets.UTF_8).length > MAX_USERNAME_BYTES) { Log.d(TAG, "Username bytes exceeded the max: " - + username.getBytes(StandardCharsets.UTF_8).length); + + mUsername.getBytes(StandardCharsets.UTF_8).length); return false; } - if (TextUtils.isEmpty(base64EncodedPassword)) { + if (TextUtils.isEmpty(mBase64EncodedPassword)) { Log.d(TAG, "Missing username"); return false; } - if (base64EncodedPassword.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) { + if (mBase64EncodedPassword.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) { Log.d(TAG, "Password bytes exceeded the max: " - + base64EncodedPassword.getBytes(StandardCharsets.UTF_8).length); + + mBase64EncodedPassword.getBytes(StandardCharsets.UTF_8).length); return false; } try { - Base64.decode(base64EncodedPassword, Base64.DEFAULT); + Base64.decode(mBase64EncodedPassword, Base64.DEFAULT); } catch (IllegalArgumentException e) { - Log.d(TAG, "Invalid encoding for password: " + base64EncodedPassword); + Log.d(TAG, "Invalid encoding for password: " + mBase64EncodedPassword); return false; } - if (TextUtils.isEmpty(trustRootCertUrl)) { + if (TextUtils.isEmpty(mTrustRootCertUrl)) { Log.d(TAG, "Missing trust root certificate URL"); return false; } - if (trustRootCertUrl.getBytes(StandardCharsets.UTF_8).length > MAX_URL_BYTES) { + if (mTrustRootCertUrl.getBytes(StandardCharsets.UTF_8).length > MAX_URL_BYTES) { Log.d(TAG, "Trust root cert URL bytes exceeded the max: " - + trustRootCertUrl.getBytes(StandardCharsets.UTF_8).length); + + mTrustRootCertUrl.getBytes(StandardCharsets.UTF_8).length); return false; } - if (trustRootCertSha256Fingerprint == null) { + if (mTrustRootCertSha256Fingerprint == null) { Log.d(TAG, "Missing trust root certificate SHA-256 fingerprint"); return false; } - if (trustRootCertSha256Fingerprint.length != CERTIFICATE_SHA256_BYTES) { + if (mTrustRootCertSha256Fingerprint.length != CERTIFICATE_SHA256_BYTES) { Log.d(TAG, "Incorrect size of trust root certificate SHA-256 fingerprint: " - + trustRootCertSha256Fingerprint.length); + + mTrustRootCertSha256Fingerprint.length); return false; } return true; @@ -284,14 +340,14 @@ public final class UpdateParameter implements Parcelable { @Override public UpdateParameter createFromParcel(Parcel in) { UpdateParameter updateParam = new UpdateParameter(); - updateParam.updateIntervalInMinutes = in.readLong(); - updateParam.updateMethod = in.readString(); - updateParam.restriction = in.readString(); - updateParam.serverUri = in.readString(); - updateParam.username = in.readString(); - updateParam.base64EncodedPassword = in.readString(); - updateParam.trustRootCertUrl = in.readString(); - updateParam.trustRootCertSha256Fingerprint = in.createByteArray(); + updateParam.setUpdateIntervalInMinutes(in.readLong()); + updateParam.setUpdateMethod(in.readString()); + updateParam.setRestriction(in.readString()); + updateParam.setServerUri(in.readString()); + updateParam.setUsername(in.readString()); + updateParam.setBase64EncodedPassword(in.readString()); + updateParam.setTrustRootCertUrl(in.readString()); + updateParam.setTrustRootCertSha256Fingerprint(in.createByteArray()); return updateParam; } diff --git a/wifi/tests/src/android/net/wifi/hotspot2/ConfigBuilderTest.java b/wifi/tests/src/android/net/wifi/hotspot2/ConfigBuilderTest.java index 6095929758f0..f7dbf7e54d10 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/ConfigBuilderTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/ConfigBuilderTest.java @@ -83,27 +83,33 @@ public class ConfigBuilderTest { PasspointConfiguration config = new PasspointConfiguration(); // HomeSP configuration. - config.homeSp = new HomeSP(); - config.homeSp.friendlyName = "Century House"; - config.homeSp.fqdn = "mi6.co.uk"; - config.homeSp.roamingConsortiumOIs = new long[] {0x112233L, 0x445566L}; + HomeSP homeSp = new HomeSP(); + homeSp.setFriendlyName("Century House"); + homeSp.setFqdn("mi6.co.uk"); + homeSp.setRoamingConsortiumOIs(new long[] {0x112233L, 0x445566L}); + config.setHomeSp(homeSp); // Credential configuration. - config.credential = new Credential(); - config.credential.realm = "shaken.stirred.com"; - config.credential.userCredential = new Credential.UserCredential(); - config.credential.userCredential.username = "james"; - config.credential.userCredential.password = "Ym9uZDAwNw=="; - config.credential.userCredential.eapType = 21; - config.credential.userCredential.nonEapInnerMethod = "MS-CHAP-V2"; - config.credential.certCredential = new Credential.CertificateCredential(); - config.credential.certCredential.certType = "x509v3"; - config.credential.certCredential.certSha256FingerPrint = new byte[32]; - Arrays.fill(config.credential.certCredential.certSha256FingerPrint, (byte)0x1f); - config.credential.simCredential = new Credential.SimCredential(); - config.credential.simCredential.imsi = "imsi"; - config.credential.simCredential.eapType = 24; - config.credential.caCertificate = FakeKeys.CA_CERT0; + Credential credential = new Credential(); + credential.setRealm("shaken.stirred.com"); + Credential.UserCredential userCredential = new Credential.UserCredential(); + userCredential.setUsername("james"); + userCredential.setPassword("Ym9uZDAwNw=="); + userCredential.setEapType(21); + userCredential.setNonEapInnerMethod("MS-CHAP-V2"); + credential.setUserCredential(userCredential); + Credential.CertificateCredential certCredential = new Credential.CertificateCredential(); + certCredential.setCertType("x509v3"); + byte[] certSha256Fingerprint = new byte[32]; + Arrays.fill(certSha256Fingerprint, (byte)0x1f); + certCredential.setCertSha256Fingerprint(certSha256Fingerprint); + credential.setCertCredential(certCredential); + Credential.SimCredential simCredential = new Credential.SimCredential(); + simCredential.setImsi("imsi"); + simCredential.setEapType(24); + credential.setSimCredential(simCredential); + credential.setCaCertificate(FakeKeys.CA_CERT0); + config.setCredential(credential); return config; } diff --git a/wifi/tests/src/android/net/wifi/hotspot2/PasspointConfigurationTest.java b/wifi/tests/src/android/net/wifi/hotspot2/PasspointConfigurationTest.java index 1eb08e0d3b58..3aed918527a3 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/PasspointConfigurationTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/PasspointConfigurationTest.java @@ -34,6 +34,8 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Unit tests for {@link android.net.wifi.hotspot2.PasspointConfiguration}. @@ -50,9 +52,9 @@ public class PasspointConfigurationTest { */ private static HomeSP createHomeSp() { HomeSP homeSp = new HomeSP(); - homeSp.fqdn = "fqdn"; - homeSp.friendlyName = "friendly name"; - homeSp.roamingConsortiumOIs = new long[] {0x55, 0x66}; + homeSp.setFqdn("fqdn"); + homeSp.setFriendlyName("friendly name"); + homeSp.setRoamingConsortiumOIs(new long[] {0x55, 0x66}); return homeSp; } @@ -63,15 +65,15 @@ public class PasspointConfigurationTest { */ private static Credential createCredential() { Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = null; - cred.certCredential = null; - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "1234*"; - cred.simCredential.eapType = EAPConstants.EAP_SIM; - cred.caCertificate = null; - cred.clientCertificateChain = null; - cred.clientPrivateKey = null; + cred.setRealm("realm"); + cred.setUserCredential(null); + cred.setCertCredential(null); + cred.setSimCredential(new Credential.SimCredential()); + cred.getSimCredential().setImsi("1234*"); + cred.getSimCredential().setEapType(EAPConstants.EAP_SIM); + cred.setCaCertificate(null); + cred.setClientCertificateChain(null); + cred.setClientPrivateKey(null); return cred; } @@ -82,56 +84,59 @@ public class PasspointConfigurationTest { */ private static Policy createPolicy() { Policy policy = new Policy(); - policy.minHomeDownlinkBandwidth = 123; - policy.minHomeUplinkBandwidth = 345; - policy.minRoamingDownlinkBandwidth = 567; - policy.minRoamingUplinkBandwidth = 789; - policy.maximumBssLoadValue = 12; - policy.excludedSsidList = new String[] {"ssid1", "ssid2"}; - policy.requiredProtoPortMap = new HashMap<>(); - policy.requiredProtoPortMap.put(12, "23,342,123"); - policy.requiredProtoPortMap.put(23, "789,372,1235"); - - policy.preferredRoamingPartnerList = new ArrayList<>(); + policy.setMinHomeDownlinkBandwidth(123); + policy.setMinHomeUplinkBandwidth(345); + policy.setMinRoamingDownlinkBandwidth(567); + policy.setMinRoamingUplinkBandwidth(789); + policy.setMaximumBssLoadValue(12); + policy.setExcludedSsidList(new String[] {"ssid1", "ssid2"}); + HashMap<Integer, String> requiredProtoPortMap = new HashMap<>(); + requiredProtoPortMap.put(12, "23,342,123"); + requiredProtoPortMap.put(23, "789,372,1235"); + policy.setRequiredProtoPortMap(requiredProtoPortMap); + + List<Policy.RoamingPartner> preferredRoamingPartnerList = new ArrayList<>(); Policy.RoamingPartner partner1 = new Policy.RoamingPartner(); - partner1.fqdn = "partner1.com"; - partner1.fqdnExactMatch = true; - partner1.priority = 12; - partner1.countries = "us,jp"; + partner1.setFqdn("partner1.com"); + partner1.setFqdnExactMatch(true); + partner1.setPriority(12); + partner1.setCountries("us,jp"); Policy.RoamingPartner partner2 = new Policy.RoamingPartner(); - partner2.fqdn = "partner2.com"; - partner2.fqdnExactMatch = false; - partner2.priority = 42; - partner2.countries = "ca,fr"; - policy.preferredRoamingPartnerList.add(partner1); - policy.preferredRoamingPartnerList.add(partner2); - - policy.policyUpdate = new UpdateParameter(); - policy.policyUpdate.updateIntervalInMinutes = 1712; - policy.policyUpdate.updateMethod = UpdateParameter.UPDATE_METHOD_OMADM; - policy.policyUpdate.restriction = UpdateParameter.UPDATE_RESTRICTION_HOMESP; - policy.policyUpdate.serverUri = "policy.update.com"; - policy.policyUpdate.username = "username"; - policy.policyUpdate.base64EncodedPassword = - Base64.encodeToString("password".getBytes(), Base64.DEFAULT); - policy.policyUpdate.trustRootCertUrl = "trust.cert.com"; - policy.policyUpdate.trustRootCertSha256Fingerprint = - new byte[CERTIFICATE_FINGERPRINT_BYTES]; + partner2.setFqdn("partner2.com"); + partner2.setFqdnExactMatch(false); + partner2.setPriority(42); + partner2.setCountries("ca,fr"); + preferredRoamingPartnerList.add(partner1); + preferredRoamingPartnerList.add(partner2); + policy.setPreferredRoamingPartnerList(preferredRoamingPartnerList); + + UpdateParameter policyUpdate = new UpdateParameter(); + policyUpdate.setUpdateIntervalInMinutes(1712); + policyUpdate.setUpdateMethod(UpdateParameter.UPDATE_METHOD_OMADM); + policyUpdate.setRestriction(UpdateParameter.UPDATE_RESTRICTION_HOMESP); + policyUpdate.setServerUri("policy.update.com"); + policyUpdate.setUsername("username"); + policyUpdate.setBase64EncodedPassword( + Base64.encodeToString("password".getBytes(), Base64.DEFAULT)); + policyUpdate.setTrustRootCertUrl("trust.cert.com"); + policyUpdate.setTrustRootCertSha256Fingerprint( + new byte[CERTIFICATE_FINGERPRINT_BYTES]); + policy.setPolicyUpdate(policyUpdate); return policy; } private static UpdateParameter createSubscriptionUpdate() { UpdateParameter subUpdate = new UpdateParameter(); - subUpdate.updateIntervalInMinutes = 9021; - subUpdate.updateMethod = UpdateParameter.UPDATE_METHOD_SSP; - subUpdate.restriction = UpdateParameter.UPDATE_RESTRICTION_ROAMING_PARTNER; - subUpdate.serverUri = "subscription.update.com"; - subUpdate.username = "subUsername"; - subUpdate.base64EncodedPassword = - Base64.encodeToString("subPassword".getBytes(), Base64.DEFAULT); - subUpdate.trustRootCertUrl = "subscription.trust.cert.com"; - subUpdate.trustRootCertSha256Fingerprint = new byte[CERTIFICATE_FINGERPRINT_BYTES]; + subUpdate.setUpdateIntervalInMinutes(9021); + subUpdate.setUpdateMethod(UpdateParameter.UPDATE_METHOD_SSP); + subUpdate.setRestriction(UpdateParameter.UPDATE_RESTRICTION_ROAMING_PARTNER); + subUpdate.setServerUri("subscription.update.com"); + subUpdate.setUsername("subUsername"); + subUpdate.setBase64EncodedPassword( + Base64.encodeToString("subPassword".getBytes(), Base64.DEFAULT)); + subUpdate.setTrustRootCertUrl("subscription.trust.cert.com"); + subUpdate.setTrustRootCertSha256Fingerprint(new byte[CERTIFICATE_FINGERPRINT_BYTES]); return subUpdate; } /** @@ -141,24 +146,25 @@ public class PasspointConfigurationTest { */ private static PasspointConfiguration createConfig() { PasspointConfiguration config = new PasspointConfiguration(); - config.homeSp = createHomeSp(); - config.credential = createCredential(); - config.policy = createPolicy(); - config.subscriptionUpdate = createSubscriptionUpdate(); - config.trustRootCertList = new HashMap<>(); - config.trustRootCertList.put("trustRoot.cert1.com", + config.setHomeSp(createHomeSp()); + config.setCredential(createCredential()); + config.setPolicy(createPolicy()); + config.setSubscriptionUpdate(createSubscriptionUpdate()); + Map<String, byte[]> trustRootCertList = new HashMap<>(); + trustRootCertList.put("trustRoot.cert1.com", new byte[CERTIFICATE_FINGERPRINT_BYTES]); - config.trustRootCertList.put("trustRoot.cert2.com", + trustRootCertList.put("trustRoot.cert2.com", new byte[CERTIFICATE_FINGERPRINT_BYTES]); - config.updateIdentifier = 1; - config.credentialPriority = 120; - config.subscriptionCreationTimeInMs = 231200; - config.subscriptionExpirationTimeInMs = 2134232; - config.subscriptionType = "Gold"; - config.usageLimitUsageTimePeriodInMinutes = 3600; - config.usageLimitStartTimeInMs = 124214213; - config.usageLimitDataLimit = 14121; - config.usageLimitTimeLimitInMinutes = 78912; + config.setTrustRootCertList(trustRootCertList); + config.setUpdateIdentifier(1); + config.setCredentialPriority(120); + config.setSubscriptionCreationTimeInMs(231200); + config.setSubscriptionExpirationTimeInMs(2134232); + config.setSubscriptionType("Gold"); + config.setUsageLimitUsageTimePeriodInMinutes(3600); + config.setUsageLimitStartTimeInMs(124214213); + config.setUsageLimitDataLimit(14121); + config.setUsageLimitTimeLimitInMinutes(78912); return config; } @@ -206,7 +212,7 @@ public class PasspointConfigurationTest { @Test public void verifyParcelWithoutHomeSP() throws Exception { PasspointConfiguration config = createConfig(); - config.homeSp = null; + config.setHomeSp(null); verifyParcel(config); } @@ -218,7 +224,7 @@ public class PasspointConfigurationTest { @Test public void verifyParcelWithoutCredential() throws Exception { PasspointConfiguration config = createConfig(); - config.credential = null; + config.setCredential(null); verifyParcel(config); } @@ -230,7 +236,7 @@ public class PasspointConfigurationTest { @Test public void verifyParcelWithoutPolicy() throws Exception { PasspointConfiguration config = createConfig(); - config.policy = null; + config.setPolicy(null); verifyParcel(config); } @@ -242,7 +248,7 @@ public class PasspointConfigurationTest { @Test public void verifyParcelWithoutSubscriptionUpdate() throws Exception { PasspointConfiguration config = createConfig(); - config.subscriptionUpdate = null; + config.setSubscriptionUpdate(null); verifyParcel(config); } @@ -255,7 +261,7 @@ public class PasspointConfigurationTest { @Test public void verifyParcelWithoutTrustRootCertList() throws Exception { PasspointConfiguration config = createConfig(); - config.trustRootCertList = null; + config.setTrustRootCertList(null); verifyParcel(config); } @@ -289,7 +295,7 @@ public class PasspointConfigurationTest { @Test public void validateConfigWithoutCredential() throws Exception { PasspointConfiguration config = createConfig(); - config.credential = null; + config.setCredential(null); assertFalse(config.validate()); } @@ -301,7 +307,7 @@ public class PasspointConfigurationTest { @Test public void validateConfigWithoutHomeSp() throws Exception { PasspointConfiguration config = createConfig(); - config.homeSp = null; + config.setHomeSp(null); assertFalse(config.validate()); } @@ -314,7 +320,7 @@ public class PasspointConfigurationTest { @Test public void validateConfigWithoutPolicy() throws Exception { PasspointConfiguration config = createConfig(); - config.policy = null; + config.setPolicy(null); assertTrue(config.validate()); } @@ -327,7 +333,7 @@ public class PasspointConfigurationTest { @Test public void validateConfigWithoutSubscriptionUpdate() throws Exception { PasspointConfiguration config = createConfig(); - config.subscriptionUpdate = null; + config.setSubscriptionUpdate(null); assertTrue(config.validate()); } @@ -341,13 +347,16 @@ public class PasspointConfigurationTest { public void validateConfigWithInvalidTrustRootCertUrl() throws Exception { PasspointConfiguration config = createConfig(); byte[] rawUrlBytes = new byte[MAX_URL_BYTES + 1]; + Map<String, byte[]> trustRootCertList = new HashMap<>(); Arrays.fill(rawUrlBytes, (byte) 'a'); - config.trustRootCertList.put(new String(rawUrlBytes, StandardCharsets.UTF_8), + trustRootCertList.put(new String(rawUrlBytes, StandardCharsets.UTF_8), new byte[CERTIFICATE_FINGERPRINT_BYTES]); + config.setTrustRootCertList(trustRootCertList); assertFalse(config.validate()); - config.trustRootCertList = new HashMap<>(); - config.trustRootCertList.put(null, new byte[CERTIFICATE_FINGERPRINT_BYTES]); + trustRootCertList = new HashMap<>(); + trustRootCertList.put(null, new byte[CERTIFICATE_FINGERPRINT_BYTES]); + config.setTrustRootCertList(trustRootCertList); assertFalse(config.validate()); } @@ -359,16 +368,19 @@ public class PasspointConfigurationTest { @Test public void validateConfigWithInvalidTrustRootCertFingerprint() throws Exception { PasspointConfiguration config = createConfig(); - config.trustRootCertList = new HashMap<>(); - config.trustRootCertList.put("test.cert.com", new byte[CERTIFICATE_FINGERPRINT_BYTES + 1]); + Map<String, byte[]> trustRootCertList = new HashMap<>(); + trustRootCertList.put("test.cert.com", new byte[CERTIFICATE_FINGERPRINT_BYTES + 1]); + config.setTrustRootCertList(trustRootCertList); assertFalse(config.validate()); - config.trustRootCertList = new HashMap<>(); - config.trustRootCertList.put("test.cert.com", new byte[CERTIFICATE_FINGERPRINT_BYTES - 1]); + trustRootCertList = new HashMap<>(); + trustRootCertList.put("test.cert.com", new byte[CERTIFICATE_FINGERPRINT_BYTES - 1]); + config.setTrustRootCertList(trustRootCertList); assertFalse(config.validate()); - config.trustRootCertList = new HashMap<>(); - config.trustRootCertList.put("test.cert.com", null); + trustRootCertList = new HashMap<>(); + trustRootCertList.put("test.cert.com", null); + config.setTrustRootCertList(trustRootCertList); assertFalse(config.validate()); } diff --git a/wifi/tests/src/android/net/wifi/hotspot2/omadm/PPSMOParserTest.java b/wifi/tests/src/android/net/wifi/hotspot2/omadm/PPSMOParserTest.java index 055204ce5b03..15de5c78a995 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/omadm/PPSMOParserTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/omadm/PPSMOParserTest.java @@ -39,6 +39,8 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Unit tests for {@link android.net.wifi.hotspot2.omadm.PPSMOParser}. @@ -86,107 +88,115 @@ public class PPSMOParserTest { */ private PasspointConfiguration generateConfigurationFromPPSMOTree() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + byte[] certFingerprint = new byte[32]; + Arrays.fill(certFingerprint, (byte) 0x1f); PasspointConfiguration config = new PasspointConfiguration(); - config.updateIdentifier = 12; - config.credentialPriority = 99; + config.setUpdateIdentifier(12); + config.setCredentialPriority(99); // AAA Server trust root. - config.trustRootCertList = new HashMap<>(); - byte[] certFingerprint = new byte[32]; - Arrays.fill(certFingerprint, (byte) 0x1f); - config.trustRootCertList.put("server1.trust.root.com", certFingerprint); + Map<String, byte[]> trustRootCertList = new HashMap<>(); + trustRootCertList.put("server1.trust.root.com", certFingerprint); + config.setTrustRootCertList(trustRootCertList); // Subscription update. - config.subscriptionUpdate = new UpdateParameter(); - config.subscriptionUpdate.updateIntervalInMinutes = 120; - config.subscriptionUpdate.updateMethod = UpdateParameter.UPDATE_METHOD_SSP; - config.subscriptionUpdate.restriction = UpdateParameter.UPDATE_RESTRICTION_ROAMING_PARTNER; - config.subscriptionUpdate.serverUri = "subscription.update.com"; - config.subscriptionUpdate.username = "subscriptionUser"; - config.subscriptionUpdate.base64EncodedPassword = "subscriptionPass"; - config.subscriptionUpdate.trustRootCertUrl = "subscription.update.cert.com"; - config.subscriptionUpdate.trustRootCertSha256Fingerprint = new byte[32]; - Arrays.fill(config.subscriptionUpdate.trustRootCertSha256Fingerprint, (byte) 0x1f); + UpdateParameter subscriptionUpdate = new UpdateParameter(); + subscriptionUpdate.setUpdateIntervalInMinutes(120); + subscriptionUpdate.setUpdateMethod(UpdateParameter.UPDATE_METHOD_SSP); + subscriptionUpdate.setRestriction(UpdateParameter.UPDATE_RESTRICTION_ROAMING_PARTNER); + subscriptionUpdate.setServerUri("subscription.update.com"); + subscriptionUpdate.setUsername("subscriptionUser"); + subscriptionUpdate.setBase64EncodedPassword("subscriptionPass"); + subscriptionUpdate.setTrustRootCertUrl("subscription.update.cert.com"); + subscriptionUpdate.setTrustRootCertSha256Fingerprint(certFingerprint); + config.setSubscriptionUpdate(subscriptionUpdate); // Subscription parameters. - config.subscriptionCreationTimeInMs = format.parse("2016-02-01T10:00:00Z").getTime(); - config.subscriptionExpirationTimeInMs = format.parse("2016-03-01T10:00:00Z").getTime(); - config.subscriptionType = "Gold"; - config.usageLimitDataLimit = 921890; - config.usageLimitStartTimeInMs = format.parse("2016-12-01T10:00:00Z").getTime(); - config.usageLimitTimeLimitInMinutes = 120; - config.usageLimitUsageTimePeriodInMinutes = 99910; + config.setSubscriptionCreationTimeInMs(format.parse("2016-02-01T10:00:00Z").getTime()); + config.setSubscriptionExpirationTimeInMs(format.parse("2016-03-01T10:00:00Z").getTime()); + config.setSubscriptionType("Gold"); + config.setUsageLimitDataLimit(921890); + config.setUsageLimitStartTimeInMs(format.parse("2016-12-01T10:00:00Z").getTime()); + config.setUsageLimitTimeLimitInMinutes(120); + config.setUsageLimitUsageTimePeriodInMinutes(99910); // HomeSP configuration. - config.homeSp = new HomeSP(); - config.homeSp.friendlyName = "Century House"; - config.homeSp.fqdn = "mi6.co.uk"; - config.homeSp.roamingConsortiumOIs = new long[] {0x112233L, 0x445566L}; - config.homeSp.iconUrl = "icon.test.com"; - config.homeSp.homeNetworkIds = new HashMap<>(); - config.homeSp.homeNetworkIds.put("TestSSID", 0x12345678L); - config.homeSp.homeNetworkIds.put("NullHESSID", null); - config.homeSp.matchAllOIs = new long[] {0x11223344}; - config.homeSp.matchAnyOIs = new long[] {0x55667788}; - config.homeSp.otherHomePartners = new String[] {"other.fqdn.com"}; + HomeSP homeSp = new HomeSP(); + homeSp.setFriendlyName("Century House"); + homeSp.setFqdn("mi6.co.uk"); + homeSp.setRoamingConsortiumOIs(new long[] {0x112233L, 0x445566L}); + homeSp.setIconUrl("icon.test.com"); + Map<String, Long> homeNetworkIds = new HashMap<>(); + homeNetworkIds.put("TestSSID", 0x12345678L); + homeNetworkIds.put("NullHESSID", null); + homeSp.setHomeNetworkIds(homeNetworkIds); + homeSp.setMatchAllOIs(new long[] {0x11223344}); + homeSp.setMatchAnyOIs(new long[] {0x55667788}); + homeSp.setOtherHomePartners(new String[] {"other.fqdn.com"}); + config.setHomeSp(homeSp); // Credential configuration. - config.credential = new Credential(); - config.credential.creationTimeInMs = format.parse("2016-01-01T10:00:00Z").getTime(); - config.credential.expirationTimeInMs = format.parse("2016-02-01T10:00:00Z").getTime(); - config.credential.realm = "shaken.stirred.com"; - config.credential.checkAAAServerCertStatus = true; - config.credential.userCredential = new Credential.UserCredential(); - config.credential.userCredential.username = "james"; - config.credential.userCredential.password = "Ym9uZDAwNw=="; - config.credential.userCredential.machineManaged = true; - config.credential.userCredential.softTokenApp = "TestApp"; - config.credential.userCredential.ableToShare = true; - config.credential.userCredential.eapType = 21; - config.credential.userCredential.nonEapInnerMethod = "MS-CHAP-V2"; - config.credential.certCredential = new Credential.CertificateCredential(); - config.credential.certCredential.certType = "x509v3"; - config.credential.certCredential.certSha256FingerPrint = new byte[32]; - Arrays.fill(config.credential.certCredential.certSha256FingerPrint, (byte)0x1f); - config.credential.simCredential = new Credential.SimCredential(); - config.credential.simCredential.imsi = "imsi"; - config.credential.simCredential.eapType = 24; + Credential credential = new Credential(); + credential.setCreationTimeInMs(format.parse("2016-01-01T10:00:00Z").getTime()); + credential.setExpirationTimeInMs(format.parse("2016-02-01T10:00:00Z").getTime()); + credential.setRealm("shaken.stirred.com"); + credential.setCheckAAAServerCertStatus(true); + Credential.UserCredential userCredential = new Credential.UserCredential(); + userCredential.setUsername("james"); + userCredential.setPassword("Ym9uZDAwNw=="); + userCredential.setMachineManaged(true); + userCredential.setSoftTokenApp("TestApp"); + userCredential.setAbleToShare(true); + userCredential.setEapType(21); + userCredential.setNonEapInnerMethod("MS-CHAP-V2"); + credential.setUserCredential(userCredential); + Credential.CertificateCredential certCredential = new Credential.CertificateCredential(); + certCredential.setCertType("x509v3"); + certCredential.setCertSha256Fingerprint(certFingerprint); + credential.setCertCredential(certCredential); + Credential.SimCredential simCredential = new Credential.SimCredential(); + simCredential.setImsi("imsi"); + simCredential.setEapType(24); + credential.setSimCredential(simCredential); + config.setCredential(credential); // Policy configuration. - config.policy = new Policy(); - config.policy.preferredRoamingPartnerList = new ArrayList<>(); + Policy policy = new Policy(); + List<Policy.RoamingPartner> preferredRoamingPartnerList = new ArrayList<>(); Policy.RoamingPartner partner1 = new Policy.RoamingPartner(); - partner1.fqdn = "test1.fqdn.com"; - partner1.fqdnExactMatch = true; - partner1.priority = 127; - partner1.countries = "us,fr"; + partner1.setFqdn("test1.fqdn.com"); + partner1.setFqdnExactMatch(true); + partner1.setPriority(127); + partner1.setCountries("us,fr"); Policy.RoamingPartner partner2 = new Policy.RoamingPartner(); - partner2.fqdn = "test2.fqdn.com"; - partner2.fqdnExactMatch = false; - partner2.priority = 200; - partner2.countries = "*"; - config.policy.preferredRoamingPartnerList.add(partner1); - config.policy.preferredRoamingPartnerList.add(partner2); - config.policy.minHomeDownlinkBandwidth = 23412; - config.policy.minHomeUplinkBandwidth = 9823; - config.policy.minRoamingDownlinkBandwidth = 9271; - config.policy.minRoamingUplinkBandwidth = 2315; - config.policy.excludedSsidList = new String[] {"excludeSSID"}; - config.policy.requiredProtoPortMap = new HashMap<>(); - config.policy.requiredProtoPortMap.put(12, "34,92,234"); - config.policy.maximumBssLoadValue = 23; - config.policy.policyUpdate = new UpdateParameter(); - config.policy.policyUpdate.updateIntervalInMinutes = 120; - config.policy.policyUpdate.updateMethod = UpdateParameter.UPDATE_METHOD_OMADM; - config.policy.policyUpdate.restriction = UpdateParameter.UPDATE_RESTRICTION_HOMESP; - config.policy.policyUpdate.serverUri = "policy.update.com"; - config.policy.policyUpdate.username = "updateUser"; - config.policy.policyUpdate.base64EncodedPassword = "updatePass"; - config.policy.policyUpdate.trustRootCertUrl = "update.cert.com"; - config.policy.policyUpdate.trustRootCertSha256Fingerprint = new byte[32]; - Arrays.fill(config.policy.policyUpdate.trustRootCertSha256Fingerprint, (byte) 0x1f); - + partner2.setFqdn("test2.fqdn.com"); + partner2.setFqdnExactMatch(false); + partner2.setPriority(200); + partner2.setCountries("*"); + preferredRoamingPartnerList.add(partner1); + preferredRoamingPartnerList.add(partner2); + policy.setPreferredRoamingPartnerList(preferredRoamingPartnerList); + policy.setMinHomeDownlinkBandwidth(23412); + policy.setMinHomeUplinkBandwidth(9823); + policy.setMinRoamingDownlinkBandwidth(9271); + policy.setMinRoamingUplinkBandwidth(2315); + policy.setExcludedSsidList(new String[] {"excludeSSID"}); + Map<Integer, String> requiredProtoPortMap = new HashMap<>(); + requiredProtoPortMap.put(12, "34,92,234"); + policy.setRequiredProtoPortMap(requiredProtoPortMap); + policy.setMaximumBssLoadValue(23); + UpdateParameter policyUpdate = new UpdateParameter(); + policyUpdate.setUpdateIntervalInMinutes(120); + policyUpdate.setUpdateMethod(UpdateParameter.UPDATE_METHOD_OMADM); + policyUpdate.setRestriction(UpdateParameter.UPDATE_RESTRICTION_HOMESP); + policyUpdate.setServerUri("policy.update.com"); + policyUpdate.setUsername("updateUser"); + policyUpdate.setBase64EncodedPassword("updatePass"); + policyUpdate.setTrustRootCertUrl("update.cert.com"); + policyUpdate.setTrustRootCertSha256Fingerprint(certFingerprint); + policy.setPolicyUpdate(policyUpdate); + config.setPolicy(policy); return config; } @@ -249,10 +259,3 @@ public class PPSMOParserTest { loadResourceFile(PPS_MO_XML_FILE_INVALID_NAME))); } } - - - - - - - diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java index f571c7fc5966..6f68e1c868c1 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java @@ -23,10 +23,11 @@ import android.net.wifi.EAPConstants; import android.net.wifi.FakeKeys; import android.os.Parcel; import android.test.suitebuilder.annotation.SmallTest; -import android.util.Log; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.Arrays; @@ -55,16 +56,16 @@ public class CredentialTest { X509Certificate[] clientCertificateChain, PrivateKey clientPrivateKey) { Credential cred = new Credential(); - cred.creationTimeInMs = 123455L; - cred.expirationTimeInMs = 2310093L; - cred.realm = "realm"; - cred.checkAAAServerCertStatus = true; - cred.userCredential = userCred; - cred.certCredential = certCred; - cred.simCredential = simCred; - cred.caCertificate = caCert; - cred.clientCertificateChain = clientCertificateChain; - cred.clientPrivateKey = clientPrivateKey; + cred.setCreationTimeInMs(123455L); + cred.setExpirationTimeInMs(2310093L); + cred.setRealm("realm"); + cred.setCheckAAAServerCertStatus(true); + cred.setUserCredential(userCred); + cred.setCertCredential(certCred); + cred.setSimCredential(simCred); + cred.setCaCertificate(caCert); + cred.setClientCertificateChain(clientCertificateChain); + cred.setClientPrivateKey(clientPrivateKey); return cred; } @@ -73,10 +74,12 @@ public class CredentialTest { * * @return {@link Credential} */ - private static Credential createCredentialWithCertificateCredential() { + private static Credential createCredentialWithCertificateCredential() + throws NoSuchAlgorithmException, CertificateEncodingException { Credential.CertificateCredential certCred = new Credential.CertificateCredential(); - certCred.certType = "x509v3"; - certCred.certSha256FingerPrint = new byte[32]; + certCred.setCertType("x509v3"); + certCred.setCertSha256Fingerprint( + MessageDigest.getInstance("SHA-256").digest(FakeKeys.CLIENT_CERT.getEncoded())); return createCredential(null, certCred, null, FakeKeys.CA_CERT0, new X509Certificate[] {FakeKeys.CLIENT_CERT}, FakeKeys.RSA_KEY1); } @@ -88,8 +91,8 @@ public class CredentialTest { */ private static Credential createCredentialWithSimCredential() { Credential.SimCredential simCred = new Credential.SimCredential(); - simCred.imsi = "1234*"; - simCred.eapType = EAPConstants.EAP_SIM; + simCred.setImsi("1234*"); + simCred.setEapType(EAPConstants.EAP_SIM); return createCredential(null, null, simCred, null, null, null); } @@ -100,15 +103,14 @@ public class CredentialTest { */ private static Credential createCredentialWithUserCredential() { Credential.UserCredential userCred = new Credential.UserCredential(); - userCred.username = "username"; - userCred.password = "password"; - userCred.machineManaged = true; - userCred.ableToShare = true; - userCred.softTokenApp = "TestApp"; - userCred.eapType = EAPConstants.EAP_TTLS; - userCred.nonEapInnerMethod = "MS-CHAP"; - return createCredential(userCred, null, null, FakeKeys.CA_CERT0, - new X509Certificate[] {FakeKeys.CLIENT_CERT}, FakeKeys.RSA_KEY1); + userCred.setUsername("username"); + userCred.setPassword("password"); + userCred.setMachineManaged(true); + userCred.setAbleToShare(true); + userCred.setSoftTokenApp("TestApp"); + userCred.setEapType(EAPConstants.EAP_TTLS); + userCred.setNonEapInnerMethod("MS-CHAP"); + return createCredential(userCred, null, null, FakeKeys.CA_CERT0, null, null); } private static void verifyParcel(Credential writeCred) { @@ -166,14 +168,7 @@ public class CredentialTest { */ @Test public void validateUserCredential() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); assertTrue(cred.validate()); } @@ -184,13 +179,8 @@ public class CredentialTest { */ @Test public void validateUserCredentialWithoutCaCert() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; + Credential cred = createCredentialWithUserCredential(); + cred.setCaCertificate(null); assertFalse(cred.validate()); } @@ -201,14 +191,8 @@ public class CredentialTest { */ @Test public void validateUserCredentialWithEapTls() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); + cred.getUserCredential().setEapType(EAPConstants.EAP_TLS); assertFalse(cred.validate()); } @@ -220,13 +204,8 @@ public class CredentialTest { */ @Test public void validateUserCredentialWithoutRealm() throws Exception { - Credential cred = new Credential(); - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); + cred.setRealm(null); assertFalse(cred.validate()); } @@ -237,13 +216,8 @@ public class CredentialTest { */ @Test public void validateUserCredentialWithoutUsername() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); + cred.getUserCredential().setUsername(null); assertFalse(cred.validate()); } @@ -254,13 +228,8 @@ public class CredentialTest { */ @Test public void validateUserCredentialWithoutPassword() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); + cred.getUserCredential().setPassword(null); assertFalse(cred.validate()); } @@ -271,13 +240,8 @@ public class CredentialTest { */ @Test public void validateUserCredentialWithoutAuthMethod() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); + cred.getUserCredential().setNonEapInnerMethod(null); assertFalse(cred.validate()); } @@ -290,17 +254,7 @@ public class CredentialTest { */ @Test public void validateCertCredential() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup certificate credential. - cred.certCredential = new Credential.CertificateCredential(); - cred.certCredential.certType = "x509v3"; - cred.certCredential.certSha256FingerPrint = - MessageDigest.getInstance("SHA-256").digest(FakeKeys.CLIENT_CERT.getEncoded()); - // Setup certificates and private key. - cred.caCertificate = FakeKeys.CA_CERT0; - cred.clientCertificateChain = new X509Certificate[] {FakeKeys.CLIENT_CERT}; - cred.clientPrivateKey = FakeKeys.RSA_KEY1; + Credential cred = createCredentialWithCertificateCredential(); assertTrue(cred.validate()); } @@ -310,16 +264,8 @@ public class CredentialTest { * @throws Exception */ public void validateCertCredentialWithoutCaCert() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup certificate credential. - cred.certCredential = new Credential.CertificateCredential(); - cred.certCredential.certType = "x509v3"; - cred.certCredential.certSha256FingerPrint = - MessageDigest.getInstance("SHA-256").digest(FakeKeys.CLIENT_CERT.getEncoded()); - // Setup certificates and private key. - cred.clientCertificateChain = new X509Certificate[] {FakeKeys.CLIENT_CERT}; - cred.clientPrivateKey = FakeKeys.RSA_KEY1; + Credential cred = createCredentialWithCertificateCredential(); + cred.setCaCertificate(null); assertFalse(cred.validate()); } @@ -330,16 +276,8 @@ public class CredentialTest { */ @Test public void validateCertCredentialWithoutClientCertChain() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup certificate credential. - cred.certCredential = new Credential.CertificateCredential(); - cred.certCredential.certType = "x509v3"; - cred.certCredential.certSha256FingerPrint = - MessageDigest.getInstance("SHA-256").digest(FakeKeys.CLIENT_CERT.getEncoded()); - // Setup certificates and private key. - cred.caCertificate = FakeKeys.CA_CERT0; - cred.clientPrivateKey = FakeKeys.RSA_KEY1; + Credential cred = createCredentialWithCertificateCredential(); + cred.setClientCertificateChain(null); assertFalse(cred.validate()); } @@ -350,16 +288,8 @@ public class CredentialTest { */ @Test public void validateCertCredentialWithoutClientPrivateKey() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup certificate credential. - cred.certCredential = new Credential.CertificateCredential(); - cred.certCredential.certType = "x509v3"; - cred.certCredential.certSha256FingerPrint = - MessageDigest.getInstance("SHA-256").digest(FakeKeys.CLIENT_CERT.getEncoded()); - // Setup certificates and private key. - cred.caCertificate = FakeKeys.CA_CERT0; - cred.clientCertificateChain = new X509Certificate[] {FakeKeys.CLIENT_CERT}; + Credential cred = createCredentialWithCertificateCredential(); + cred.setClientPrivateKey(null); assertFalse(cred.validate()); } @@ -371,17 +301,8 @@ public class CredentialTest { */ @Test public void validateCertCredentialWithMismatchFingerprint() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup certificate credential. - cred.certCredential = new Credential.CertificateCredential(); - cred.certCredential.certType = "x509v3"; - cred.certCredential.certSha256FingerPrint = new byte[32]; - Arrays.fill(cred.certCredential.certSha256FingerPrint, (byte)0); - // Setup certificates and private key. - cred.caCertificate = FakeKeys.CA_CERT0; - cred.clientCertificateChain = new X509Certificate[] {FakeKeys.CLIENT_CERT}; - cred.clientPrivateKey = FakeKeys.RSA_KEY1; + Credential cred = createCredentialWithCertificateCredential(); + cred.getCertCredential().setCertSha256Fingerprint(new byte[32]); assertFalse(cred.validate()); } @@ -392,12 +313,7 @@ public class CredentialTest { */ @Test public void validateSimCredentialWithEapSim() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "1234*"; - cred.simCredential.eapType = EAPConstants.EAP_SIM; + Credential cred = createCredentialWithSimCredential(); assertTrue(cred.validate()); } @@ -408,12 +324,8 @@ public class CredentialTest { */ @Test public void validateSimCredentialWithEapAka() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "1234*"; - cred.simCredential.eapType = EAPConstants.EAP_AKA; + Credential cred = createCredentialWithSimCredential(); + cred.getSimCredential().setEapType(EAPConstants.EAP_AKA); assertTrue(cred.validate()); } @@ -424,12 +336,8 @@ public class CredentialTest { */ @Test public void validateSimCredentialWithEapAkaPrime() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "1234*"; - cred.simCredential.eapType = EAPConstants.EAP_AKA_PRIME; + Credential cred = createCredentialWithSimCredential(); + cred.getSimCredential().setEapType(EAPConstants.EAP_AKA_PRIME); assertTrue(cred.validate()); } @@ -440,11 +348,8 @@ public class CredentialTest { */ @Test public void validateSimCredentialWithoutIMSI() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.eapType = EAPConstants.EAP_SIM; + Credential cred = createCredentialWithSimCredential(); + cred.getSimCredential().setImsi(null); assertFalse(cred.validate()); } @@ -455,12 +360,8 @@ public class CredentialTest { */ @Test public void validateSimCredentialWithInvalidIMSI() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "dummy"; - cred.simCredential.eapType = EAPConstants.EAP_SIM; + Credential cred = createCredentialWithSimCredential(); + cred.getSimCredential().setImsi("dummy"); assertFalse(cred.validate()); } @@ -471,12 +372,8 @@ public class CredentialTest { */ @Test public void validateSimCredentialWithEapTls() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "1234*"; - cred.simCredential.eapType = EAPConstants.EAP_TLS; + Credential cred = createCredentialWithSimCredential(); + cred.getSimCredential().setEapType(EAPConstants.EAP_TLS); assertFalse(cred.validate()); } @@ -487,19 +384,12 @@ public class CredentialTest { */ @Test public void validateCredentialWithUserAndSimCredential() throws Exception { - Credential cred = new Credential(); - cred.realm = "realm"; - // Setup user credential with EAP-TTLS. - cred.userCredential = new Credential.UserCredential(); - cred.userCredential.username = "username"; - cred.userCredential.password = "password"; - cred.userCredential.eapType = EAPConstants.EAP_TTLS; - cred.userCredential.nonEapInnerMethod = "MS-CHAP"; - cred.caCertificate = FakeKeys.CA_CERT0; + Credential cred = createCredentialWithUserCredential(); // Setup SIM credential. - cred.simCredential = new Credential.SimCredential(); - cred.simCredential.imsi = "1234*"; - cred.simCredential.eapType = EAPConstants.EAP_SIM; + Credential.SimCredential simCredential = new Credential.SimCredential(); + simCredential.setImsi("1234*"); + simCredential.setEapType(EAPConstants.EAP_SIM); + cred.setSimCredential(simCredential); assertFalse(cred.validate()); } diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/HomeSPTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/HomeSPTest.java index 45fdbea90769..92e94ee51317 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/pps/HomeSPTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/HomeSPTest.java @@ -55,14 +55,14 @@ public class HomeSPTest { */ private static HomeSP createHomeSp(Map<String, Long> homeNetworkIds) { HomeSP homeSp = new HomeSP(); - homeSp.fqdn = "fqdn"; - homeSp.friendlyName = "friendly name"; - homeSp.iconUrl = "icon.url"; - homeSp.homeNetworkIds = homeNetworkIds; - homeSp.matchAllOIs = new long[] {0x11L, 0x22L}; - homeSp.matchAnyOIs = new long[] {0x33L, 0x44L}; - homeSp.otherHomePartners = new String[] {"partner1", "partner2"}; - homeSp.roamingConsortiumOIs = new long[] {0x55, 0x66}; + homeSp.setFqdn("fqdn"); + homeSp.setFriendlyName("friendly name"); + homeSp.setIconUrl("icon.url"); + homeSp.setHomeNetworkIds(homeNetworkIds); + homeSp.setMatchAllOIs(new long[] {0x11L, 0x22L}); + homeSp.setMatchAnyOIs(new long[] {0x33L, 0x44L}); + homeSp.setOtherHomePartners(new String[] {"partner1", "partner2"}); + homeSp.setRoamingConsortiumOIs(new long[] {0x55, 0x66}); return homeSp; } @@ -136,9 +136,7 @@ public class HomeSPTest { */ @Test public void validateValidHomeSP() throws Exception { - HomeSP homeSp = new HomeSP(); - homeSp.fqdn = "fqdn"; - homeSp.friendlyName = "friendly name"; + HomeSP homeSp = createHomeSpWithHomeNetworkIds(); assertTrue(homeSp.validate()); } @@ -149,8 +147,8 @@ public class HomeSPTest { */ @Test public void validateHomeSpWithoutFqdn() throws Exception { - HomeSP homeSp = new HomeSP(); - homeSp.friendlyName = "friendly name"; + HomeSP homeSp = createHomeSpWithHomeNetworkIds(); + homeSp.setFqdn(null); assertFalse(homeSp.validate()); } @@ -161,36 +159,9 @@ public class HomeSPTest { */ @Test public void validateHomeSpWithoutFriendlyName() throws Exception { - HomeSP homeSp = new HomeSP(); - homeSp.fqdn = "fqdn"; - assertFalse(homeSp.validate()); - } - - /** - * Verify that a HomeSP is valid when the optional Roaming Consortium OIs are - * provided. - * - * @throws Exception - */ - @Test - public void validateHomeSpWithRoamingConsoritums() throws Exception { - HomeSP homeSp = new HomeSP(); - homeSp.fqdn = "fqdn"; - homeSp.friendlyName = "friendly name"; - homeSp.roamingConsortiumOIs = new long[] {0x55, 0x66}; - assertTrue(homeSp.validate()); - } - - /** - * Verify that a HomeSP is valid when the optional Home Network IDs are - * provided. - * - * @throws Exception - */ - @Test - public void validateHomeSpWithHomeNetworkIds() throws Exception { HomeSP homeSp = createHomeSpWithHomeNetworkIds(); - assertTrue(homeSp.validate()); + homeSp.setFriendlyName(null); + assertFalse(homeSp.validate()); } /** @@ -213,14 +184,14 @@ public class HomeSPTest { */ @Test public void validateHomeSpWithInvalidHomeNetworkIds() throws Exception { - HomeSP homeSp = new HomeSP(); - homeSp.fqdn = "fqdn"; - homeSp.friendlyName = "friendly name"; - homeSp.homeNetworkIds = new HashMap<>(); + HomeSP homeSp = createHomeSpWithoutHomeNetworkIds(); + // HomeNetworkID with SSID exceeding the maximum length. + Map<String, Long> homeNetworkIds = new HashMap<>(); byte[] rawSsidBytes = new byte[33]; Arrays.fill(rawSsidBytes, (byte) 'a'); - homeSp.homeNetworkIds.put( + homeNetworkIds.put( StringFactory.newStringFromBytes(rawSsidBytes, StandardCharsets.UTF_8), 0x1234L); + homeSp.setHomeNetworkIds(homeNetworkIds); assertFalse(homeSp.validate()); } diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/PolicyTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/PolicyTest.java index c371c497f26d..2a3676463936 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/pps/PolicyTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/PolicyTest.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -48,40 +49,43 @@ public class PolicyTest { */ private static Policy createPolicy() { Policy policy = new Policy(); - policy.minHomeDownlinkBandwidth = 123; - policy.minHomeUplinkBandwidth = 345; - policy.minRoamingDownlinkBandwidth = 567; - policy.minRoamingUplinkBandwidth = 789; - policy.excludedSsidList = new String[] {"ssid1", "ssid2"}; - policy.requiredProtoPortMap = new HashMap<>(); - policy.requiredProtoPortMap.put(12, "23,342,123"); - policy.requiredProtoPortMap.put(23, "789,372,1235"); - policy.maximumBssLoadValue = 12; + policy.setMinHomeDownlinkBandwidth(123); + policy.setMinHomeUplinkBandwidth(345); + policy.setMinRoamingDownlinkBandwidth(567); + policy.setMinRoamingUplinkBandwidth(789); + policy.setExcludedSsidList(new String[] {"ssid1", "ssid2"}); + Map<Integer, String> requiredProtoPortMap = new HashMap<>(); + requiredProtoPortMap.put(12, "23,342,123"); + requiredProtoPortMap.put(23, "789,372,1235"); + policy.setRequiredProtoPortMap(requiredProtoPortMap); + policy.setMaximumBssLoadValue(12); - policy.preferredRoamingPartnerList = new ArrayList<>(); + List<Policy.RoamingPartner> preferredRoamingPartnerList = new ArrayList<>(); Policy.RoamingPartner partner1 = new Policy.RoamingPartner(); - partner1.fqdn = "partner1.com"; - partner1.fqdnExactMatch = true; - partner1.priority = 12; - partner1.countries = "us,jp"; + partner1.setFqdn("partner1.com"); + partner1.setFqdnExactMatch(true); + partner1.setPriority(12); + partner1.setCountries("us,jp"); Policy.RoamingPartner partner2 = new Policy.RoamingPartner(); - partner2.fqdn = "partner2.com"; - partner2.fqdnExactMatch = false; - partner2.priority = 42; - partner2.countries = "ca,fr"; - policy.preferredRoamingPartnerList.add(partner1); - policy.preferredRoamingPartnerList.add(partner2); + partner2.setFqdn("partner2.com"); + partner2.setFqdnExactMatch(false); + partner2.setPriority(42); + partner2.setCountries("ca,fr"); + preferredRoamingPartnerList.add(partner1); + preferredRoamingPartnerList.add(partner2); + policy.setPreferredRoamingPartnerList(preferredRoamingPartnerList); - policy.policyUpdate = new UpdateParameter(); - policy.policyUpdate.updateIntervalInMinutes = 1712; - policy.policyUpdate.updateMethod = UpdateParameter.UPDATE_METHOD_OMADM; - policy.policyUpdate.restriction = UpdateParameter.UPDATE_RESTRICTION_HOMESP; - policy.policyUpdate.serverUri = "policy.update.com"; - policy.policyUpdate.username = "username"; - policy.policyUpdate.base64EncodedPassword = - Base64.encodeToString("password".getBytes(), Base64.DEFAULT); - policy.policyUpdate.trustRootCertUrl = "trust.cert.com"; - policy.policyUpdate.trustRootCertSha256Fingerprint = new byte[32]; + UpdateParameter policyUpdate = new UpdateParameter(); + policyUpdate.setUpdateIntervalInMinutes(1712); + policyUpdate.setUpdateMethod(UpdateParameter.UPDATE_METHOD_OMADM); + policyUpdate.setRestriction(UpdateParameter.UPDATE_RESTRICTION_HOMESP); + policyUpdate.setServerUri("policy.update.com"); + policyUpdate.setUsername("username"); + policyUpdate.setBase64EncodedPassword( + Base64.encodeToString("password".getBytes(), Base64.DEFAULT)); + policyUpdate.setTrustRootCertUrl("trust.cert.com"); + policyUpdate.setTrustRootCertSha256Fingerprint(new byte[32]); + policy.setPolicyUpdate(policyUpdate); return policy; } @@ -128,7 +132,7 @@ public class PolicyTest { @Test public void verifyParcelWithoutProtoPortMap() throws Exception { Policy policy = createPolicy(); - policy.requiredProtoPortMap = null; + policy.setRequiredProtoPortMap(null); verifyParcel(policy); } @@ -140,7 +144,7 @@ public class PolicyTest { @Test public void verifyParcelWithoutPreferredRoamingPartnerList() throws Exception { Policy policy = createPolicy(); - policy.preferredRoamingPartnerList = null; + policy.setPreferredRoamingPartnerList(null); verifyParcel(policy); } @@ -152,7 +156,7 @@ public class PolicyTest { @Test public void verifyParcelWithoutPolicyUpdate() throws Exception { Policy policy = createPolicy(); - policy.policyUpdate = null; + policy.setPolicyUpdate(null); verifyParcel(policy); } @@ -212,7 +216,7 @@ public class PolicyTest { @Test public void validatePolicyWithoutPolicyUpdate() throws Exception { Policy policy = createPolicy(); - policy.policyUpdate = null; + policy.setPolicyUpdate(null); assertFalse(policy.validate()); } @@ -224,7 +228,7 @@ public class PolicyTest { @Test public void validatePolicyWithInvalidPolicyUpdate() throws Exception { Policy policy = createPolicy(); - policy.policyUpdate = new UpdateParameter(); + policy.setPolicyUpdate(new UpdateParameter()); assertFalse(policy.validate()); } @@ -237,10 +241,10 @@ public class PolicyTest { public void validatePolicyWithRoamingPartnerWithoutFQDN() throws Exception { Policy policy = createPolicy(); Policy.RoamingPartner partner = new Policy.RoamingPartner(); - partner.fqdnExactMatch = true; - partner.priority = 12; - partner.countries = "us,jp"; - policy.preferredRoamingPartnerList.add(partner); + partner.setFqdnExactMatch(true); + partner.setPriority(12); + partner.setCountries("us,jp"); + policy.getPreferredRoamingPartnerList().add(partner); assertFalse(policy.validate()); } @@ -254,10 +258,10 @@ public class PolicyTest { public void validatePolicyWithRoamingPartnerWithoutCountries() throws Exception { Policy policy = createPolicy(); Policy.RoamingPartner partner = new Policy.RoamingPartner(); - partner.fqdn = "test.com"; - partner.fqdnExactMatch = true; - partner.priority = 12; - policy.preferredRoamingPartnerList.add(partner); + partner.setFqdn("test.com"); + partner.setFqdnExactMatch(true); + partner.setPriority(12); + policy.getPreferredRoamingPartnerList().add(partner); assertFalse(policy.validate()); } @@ -271,7 +275,8 @@ public class PolicyTest { public void validatePolicyWithInvalidPortStringInProtoPortMap() throws Exception { Policy policy = createPolicy(); byte[] rawPortBytes = new byte[MAX_PORT_STRING_BYTES + 1]; - policy.requiredProtoPortMap.put(324, new String(rawPortBytes, StandardCharsets.UTF_8)); + policy.getRequiredProtoPortMap().put( + 324, new String(rawPortBytes, StandardCharsets.UTF_8)); assertFalse(policy.validate()); } @@ -283,8 +288,9 @@ public class PolicyTest { @Test public void validatePolicyWithSsidExclusionListSizeExceededMax() throws Exception { Policy policy = createPolicy(); - policy.excludedSsidList = new String[MAX_NUMBER_OF_EXCLUDED_SSIDS + 1]; - Arrays.fill(policy.excludedSsidList, "ssid"); + String[] excludedSsidList = new String[MAX_NUMBER_OF_EXCLUDED_SSIDS + 1]; + Arrays.fill(excludedSsidList, "ssid"); + policy.setExcludedSsidList(excludedSsidList); assertFalse(policy.validate()); } @@ -298,7 +304,9 @@ public class PolicyTest { Policy policy = createPolicy(); byte[] rawSsidBytes = new byte[MAX_SSID_BYTES + 1]; Arrays.fill(rawSsidBytes, (byte) 'a'); - policy.excludedSsidList = new String[] {new String(rawSsidBytes, StandardCharsets.UTF_8)}; + String[] excludedSsidList = new String[] { + new String(rawSsidBytes, StandardCharsets.UTF_8)}; + policy.setExcludedSsidList(excludedSsidList); assertFalse(policy.validate()); } } diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java index 6bf0db1b4358..551ed43c5efa 100644 --- a/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java +++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java @@ -50,15 +50,15 @@ public class UpdateParameterTest { */ private static UpdateParameter createUpdateParameter() { UpdateParameter updateParam = new UpdateParameter(); - updateParam.updateIntervalInMinutes = 1712; - updateParam.updateMethod = UpdateParameter.UPDATE_METHOD_OMADM; - updateParam.restriction = UpdateParameter.UPDATE_RESTRICTION_HOMESP; - updateParam.serverUri = "server.pdate.com"; - updateParam.username = "username"; - updateParam.base64EncodedPassword = - Base64.encodeToString("password".getBytes(), Base64.DEFAULT); - updateParam.trustRootCertUrl = "trust.cert.com"; - updateParam.trustRootCertSha256Fingerprint = new byte[32]; + updateParam.setUpdateIntervalInMinutes(1712); + updateParam.setUpdateMethod(UpdateParameter.UPDATE_METHOD_OMADM); + updateParam.setRestriction(UpdateParameter.UPDATE_RESTRICTION_HOMESP); + updateParam.setServerUri("server.pdate.com"); + updateParam.setUsername("username"); + updateParam.setBase64EncodedPassword( + Base64.encodeToString("password".getBytes(), Base64.DEFAULT)); + updateParam.setTrustRootCertUrl("trust.cert.com"); + updateParam.setTrustRootCertSha256Fingerprint(new byte[32]); return updateParam; } @@ -152,7 +152,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithUnknowMethod() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.updateMethod = "adsfasd"; + updateParam.setUpdateMethod("adsfasd"); assertFalse(updateParam.validate()); } @@ -164,7 +164,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithUnknowRestriction() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.restriction = "adsfasd"; + updateParam.setRestriction("adsfasd"); assertFalse(updateParam.validate()); } @@ -178,7 +178,7 @@ public class UpdateParameterTest { UpdateParameter updateParam = createUpdateParameter(); byte[] rawUsernameBytes = new byte[MAX_USERNAME_BYTES + 1]; Arrays.fill(rawUsernameBytes, (byte) 'a'); - updateParam.username = new String(rawUsernameBytes, StandardCharsets.UTF_8); + updateParam.setUsername(new String(rawUsernameBytes, StandardCharsets.UTF_8)); assertFalse(updateParam.validate()); } @@ -190,7 +190,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithEmptyUsername() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.username = null; + updateParam.setUsername(null); assertFalse(updateParam.validate()); } @@ -204,7 +204,7 @@ public class UpdateParameterTest { UpdateParameter updateParam = createUpdateParameter(); byte[] rawPasswordBytes = new byte[MAX_PASSWORD_BYTES + 1]; Arrays.fill(rawPasswordBytes, (byte) 'a'); - updateParam.base64EncodedPassword = new String(rawPasswordBytes, StandardCharsets.UTF_8); + updateParam.setBase64EncodedPassword(new String(rawPasswordBytes, StandardCharsets.UTF_8)); assertFalse(updateParam.validate()); } @@ -216,7 +216,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithEmptyPassword() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.base64EncodedPassword = null; + updateParam.setBase64EncodedPassword(null); assertFalse(updateParam.validate()); } @@ -229,7 +229,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithPasswordContainedInvalidPadding() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.base64EncodedPassword = updateParam.base64EncodedPassword + "="; + updateParam.setBase64EncodedPassword(updateParam.getBase64EncodedPassword() + "="); assertFalse(updateParam.validate()); } @@ -241,7 +241,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithoutTrustRootCertUrl() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.trustRootCertUrl = null; + updateParam.setTrustRootCertUrl(null); assertFalse(updateParam.validate()); } @@ -255,7 +255,7 @@ public class UpdateParameterTest { UpdateParameter updateParam = createUpdateParameter(); byte[] rawUrlBytes = new byte[MAX_URL_BYTES + 1]; Arrays.fill(rawUrlBytes, (byte) 'a'); - updateParam.trustRootCertUrl = new String(rawUrlBytes, StandardCharsets.UTF_8); + updateParam.setTrustRootCertUrl(new String(rawUrlBytes, StandardCharsets.UTF_8)); assertFalse(updateParam.validate()); } @@ -268,7 +268,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithouttrustRootCertSha256Fingerprint() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.trustRootCertSha256Fingerprint = null; + updateParam.setTrustRootCertSha256Fingerprint(null); assertFalse(updateParam.validate()); } @@ -281,10 +281,10 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithInvalidtrustRootCertSha256Fingerprint() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.trustRootCertSha256Fingerprint = new byte[CERTIFICATE_SHA256_BYTES + 1]; + updateParam.setTrustRootCertSha256Fingerprint(new byte[CERTIFICATE_SHA256_BYTES + 1]); assertFalse(updateParam.validate()); - updateParam.trustRootCertSha256Fingerprint = new byte[CERTIFICATE_SHA256_BYTES - 1]; + updateParam.setTrustRootCertSha256Fingerprint(new byte[CERTIFICATE_SHA256_BYTES - 1]); assertFalse(updateParam.validate()); } @@ -296,7 +296,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithoutServerUri() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.serverUri = null; + updateParam.setServerUri(null); assertFalse(updateParam.validate()); } @@ -310,7 +310,7 @@ public class UpdateParameterTest { UpdateParameter updateParam = createUpdateParameter(); byte[] rawUriBytes = new byte[MAX_URI_BYTES + 1]; Arrays.fill(rawUriBytes, (byte) 'a'); - updateParam.serverUri = new String(rawUriBytes, StandardCharsets.UTF_8); + updateParam.setServerUri(new String(rawUriBytes, StandardCharsets.UTF_8)); assertFalse(updateParam.validate()); } @@ -323,14 +323,14 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithNoServerCheck() throws Exception { UpdateParameter updateParam = new UpdateParameter(); - updateParam.updateIntervalInMinutes = UpdateParameter.UPDATE_CHECK_INTERVAL_NEVER; - updateParam.username = null; - updateParam.base64EncodedPassword = null; - updateParam.updateMethod = null; - updateParam.restriction = null; - updateParam.serverUri = null; - updateParam.trustRootCertUrl = null; - updateParam.trustRootCertSha256Fingerprint = null; + updateParam.setUpdateIntervalInMinutes(UpdateParameter.UPDATE_CHECK_INTERVAL_NEVER); + updateParam.setUsername(null); + updateParam.setBase64EncodedPassword(null); + updateParam.setUpdateMethod(null); + updateParam.setRestriction(null); + updateParam.setServerUri(null); + updateParam.setTrustRootCertUrl(null); + updateParam.setTrustRootCertSha256Fingerprint(null); assertTrue(updateParam.validate()); } @@ -342,7 +342,7 @@ public class UpdateParameterTest { @Test public void validateUpdateParameterWithoutUpdateInterval() throws Exception { UpdateParameter updateParam = createUpdateParameter(); - updateParam.updateIntervalInMinutes = Long.MIN_VALUE; + updateParam.setUpdateIntervalInMinutes(Long.MIN_VALUE); assertFalse(updateParam.validate()); } } |