Merge "Clear reference to Global Actions Dialog after it is dismissed"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index f7a2858..8fac394 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -255,6 +255,7 @@
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/CaptivePortalLogin)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/framework/ext.jar)
$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/telephony/java/com/google/android/mms)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/framework/*-service.jar)
# ******************************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER
# ******************************************************************
diff --git a/apex/appsearch/service/Android.bp b/apex/appsearch/service/Android.bp
index 2821fbe..2cd7aa0 100644
--- a/apex/appsearch/service/Android.bp
+++ b/apex/appsearch/service/Android.bp
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
java_library {
- name: "appsearch-service",
+ name: "service-appsearch",
installable: true,
srcs: [
"java/**/*.java",
diff --git a/apex/blobstore/service/Android.bp b/apex/blobstore/service/Android.bp
index 019f989..d8caa5a 100644
--- a/apex/blobstore/service/Android.bp
+++ b/apex/blobstore/service/Android.bp
@@ -13,7 +13,7 @@
// limitations under the License.
java_library {
- name: "blobstore-service",
+ name: "service-blobstore",
installable: true,
srcs: [
@@ -24,4 +24,4 @@
"framework",
"services.core",
],
-}
\ No newline at end of file
+}
diff --git a/apex/jobscheduler/README_js-mainline.md b/apex/jobscheduler/README_js-mainline.md
index ea20e3e..134ff3d 100644
--- a/apex/jobscheduler/README_js-mainline.md
+++ b/apex/jobscheduler/README_js-mainline.md
@@ -2,14 +2,14 @@
## Current structure
-- JS service side classes are put in `jobscheduler-service.jar`.
+- JS service side classes are put in `service-jobscheduler.jar`.
It's *not* included in services.jar, and instead it's put in the system server classpath,
which currently looks like the following:
-`SYSTEMSERVERCLASSPATH=/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/com.android.location.provider.jar:/system/framework/jobscheduler-service.jar`
+`SYSTEMSERVERCLASSPATH=/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/com.android.location.provider.jar:/system/framework/service-jobscheduler.jar`
`SYSTEMSERVERCLASSPATH` is generated from `PRODUCT_SYSTEM_SERVER_JARS`.
-- JS framework side classes are put in `jobscheduler-framework.jar`,
+- JS framework side classes are put in `framework-jobscheduler.jar`,
and the rest of the framework code is put in `framework-minus-apex.jar`,
as of http://ag/9145619.
diff --git a/apex/jobscheduler/framework/Android.bp b/apex/jobscheduler/framework/Android.bp
index 3902aa2..98bbe82 100644
--- a/apex/jobscheduler/framework/Android.bp
+++ b/apex/jobscheduler/framework/Android.bp
@@ -11,7 +11,7 @@
}
java_library {
- name: "jobscheduler-framework",
+ name: "framework-jobscheduler",
installable: false,
compile_dex: true,
sdk_version: "core_platform",
diff --git a/apex/jobscheduler/service/Android.bp b/apex/jobscheduler/service/Android.bp
index ca6dc45..c9d9d6c 100644
--- a/apex/jobscheduler/service/Android.bp
+++ b/apex/jobscheduler/service/Android.bp
@@ -1,7 +1,7 @@
// Job Scheduler Service jar, which will eventually be put in the jobscheduler mainline apex.
-// jobscheduler-service needs to be added to PRODUCT_SYSTEM_SERVER_JARS.
+// service-jobscheduler needs to be added to PRODUCT_SYSTEM_SERVER_JARS.
java_library {
- name: "jobscheduler-service",
+ name: "service-jobscheduler",
installable: true,
srcs: [
diff --git a/apex/statsd/service/Android.bp b/apex/statsd/service/Android.bp
index 786e8b0..f71d74f 100644
--- a/apex/statsd/service/Android.bp
+++ b/apex/statsd/service/Android.bp
@@ -1,8 +1,8 @@
// Statsd Service jar, which will eventually be put in the statsd mainline apex.
-// statsd-service needs to be added to PRODUCT_SYSTEM_SERVER_JARS.
+// service-statsd needs to be added to PRODUCT_SYSTEM_SERVER_JARS.
// This jar will contain StatsCompanionService
java_library {
- name: "statsd-service",
+ name: "service-statsd",
installable: true,
srcs: [
@@ -13,4 +13,4 @@
"framework",
"services.core",
],
-}
\ No newline at end of file
+}
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
index 8a00c83..a6cc06f 100644
--- a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
+++ b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
@@ -2076,6 +2076,7 @@
private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
List<StatsLogEventWrapper> pulledData) {
long token = Binder.clearCallingIdentity();
+ Set<Integer> reportedUids = new HashSet<>();
try {
PackageManager pm = mContext.getPackageManager();
@@ -2096,6 +2097,12 @@
continue;
}
+ if (reportedUids.contains(pkg.applicationInfo.uid)) {
+ // do not report same uid twice
+ continue;
+ }
+ reportedUids.add(pkg.applicationInfo.uid);
+
int numPerms = pkg.requestedPermissions.length;
for (int permNum = 0; permNum < numPerms; permNum++) {
String permName = pkg.requestedPermissions[permNum];
@@ -2120,7 +2127,7 @@
e.writeString(permName);
e.writeInt(pkg.applicationInfo.uid);
- e.writeString(pkg.packageName);
+ e.writeString(null);
e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
& REQUESTED_PERMISSION_GRANTED) != 0);
e.writeInt(permissionFlags);
diff --git a/api/current.txt b/api/current.txt
index f010fca..323a74a 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -4759,18 +4759,18 @@
field public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3; // 0x3
}
- public class ExpandableListActivity extends android.app.Activity implements android.widget.ExpandableListView.OnChildClickListener android.widget.ExpandableListView.OnGroupCollapseListener android.widget.ExpandableListView.OnGroupExpandListener android.view.View.OnCreateContextMenuListener {
- ctor public ExpandableListActivity();
- method public android.widget.ExpandableListAdapter getExpandableListAdapter();
- method public android.widget.ExpandableListView getExpandableListView();
- method public long getSelectedId();
- method public long getSelectedPosition();
- method public boolean onChildClick(android.widget.ExpandableListView, android.view.View, int, int, long);
- method public void onGroupCollapse(int);
- method public void onGroupExpand(int);
- method public void setListAdapter(android.widget.ExpandableListAdapter);
- method public boolean setSelectedChild(int, int, boolean);
- method public void setSelectedGroup(int);
+ @Deprecated public class ExpandableListActivity extends android.app.Activity implements android.widget.ExpandableListView.OnChildClickListener android.widget.ExpandableListView.OnGroupCollapseListener android.widget.ExpandableListView.OnGroupExpandListener android.view.View.OnCreateContextMenuListener {
+ ctor @Deprecated public ExpandableListActivity();
+ method @Deprecated public android.widget.ExpandableListAdapter getExpandableListAdapter();
+ method @Deprecated public android.widget.ExpandableListView getExpandableListView();
+ method @Deprecated public long getSelectedId();
+ method @Deprecated public long getSelectedPosition();
+ method @Deprecated public boolean onChildClick(android.widget.ExpandableListView, android.view.View, int, int, long);
+ method @Deprecated public void onGroupCollapse(int);
+ method @Deprecated public void onGroupExpand(int);
+ method @Deprecated public void setListAdapter(android.widget.ExpandableListAdapter);
+ method @Deprecated public boolean setSelectedChild(int, int, boolean);
+ method @Deprecated public void setSelectedGroup(int);
}
@Deprecated public class Fragment implements android.content.ComponentCallbacks2 android.view.View.OnCreateContextMenuListener {
@@ -5212,40 +5212,40 @@
method @Deprecated public void onKeyguardExitResult(boolean);
}
- public abstract class LauncherActivity extends android.app.ListActivity {
- ctor public LauncherActivity();
- method protected android.content.Intent getTargetIntent();
- method protected android.content.Intent intentForPosition(int);
- method protected android.app.LauncherActivity.ListItem itemForPosition(int);
- method public java.util.List<android.app.LauncherActivity.ListItem> makeListItems();
- method protected java.util.List<android.content.pm.ResolveInfo> onQueryPackageManager(android.content.Intent);
- method protected void onSetContentView();
+ @Deprecated public abstract class LauncherActivity extends android.app.ListActivity {
+ ctor @Deprecated public LauncherActivity();
+ method @Deprecated protected android.content.Intent getTargetIntent();
+ method @Deprecated protected android.content.Intent intentForPosition(int);
+ method @Deprecated protected android.app.LauncherActivity.ListItem itemForPosition(int);
+ method @Deprecated public java.util.List<android.app.LauncherActivity.ListItem> makeListItems();
+ method @Deprecated protected java.util.List<android.content.pm.ResolveInfo> onQueryPackageManager(android.content.Intent);
+ method @Deprecated protected void onSetContentView();
}
- public class LauncherActivity.IconResizer {
- ctor public LauncherActivity.IconResizer();
- method public android.graphics.drawable.Drawable createIconThumbnail(android.graphics.drawable.Drawable);
+ @Deprecated public class LauncherActivity.IconResizer {
+ ctor @Deprecated public LauncherActivity.IconResizer();
+ method @Deprecated public android.graphics.drawable.Drawable createIconThumbnail(android.graphics.drawable.Drawable);
}
- public static class LauncherActivity.ListItem {
- ctor public LauncherActivity.ListItem();
- field public String className;
- field public android.os.Bundle extras;
- field public android.graphics.drawable.Drawable icon;
- field public CharSequence label;
- field public String packageName;
- field public android.content.pm.ResolveInfo resolveInfo;
+ @Deprecated public static class LauncherActivity.ListItem {
+ ctor @Deprecated public LauncherActivity.ListItem();
+ field @Deprecated public String className;
+ field @Deprecated public android.os.Bundle extras;
+ field @Deprecated public android.graphics.drawable.Drawable icon;
+ field @Deprecated public CharSequence label;
+ field @Deprecated public String packageName;
+ field @Deprecated public android.content.pm.ResolveInfo resolveInfo;
}
- public class ListActivity extends android.app.Activity {
- ctor public ListActivity();
- method public android.widget.ListAdapter getListAdapter();
- method public android.widget.ListView getListView();
- method public long getSelectedItemId();
- method public int getSelectedItemPosition();
- method protected void onListItemClick(android.widget.ListView, android.view.View, int, long);
- method public void setListAdapter(android.widget.ListAdapter);
- method public void setSelection(int);
+ @Deprecated public class ListActivity extends android.app.Activity {
+ ctor @Deprecated public ListActivity();
+ method @Deprecated public android.widget.ListAdapter getListAdapter();
+ method @Deprecated public android.widget.ListView getListView();
+ method @Deprecated public long getSelectedItemId();
+ method @Deprecated public int getSelectedItemPosition();
+ method @Deprecated protected void onListItemClick(android.widget.ListView, android.view.View, int, long);
+ method @Deprecated public void setListAdapter(android.widget.ListAdapter);
+ method @Deprecated public void setSelection(int);
}
@Deprecated public class ListFragment extends android.app.Fragment {
@@ -29165,14 +29165,17 @@
}
public class ProxyInfo implements android.os.Parcelable {
+ ctor public ProxyInfo(@Nullable android.net.ProxyInfo);
method public static android.net.ProxyInfo buildDirectProxy(String, int);
method public static android.net.ProxyInfo buildDirectProxy(String, int, java.util.List<java.lang.String>);
method public static android.net.ProxyInfo buildPacProxy(android.net.Uri);
+ method @NonNull public static android.net.ProxyInfo buildPacProxy(@NonNull android.net.Uri, int);
method public int describeContents();
method public String[] getExclusionList();
method public String getHost();
method public android.net.Uri getPacFileUrl();
method public int getPort();
+ method public boolean isValid();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.ProxyInfo> CREATOR;
}
@@ -34964,7 +34967,7 @@
method @Nullable public static android.os.Looper myLooper();
method @NonNull public static android.os.MessageQueue myQueue();
method public static void prepare();
- method public static void prepareMainLooper();
+ method @Deprecated public static void prepareMainLooper();
method public void quit();
method public void quitSafely();
method public void setMessageLogging(@Nullable android.util.Printer);
@@ -48901,12 +48904,12 @@
method @Nullable public static java.util.List<java.lang.String> getTimeZoneIdsForCountryCode(@NonNull String);
}
- public class TimingLogger {
- ctor public TimingLogger(String, String);
- method public void addSplit(String);
- method public void dumpToLog();
- method public void reset(String, String);
- method public void reset();
+ @Deprecated public class TimingLogger {
+ ctor @Deprecated public TimingLogger(String, String);
+ method @Deprecated public void addSplit(String);
+ method @Deprecated public void dumpToLog();
+ method @Deprecated public void reset(String, String);
+ method @Deprecated public void reset();
}
public class TypedValue {
diff --git a/api/system-current.txt b/api/system-current.txt
index 1ee60ff..9a63ea3 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -604,6 +604,10 @@
method public void setNotificationAssistantAccessGranted(@Nullable android.content.ComponentName, boolean);
}
+ public class SearchManager implements android.content.DialogInterface.OnCancelListener android.content.DialogInterface.OnDismissListener {
+ method public void launchAssist(@Nullable android.os.Bundle);
+ }
+
public final class StatsManager {
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void addConfig(long, byte[]) throws android.app.StatsManager.StatsUnavailableException;
method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean addConfiguration(long, byte[]);
@@ -4183,6 +4187,33 @@
method public void onUpstreamChanged(@Nullable android.net.Network);
}
+ public final class IpConfiguration implements android.os.Parcelable {
+ ctor public IpConfiguration();
+ ctor public IpConfiguration(@NonNull android.net.IpConfiguration);
+ method @Nullable public android.net.ProxyInfo getHttpProxy();
+ method @NonNull public android.net.IpConfiguration.IpAssignment getIpAssignment();
+ method @NonNull public android.net.IpConfiguration.ProxySettings getProxySettings();
+ method @Nullable public android.net.StaticIpConfiguration getStaticIpConfiguration();
+ method public void setHttpProxy(@Nullable android.net.ProxyInfo);
+ method public void setIpAssignment(@NonNull android.net.IpConfiguration.IpAssignment);
+ method public void setProxySettings(@NonNull android.net.IpConfiguration.ProxySettings);
+ method public void setStaticIpConfiguration(@Nullable android.net.StaticIpConfiguration);
+ field @NonNull public static final android.os.Parcelable.Creator<android.net.IpConfiguration> CREATOR;
+ }
+
+ public enum IpConfiguration.IpAssignment {
+ enum_constant public static final android.net.IpConfiguration.IpAssignment DHCP;
+ enum_constant public static final android.net.IpConfiguration.IpAssignment STATIC;
+ enum_constant public static final android.net.IpConfiguration.IpAssignment UNASSIGNED;
+ }
+
+ public enum IpConfiguration.ProxySettings {
+ enum_constant public static final android.net.IpConfiguration.ProxySettings NONE;
+ enum_constant public static final android.net.IpConfiguration.ProxySettings PAC;
+ enum_constant public static final android.net.IpConfiguration.ProxySettings STATIC;
+ enum_constant public static final android.net.IpConfiguration.ProxySettings UNASSIGNED;
+ }
+
public final class IpPrefix implements android.os.Parcelable {
ctor public IpPrefix(@NonNull java.net.InetAddress, @IntRange(from=0, to=128) int);
ctor public IpPrefix(@NonNull String);
@@ -4255,6 +4286,7 @@
public class NetworkKey implements android.os.Parcelable {
ctor public NetworkKey(android.net.WifiKey);
+ method @Nullable public static android.net.NetworkKey createFromScanResult(@Nullable android.net.wifi.ScanResult);
method public int describeContents();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkKey> CREATOR;
@@ -4277,16 +4309,23 @@
method @RequiresPermission(anyOf={android.Manifest.permission.SCORE_NETWORKS, "android.permission.REQUEST_NETWORK_SCORES"}) public boolean clearScores() throws java.lang.SecurityException;
method @RequiresPermission(anyOf={android.Manifest.permission.SCORE_NETWORKS, "android.permission.REQUEST_NETWORK_SCORES"}) public void disableScoring() throws java.lang.SecurityException;
method @RequiresPermission(anyOf={android.Manifest.permission.SCORE_NETWORKS, "android.permission.REQUEST_NETWORK_SCORES"}) public String getActiveScorerPackage();
+ method @RequiresPermission("android.permission.REQUEST_NETWORK_SCORES") public void registerNetworkScoreCallback(int, int, @NonNull java.util.concurrent.Executor, @NonNull android.net.NetworkScoreManager.NetworkScoreCallback) throws java.lang.SecurityException;
+ method @RequiresPermission("android.permission.REQUEST_NETWORK_SCORES") public boolean requestScores(@NonNull android.net.NetworkKey[]) throws java.lang.SecurityException;
method @RequiresPermission(anyOf={android.Manifest.permission.SCORE_NETWORKS, "android.permission.REQUEST_NETWORK_SCORES"}) public boolean setActiveScorer(String) throws java.lang.SecurityException;
- method @RequiresPermission(android.Manifest.permission.SCORE_NETWORKS) public boolean updateScores(android.net.ScoredNetwork[]) throws java.lang.SecurityException;
- field public static final String ACTION_CHANGE_ACTIVE = "android.net.scoring.CHANGE_ACTIVE";
+ method @RequiresPermission(android.Manifest.permission.SCORE_NETWORKS) public boolean updateScores(@NonNull android.net.ScoredNetwork[]) throws java.lang.SecurityException;
+ field @Deprecated public static final String ACTION_CHANGE_ACTIVE = "android.net.scoring.CHANGE_ACTIVE";
field public static final String ACTION_CUSTOM_ENABLE = "android.net.scoring.CUSTOM_ENABLE";
field public static final String ACTION_RECOMMEND_NETWORKS = "android.net.action.RECOMMEND_NETWORKS";
field public static final String ACTION_SCORER_CHANGED = "android.net.scoring.SCORER_CHANGED";
- field public static final String ACTION_SCORE_NETWORKS = "android.net.scoring.SCORE_NETWORKS";
- field public static final String EXTRA_NETWORKS_TO_SCORE = "networksToScore";
+ field @Deprecated public static final String ACTION_SCORE_NETWORKS = "android.net.scoring.SCORE_NETWORKS";
+ field @Deprecated public static final String EXTRA_NETWORKS_TO_SCORE = "networksToScore";
field public static final String EXTRA_NEW_SCORER = "newScorer";
- field public static final String EXTRA_PACKAGE_NAME = "packageName";
+ field @Deprecated public static final String EXTRA_PACKAGE_NAME = "packageName";
+ }
+
+ public static interface NetworkScoreManager.NetworkScoreCallback {
+ method public void clearScores();
+ method public void updateScores(@NonNull java.util.List<android.net.ScoredNetwork>);
}
public class NetworkStack {
@@ -6445,7 +6484,7 @@
public static final class Settings.Secure extends android.provider.Settings.NameValueTable {
method @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public static boolean putString(@NonNull android.content.ContentResolver, @NonNull String, @Nullable String, @Nullable String, boolean);
method @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public static void resetToDefaults(@NonNull android.content.ContentResolver, @Nullable String);
- field public static final String ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED = "accessibility_display_magnification_navbar_enabled";
+ field @Deprecated public static final String ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED = "accessibility_display_magnification_navbar_enabled";
field public static final String ASSIST_GESTURE_SETUP_COMPLETE = "assist_gesture_setup_complete";
field public static final String AUTOFILL_FEATURE_FIELD_CLASSIFICATION = "autofill_field_classification";
field public static final String AUTOFILL_USER_DATA_MAX_CATEGORY_COUNT = "autofill_user_data_max_category_count";
diff --git a/core/java/android/accessibilityservice/AccessibilityServiceInfo.java b/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
index 5913680..3db0b26 100644
--- a/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
+++ b/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
@@ -670,9 +670,8 @@
}
try {
if (platformCompat != null) {
- return platformCompat.isChangeEnabledByPackageName(
- REQUEST_ACCESSIBILITY_BUTTON_CHANGE, mResolveInfo.serviceInfo.packageName,
- mResolveInfo.serviceInfo.applicationInfo.uid);
+ return platformCompat.isChangeEnabled(REQUEST_ACCESSIBILITY_BUTTON_CHANGE,
+ mResolveInfo.serviceInfo.applicationInfo);
}
} catch (RemoteException ignore) {
}
diff --git a/core/java/android/app/ExpandableListActivity.java b/core/java/android/app/ExpandableListActivity.java
index e08f25a..22de878 100644
--- a/core/java/android/app/ExpandableListActivity.java
+++ b/core/java/android/app/ExpandableListActivity.java
@@ -150,7 +150,11 @@
*
* @see #setListAdapter
* @see android.widget.ExpandableListView
+ *
+ * @deprecated Use {@link androidx.recyclerview.widget.RecyclerView} or use
+ * {@link android.widget.ExpandableListView} directly
*/
+@Deprecated
public class ExpandableListActivity extends Activity implements
OnCreateContextMenuListener,
ExpandableListView.OnChildClickListener, ExpandableListView.OnGroupCollapseListener,
diff --git a/core/java/android/app/ISearchManager.aidl b/core/java/android/app/ISearchManager.aidl
index 53f1a46..0119707 100644
--- a/core/java/android/app/ISearchManager.aidl
+++ b/core/java/android/app/ISearchManager.aidl
@@ -31,6 +31,5 @@
@UnsupportedAppUsage
ComponentName getGlobalSearchActivity();
ComponentName getWebSearchActivity();
- void launchAssist(in Bundle args);
- boolean launchLegacyAssist(String hint, int userHandle, in Bundle args);
+ void launchAssist(int userHandle, in Bundle args);
}
diff --git a/core/java/android/app/LauncherActivity.java b/core/java/android/app/LauncherActivity.java
index 88e2356..b495b3c 100644
--- a/core/java/android/app/LauncherActivity.java
+++ b/core/java/android/app/LauncherActivity.java
@@ -53,7 +53,11 @@
* Displays a list of all activities which can be performed
* for a given intent. Launches when clicked.
*
+ * @deprecated Applications can implement this UI themselves using
+ * {@link androidx.recyclerview.widget.RecyclerView} and
+ * {@link android.content.pm.PackageManager#queryIntentActivities(Intent, int)}
*/
+@Deprecated
public abstract class LauncherActivity extends ListActivity {
Intent mIntent;
PackageManager mPackageManager;
diff --git a/core/java/android/app/ListActivity.java b/core/java/android/app/ListActivity.java
index 2162521..810cca2 100644
--- a/core/java/android/app/ListActivity.java
+++ b/core/java/android/app/ListActivity.java
@@ -171,7 +171,11 @@
*
* @see #setListAdapter
* @see android.widget.ListView
+ *
+ * @deprecated Use {@link androidx.fragment.app.ListFragment} or
+ * {@link androidx.recyclerview.widget.RecyclerView} to implement your Activity instead.
*/
+@Deprecated
public class ListActivity extends Activity {
/**
* This field should be made private, so it is hidden from the SDK.
diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java
index acca6fc..b10c3e2 100644
--- a/core/java/android/app/SearchManager.java
+++ b/core/java/android/app/SearchManager.java
@@ -16,6 +16,8 @@
package android.app;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.UnsupportedAppUsage;
import android.content.ActivityNotFoundException;
@@ -973,37 +975,22 @@
}
/**
- * Starts the assistant.
+ * Starts the {@link android.provider.Settings.Secure#ASSISTANT assistant}.
*
- * @param args the args to pass to the assistant
+ * @param args a {@code Bundle} that will be passed to the assistant's
+ * {@link android.service.voice.VoiceInteractionSession#onShow VoiceInteractionSession}
+ * (or as {@link Intent#getExtras() extras} along
+ * {@link Intent#ACTION_ASSIST ACTION_ASSIST} for legacy assistants)
*
* @hide
*/
- @UnsupportedAppUsage
- public void launchAssist(Bundle args) {
+ @SystemApi
+ public void launchAssist(@Nullable Bundle args) {
try {
if (mService == null) {
return;
}
- mService.launchAssist(args);
- } catch (RemoteException re) {
- throw re.rethrowFromSystemServer();
- }
- }
-
- /**
- * Starts the legacy assistant (i.e. the {@link Intent#ACTION_ASSIST}).
- *
- * @param args the args to pass to the assistant
- *
- * @hide
- */
- public boolean launchLegacyAssist(String hint, int userHandle, Bundle args) {
- try {
- if (mService == null) {
- return false;
- }
- return mService.launchLegacyAssist(hint, userHandle, args);
+ mService.launchAssist(mContext.getUserId(), args);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
diff --git a/core/java/android/net/IpConfiguration.java b/core/java/android/net/IpConfiguration.java
index 2af82d7..143467b 100644
--- a/core/java/android/net/IpConfiguration.java
+++ b/core/java/android/net/IpConfiguration.java
@@ -16,6 +16,10 @@
package android.net;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SuppressLint;
+import android.annotation.SystemApi;
import android.annotation.UnsupportedAppUsage;
import android.net.StaticIpConfiguration;
import android.os.Parcel;
@@ -27,13 +31,17 @@
* A class representing a configured network.
* @hide
*/
-public class IpConfiguration implements Parcelable {
+@SystemApi
+public final class IpConfiguration implements Parcelable {
private static final String TAG = "IpConfiguration";
+ // This enum has been used by apps through reflection for many releases.
+ // Therefore they can't just be removed. Duplicating these constants to
+ // give an alternate SystemApi is a worse option than exposing them.
+ @SuppressLint("Enum")
public enum IpAssignment {
/* Use statically configured IP settings. Configuration can be accessed
* with staticIpConfiguration */
- @UnsupportedAppUsage
STATIC,
/* Use dynamically configured IP settings */
DHCP,
@@ -42,14 +50,19 @@
UNASSIGNED
}
+ /** @hide */
public IpAssignment ipAssignment;
+ /** @hide */
public StaticIpConfiguration staticIpConfiguration;
+ // This enum has been used by apps through reflection for many releases.
+ // Therefore they can't just be removed. Duplicating these constants to
+ // give an alternate SystemApi is a worse option than exposing them.
+ @SuppressLint("Enum")
public enum ProxySettings {
/* No proxy is to be used. Any existing proxy settings
* should be cleared. */
- @UnsupportedAppUsage
NONE,
/* Use statically configured proxy. Configuration can be accessed
* with httpProxy. */
@@ -62,8 +75,10 @@
PAC
}
+ /** @hide */
public ProxySettings proxySettings;
+ /** @hide */
@UnsupportedAppUsage
public ProxyInfo httpProxy;
@@ -83,6 +98,7 @@
init(IpAssignment.UNASSIGNED, ProxySettings.UNASSIGNED, null, null);
}
+ /** @hide */
@UnsupportedAppUsage
public IpConfiguration(IpAssignment ipAssignment,
ProxySettings proxySettings,
@@ -91,7 +107,7 @@
init(ipAssignment, proxySettings, staticIpConfiguration, httpProxy);
}
- public IpConfiguration(IpConfiguration source) {
+ public IpConfiguration(@NonNull IpConfiguration source) {
this();
if (source != null) {
init(source.ipAssignment, source.proxySettings,
@@ -99,35 +115,35 @@
}
}
- public IpAssignment getIpAssignment() {
+ public @NonNull IpAssignment getIpAssignment() {
return ipAssignment;
}
- public void setIpAssignment(IpAssignment ipAssignment) {
+ public void setIpAssignment(@NonNull IpAssignment ipAssignment) {
this.ipAssignment = ipAssignment;
}
- public StaticIpConfiguration getStaticIpConfiguration() {
+ public @Nullable StaticIpConfiguration getStaticIpConfiguration() {
return staticIpConfiguration;
}
- public void setStaticIpConfiguration(StaticIpConfiguration staticIpConfiguration) {
+ public void setStaticIpConfiguration(@Nullable StaticIpConfiguration staticIpConfiguration) {
this.staticIpConfiguration = staticIpConfiguration;
}
- public ProxySettings getProxySettings() {
+ public @NonNull ProxySettings getProxySettings() {
return proxySettings;
}
- public void setProxySettings(ProxySettings proxySettings) {
+ public void setProxySettings(@NonNull ProxySettings proxySettings) {
this.proxySettings = proxySettings;
}
- public ProxyInfo getHttpProxy() {
+ public @Nullable ProxyInfo getHttpProxy() {
return httpProxy;
}
- public void setHttpProxy(ProxyInfo httpProxy) {
+ public void setHttpProxy(@Nullable ProxyInfo httpProxy) {
this.httpProxy = httpProxy;
}
@@ -175,13 +191,19 @@
83 * httpProxy.hashCode();
}
- /** Implement the Parcelable interface */
+ /**
+ * Implement the Parcelable interface
+ * @hide
+ */
public int describeContents() {
return 0;
}
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
+ /**
+ * Implement the Parcelable interface
+ * @hide
+ */
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeString(ipAssignment.name());
dest.writeString(proxySettings.name());
dest.writeParcelable(staticIpConfiguration, flags);
@@ -189,7 +211,7 @@
}
/** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<IpConfiguration> CREATOR =
+ public static final @NonNull Creator<IpConfiguration> CREATOR =
new Creator<IpConfiguration>() {
public IpConfiguration createFromParcel(Parcel in) {
IpConfiguration config = new IpConfiguration();
diff --git a/core/java/android/net/NetworkKey.java b/core/java/android/net/NetworkKey.java
index 4254240..47c08a4 100644
--- a/core/java/android/net/NetworkKey.java
+++ b/core/java/android/net/NetworkKey.java
@@ -16,6 +16,7 @@
package android.net;
+import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
@@ -27,6 +28,8 @@
import android.text.TextUtils;
import android.util.Log;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
/**
@@ -48,6 +51,13 @@
/** A wifi network, for which {@link #wifiKey} will be populated. */
public static final int TYPE_WIFI = 1;
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"TYPE_"}, value = {
+ TYPE_WIFI
+ })
+ public @interface NetworkType {}
+
/**
* The type of this network.
* @see #TYPE_WIFI
@@ -65,7 +75,6 @@
*
* @return A new {@link NetworkKey} instance or <code>null</code> if the given
* {@link ScanResult} instance is malformed.
- * @hide
*/
@Nullable
public static NetworkKey createFromScanResult(@Nullable ScanResult result) {
diff --git a/core/java/android/net/NetworkScore.java b/core/java/android/net/NetworkScore.java
index 1ab6335..13f2994 100644
--- a/core/java/android/net/NetworkScore.java
+++ b/core/java/android/net/NetworkScore.java
@@ -154,4 +154,9 @@
}
return true;
}
+
+ /** Convert to a string */
+ public String toString() {
+ return "NetworkScore[" + mExtensions.toString() + "]";
+ }
}
diff --git a/core/java/android/net/NetworkScoreManager.java b/core/java/android/net/NetworkScoreManager.java
index 50dd468..f6dc525 100644
--- a/core/java/android/net/NetworkScoreManager.java
+++ b/core/java/android/net/NetworkScoreManager.java
@@ -17,7 +17,9 @@
package android.net;
import android.Manifest.permission;
+import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
+import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
@@ -25,13 +27,16 @@
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.content.Context;
+import android.os.Binder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.ServiceManager.ServiceNotFoundException;
+import android.util.Log;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
+import java.util.concurrent.Executor;
/**
* Class that manages communication between network subsystems and a network scorer.
@@ -50,19 +55,25 @@
@SystemApi
@SystemService(Context.NETWORK_SCORE_SERVICE)
public class NetworkScoreManager {
+ private static final String TAG = "NetworkScoreManager";
+
/**
* Activity action: ask the user to change the active network scorer. This will show a dialog
* that asks the user whether they want to replace the current active scorer with the one
* specified in {@link #EXTRA_PACKAGE_NAME}. The activity will finish with RESULT_OK if the
* active scorer was changed or RESULT_CANCELED if it failed for any reason.
+ * @deprecated No longer sent.
*/
+ @Deprecated
@SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
public static final String ACTION_CHANGE_ACTIVE = "android.net.scoring.CHANGE_ACTIVE";
/**
* Extra used with {@link #ACTION_CHANGE_ACTIVE} to specify the new scorer package. Set with
* {@link android.content.Intent#putExtra(String, String)}.
+ * @deprecated No longer sent.
*/
+ @Deprecated
public static final String EXTRA_PACKAGE_NAME = "packageName";
/**
@@ -73,7 +84,9 @@
* configured by the user as well as any open networks.
*
* <p class="note">This is a protected intent that can only be sent by the system.
+ * @deprecated Use {@link #ACTION_RECOMMEND_NETWORKS} to bind scorer app instead.
*/
+ @Deprecated
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_SCORE_NETWORKS = "android.net.scoring.SCORE_NETWORKS";
@@ -81,7 +94,9 @@
* Extra used with {@link #ACTION_SCORE_NETWORKS} to specify the networks to be scored, as an
* array of {@link NetworkKey}s. Can be obtained with
* {@link android.content.Intent#getParcelableArrayExtra(String)}}.
+ * @deprecated Use {@link #ACTION_RECOMMEND_NETWORKS} to bind scorer app instead.
*/
+ @Deprecated
public static final String EXTRA_NETWORKS_TO_SCORE = "networksToScore";
/**
@@ -285,7 +300,7 @@
* @throws SecurityException if the caller is not the active scorer.
*/
@RequiresPermission(android.Manifest.permission.SCORE_NETWORKS)
- public boolean updateScores(ScoredNetwork[] networks) throws SecurityException {
+ public boolean updateScores(@NonNull ScoredNetwork[] networks) throws SecurityException {
try {
return mService.updateScores(networks);
} catch (RemoteException e) {
@@ -359,13 +374,21 @@
/**
* Request scoring for networks.
*
- * @return true if the broadcast was sent, or false if there is no active scorer.
+ * <p>
+ * Note: The results (i.e scores) for these networks, when available will be provided via the
+ * callback registered with {@link #registerNetworkScoreCallback(int, int, Executor,
+ * NetworkScoreCallback)}. The calling module is responsible for registering a callback to
+ * receive the results before requesting new scores via this API.
+ *
+ * @return true if the request was successfully sent, or false if there is no active scorer.
* @throws SecurityException if the caller does not hold the
* {@link permission#REQUEST_NETWORK_SCORES} permission.
+ *
* @hide
*/
+ @SystemApi
@RequiresPermission(android.Manifest.permission.REQUEST_NETWORK_SCORES)
- public boolean requestScores(NetworkKey[] networks) throws SecurityException {
+ public boolean requestScores(@NonNull NetworkKey[] networks) throws SecurityException {
try {
return mService.requestScores(networks);
} catch (RemoteException e) {
@@ -431,6 +454,88 @@
}
/**
+ * Base class for network score cache callback. Should be extended by applications and set
+ * when calling {@link #registerNetworkScoreCallback(int, int, NetworkScoreCallback,
+ * Executor)}
+ *
+ * @hide
+ */
+ @SystemApi
+ public interface NetworkScoreCallback {
+ /**
+ * Called when a new set of network scores are available.
+ * This is triggered in response when the client invokes
+ * {@link #requestScores(NetworkKey[])} to score a new set of networks.
+ *
+ * @param networks List of {@link ScoredNetwork} containing updated scores.
+ */
+ void updateScores(@NonNull List<ScoredNetwork> networks);
+
+ /**
+ * Invokes when all the previously provided scores are no longer valid.
+ */
+ void clearScores();
+ }
+
+ /**
+ * Callback proxy for {@link NetworkScoreCallback} objects.
+ */
+ private class NetworkScoreCallbackProxy extends INetworkScoreCache.Stub {
+ private final Executor mExecutor;
+ private final NetworkScoreCallback mCallback;
+
+ NetworkScoreCallbackProxy(Executor executor, NetworkScoreCallback callback) {
+ mExecutor = executor;
+ mCallback = callback;
+ }
+
+ @Override
+ public void updateScores(@NonNull List<ScoredNetwork> networks) {
+ Binder.clearCallingIdentity();
+ mExecutor.execute(() -> {
+ mCallback.updateScores(networks);
+ });
+ }
+
+ @Override
+ public void clearScores() {
+ Binder.clearCallingIdentity();
+ mExecutor.execute(() -> {
+ mCallback.clearScores();
+ });
+ }
+ }
+
+ /**
+ * Register a network score callback.
+ *
+ * @param networkType the type of network this cache can handle. See {@link NetworkKey#type}
+ * @param filterType the {@link CacheUpdateFilter} to apply
+ * @param callback implementation of {@link NetworkScoreCallback} that will be invoked when the
+ * scores change.
+ * @param executor The executor on which to execute the callbacks.
+ * @throws SecurityException if the caller does not hold the
+ * {@link permission#REQUEST_NETWORK_SCORES} permission.
+ * @throws IllegalArgumentException if a callback is already registered for this type.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.REQUEST_NETWORK_SCORES)
+ public void registerNetworkScoreCallback(@NetworkKey.NetworkType int networkType,
+ @CacheUpdateFilter int filterType,
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull NetworkScoreCallback callback) throws SecurityException {
+ if (callback == null || executor == null) {
+ throw new IllegalArgumentException("callback / executor cannot be null");
+ }
+ Log.v(TAG, "registerNetworkScoreCallback: callback=" + callback + ", executor="
+ + executor);
+ // Use the @hide method.
+ registerNetworkScoreCache(
+ networkType, new NetworkScoreCallbackProxy(executor, callback), filterType);
+ }
+
+ /**
* Determine whether the application with the given UID is the enabled scorer.
*
* @param callingUid the UID to check
diff --git a/core/java/android/net/ProxyInfo.java b/core/java/android/net/ProxyInfo.java
index 807c467..9d92db4 100644
--- a/core/java/android/net/ProxyInfo.java
+++ b/core/java/android/net/ProxyInfo.java
@@ -16,7 +16,8 @@
package android.net;
-
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
@@ -89,6 +90,15 @@
}
/**
+ * Construct a {@link ProxyInfo} object that will download and run the PAC script at the
+ * specified URL and port.
+ */
+ @NonNull
+ public static ProxyInfo buildPacProxy(@NonNull Uri pacUrl, int port) {
+ return new ProxyInfo(pacUrl, port);
+ }
+
+ /**
* Create a ProxyProperties that points at a HTTP Proxy.
* @hide
*/
@@ -105,7 +115,7 @@
* Create a ProxyProperties that points at a PAC URL.
* @hide
*/
- public ProxyInfo(Uri pacFileUrl) {
+ public ProxyInfo(@NonNull Uri pacFileUrl) {
mHost = LOCAL_HOST;
mPort = LOCAL_PORT;
mExclusionList = LOCAL_EXCL_LIST;
@@ -132,7 +142,7 @@
* Only used in PacManager after Local Proxy is bound.
* @hide
*/
- public ProxyInfo(Uri pacFileUrl, int localProxyPort) {
+ public ProxyInfo(@NonNull Uri pacFileUrl, int localProxyPort) {
mHost = LOCAL_HOST;
mPort = localProxyPort;
mExclusionList = LOCAL_EXCL_LIST;
@@ -159,11 +169,10 @@
mPacFileUrl = Uri.EMPTY;
}
- // copy constructor instead of clone
/**
- * @hide
+ * A copy constructor to hold proxy properties.
*/
- public ProxyInfo(ProxyInfo source) {
+ public ProxyInfo(@Nullable ProxyInfo source) {
if (source != null) {
mHost = source.getHost();
mPort = source.getPort();
@@ -226,12 +235,13 @@
* comma separated
* @hide
*/
+ @Nullable
public String getExclusionListAsString() {
return mExclusionList;
}
/**
- * @hide
+ * Return true if the pattern of proxy is valid, otherwise return false.
*/
public boolean isValid() {
if (!Uri.EMPTY.equals(mPacFileUrl)) return true;
diff --git a/core/java/android/os/Looper.java b/core/java/android/os/Looper.java
index 3222fc4..d468972 100644
--- a/core/java/android/os/Looper.java
+++ b/core/java/android/os/Looper.java
@@ -112,10 +112,12 @@
/**
* Initialize the current thread as a looper, marking it as an
- * application's main looper. The main looper for your application
- * is created by the Android environment, so you should never need
- * to call this function yourself. See also: {@link #prepare()}
+ * application's main looper. See also: {@link #prepare()}
+ *
+ * @deprecated The main looper for your application is created by the Android environment,
+ * so you should never need to call this function yourself.
*/
+ @Deprecated
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 7a63b59..0af2c36 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -6191,8 +6191,12 @@
"accessibility_shortcut_dialog_shown";
/**
- * Setting specifying the accessibility service to be toggled via the accessibility
- * shortcut. Must be its flattened {@link ComponentName}.
+ * Setting specifying the accessibility services, accessibility shortcut targets,
+ * or features to be toggled via the accessibility shortcut.
+ *
+ * <p> This is a colon-separated string list which contains the flattened
+ * {@link ComponentName} and the class name of a system class implementing a supported
+ * accessibility feature.
* @hide
*/
@UnsupportedAppUsage
@@ -6201,9 +6205,11 @@
"accessibility_shortcut_target_service";
/**
- * Setting specifying the accessibility service or feature to be toggled via the
- * accessibility button in the navigation bar. This is either a flattened
- * {@link ComponentName} or the class name of a system class implementing a supported
+ * Setting specifying the accessibility services, accessibility shortcut targets,
+ * or features to be toggled via the accessibility button in the navigation bar.
+ *
+ * <p> This is a colon-separated string list which contains the flattened
+ * {@link ComponentName} and the class name of a system class implementing a supported
* accessibility feature.
* @hide
*/
@@ -6364,6 +6370,9 @@
* zoom in the display content and is targeted to low vision users. The current
* magnification scale is controlled by {@link #ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE}.
*
+ * @deprecated Use {@link #ACCESSIBILITY_BUTTON_TARGET_COMPONENT} instead.
+ * {@link #ACCESSIBILITY_BUTTON_TARGET_COMPONENT} holds the magnification system class name
+ * when navigation bar magnification is enabled.
* @hide
*/
@SystemApi
@@ -7170,16 +7179,6 @@
public static final String VOICE_RECOGNITION_SERVICE = "voice_recognition_service";
/**
- * Stores whether an user has consented to have apps verified through PAM.
- * The value is boolean (1 or 0).
- *
- * @hide
- */
- @UnsupportedAppUsage
- public static final String PACKAGE_VERIFIER_USER_CONSENT =
- "package_verifier_user_consent";
-
- /**
* The {@link ComponentName} string of the selected spell checker service which is
* one of the services managed by the text service manager.
*
diff --git a/core/java/android/util/TimingLogger.java b/core/java/android/util/TimingLogger.java
index be442da..5a4a512 100644
--- a/core/java/android/util/TimingLogger.java
+++ b/core/java/android/util/TimingLogger.java
@@ -44,7 +44,14 @@
* D/TAG ( 3459): methodA: 6 ms, work C
* D/TAG ( 3459): methodA: end, 16 ms
* </pre>
+ *
+ * @deprecated Use {@link android.os.Trace}, or
+ * <a href="https://developer.android.com/studio/profile/benchmark">Android Studio</a>. In
+ * general, milliseconds is the wrong granularity for method-level tracing. Rounding errors
+ * can overemphasize cheap operations, or underemphasize repeated operations. This timing
+ * system also does not take CPU scheduling or frequency into account.
*/
+@Deprecated
public class TimingLogger {
/**
diff --git a/core/java/android/widget/ArrayAdapter.java b/core/java/android/widget/ArrayAdapter.java
index 2bf1ba5..f7225d0 100644
--- a/core/java/android/widget/ArrayAdapter.java
+++ b/core/java/android/widget/ArrayAdapter.java
@@ -49,9 +49,6 @@
* To customize what type of view is used for the data object,
* override {@link #getView(int, View, ViewGroup)}
* and inflate a view resource.
- * For a code example, see
- * the <a href="https://github.com/googlesamples/android-CustomChoiceList/#readme">
- * CustomChoiceList</a> sample.
* </p>
* <p>
* For an example of using an array adapter with a ListView, see the
diff --git a/core/java/com/android/internal/policy/PhoneWindow.java b/core/java/com/android/internal/policy/PhoneWindow.java
index 227ef28..764d4a5 100644
--- a/core/java/com/android/internal/policy/PhoneWindow.java
+++ b/core/java/com/android/internal/policy/PhoneWindow.java
@@ -3109,8 +3109,9 @@
// On TVs, if the app doesn't implement search, we want to launch assist.
Bundle args = new Bundle();
args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, event.getDeviceId());
- return ((SearchManager)getContext().getSystemService(Context.SEARCH_SERVICE))
- .launchLegacyAssist(null, getContext().getUserId(), args);
+ ((SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE))
+ .launchAssist(args);
+ return true;
}
return result;
}
diff --git a/core/tests/coretests/src/android/util/StatsEventTest.java b/core/tests/coretests/src/android/util/StatsEventTest.java
new file mode 100644
index 0000000..93f11db
--- /dev/null
+++ b/core/tests/coretests/src/android/util/StatsEventTest.java
@@ -0,0 +1,466 @@
+/*
+ * Copyright (C) 2019 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.util;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import android.os.SystemClock;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.common.collect.Range;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+/**
+ * Internal tests for {@link StatsEvent}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class StatsEventTest {
+
+ @Test
+ public void testNoFields() {
+ final long minTimestamp = SystemClock.elapsedRealtimeNanos();
+ final StatsEvent statsEvent = StatsEvent.newBuilder().build();
+ final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
+
+ final int expectedAtomId = 0;
+ assertThat(statsEvent.getAtomId()).isEqualTo(expectedAtomId);
+
+ final ByteBuffer buffer =
+ ByteBuffer.wrap(statsEvent.getBytes()).order(ByteOrder.LITTLE_ENDIAN);
+
+ assertWithMessage("Root element in buffer is not TYPE_ERRORS")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_ERRORS);
+
+ assertWithMessage("Incorrect number of elements in root object")
+ .that(buffer.get()).isEqualTo(3);
+
+ assertWithMessage("First element is not timestamp")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect timestamp")
+ .that(buffer.getLong()).isIn(Range.closed(minTimestamp, maxTimestamp));
+
+ assertWithMessage("Second element is not atom id")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect atom id")
+ .that(buffer.getInt()).isEqualTo(expectedAtomId);
+
+ final int errorMask = buffer.getInt();
+
+ assertWithMessage("ERROR_NO_ATOM_ID should be the only error in the error mask")
+ .that(errorMask).isEqualTo(StatsEvent.ERROR_NO_ATOM_ID);
+
+ assertThat(statsEvent.getNumBytes()).isEqualTo(buffer.position());
+
+ statsEvent.release();
+ }
+
+ @Test
+ public void testIntBooleanIntInt() {
+ final int expectedAtomId = 109;
+ final int field1 = 1;
+ final boolean field2 = true;
+ final int field3 = 3;
+ final int field4 = 4;
+
+ final long minTimestamp = SystemClock.elapsedRealtimeNanos();
+ final StatsEvent statsEvent = StatsEvent.newBuilder()
+ .setAtomId(expectedAtomId)
+ .writeInt(field1)
+ .writeBoolean(field2)
+ .writeInt(field3)
+ .writeInt(field4)
+ .build();
+ final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
+
+ assertThat(statsEvent.getAtomId()).isEqualTo(expectedAtomId);
+
+ final ByteBuffer buffer =
+ ByteBuffer.wrap(statsEvent.getBytes()).order(ByteOrder.LITTLE_ENDIAN);
+
+ assertWithMessage("Root element in buffer is not TYPE_OBJECT")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_OBJECT);
+
+ assertWithMessage("Incorrect number of elements in root object")
+ .that(buffer.get()).isEqualTo(6);
+
+ assertWithMessage("First element is not timestamp")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect timestamp")
+ .that(buffer.getLong()).isIn(Range.closed(minTimestamp, maxTimestamp));
+
+ assertWithMessage("Second element is not atom id")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect atom id")
+ .that(buffer.getInt()).isEqualTo(expectedAtomId);
+
+ assertWithMessage("First field is not Int")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect field 1")
+ .that(buffer.getInt()).isEqualTo(field1);
+
+ assertWithMessage("Second field is not Boolean")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_BOOLEAN);
+
+ assertWithMessage("Incorrect field 2")
+ .that(buffer.get()).isEqualTo(1);
+
+ assertWithMessage("Third field is not Int")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect field 3")
+ .that(buffer.getInt()).isEqualTo(field3);
+
+ assertWithMessage("Fourth field is not Int")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect field 4")
+ .that(buffer.getInt()).isEqualTo(field4);
+
+ assertThat(statsEvent.getNumBytes()).isEqualTo(buffer.position());
+
+ statsEvent.release();
+ }
+
+ @Test
+ public void testStringFloatByteArray() {
+ final int expectedAtomId = 109;
+ final String field1 = "Str 1";
+ final float field2 = 9.334f;
+ final byte[] field3 = new byte[] { 56, 23, 89, -120 };
+
+ final long minTimestamp = SystemClock.elapsedRealtimeNanos();
+ final StatsEvent statsEvent = StatsEvent.newBuilder()
+ .setAtomId(expectedAtomId)
+ .writeString(field1)
+ .writeFloat(field2)
+ .writeByteArray(field3)
+ .build();
+ final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
+
+ assertThat(statsEvent.getAtomId()).isEqualTo(expectedAtomId);
+
+ final ByteBuffer buffer =
+ ByteBuffer.wrap(statsEvent.getBytes()).order(ByteOrder.LITTLE_ENDIAN);
+
+ assertWithMessage("Root element in buffer is not TYPE_OBJECT")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_OBJECT);
+
+ assertWithMessage("Incorrect number of elements in root object")
+ .that(buffer.get()).isEqualTo(5);
+
+ assertWithMessage("First element is not timestamp")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect timestamp")
+ .that(buffer.getLong()).isIn(Range.closed(minTimestamp, maxTimestamp));
+
+ assertWithMessage("Second element is not atom id")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect atom id")
+ .that(buffer.getInt()).isEqualTo(expectedAtomId);
+
+ assertWithMessage("First field is not String")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_STRING);
+
+ final String field1Actual = getStringFromByteBuffer(buffer);
+ assertWithMessage("Incorrect field 1")
+ .that(field1Actual).isEqualTo(field1);
+
+ assertWithMessage("Second field is not Float")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_FLOAT);
+
+ assertWithMessage("Incorrect field 2")
+ .that(buffer.getFloat()).isEqualTo(field2);
+
+ assertWithMessage("Third field is not byte array")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_BYTE_ARRAY);
+
+ final byte[] field3Actual = getByteArrayFromByteBuffer(buffer);
+ assertWithMessage("Incorrect field 3")
+ .that(field3Actual).isEqualTo(field3);
+
+ assertThat(statsEvent.getNumBytes()).isEqualTo(buffer.position());
+
+ statsEvent.release();
+ }
+
+ @Test
+ public void testAttributionChainLong() {
+ final int expectedAtomId = 109;
+ final int[] uids = new int[] { 1, 2, 3, 4, 5 };
+ final String[] tags = new String[] { "1", "2", "3", "4", "5" };
+ final long field2 = -230909823L;
+
+ final long minTimestamp = SystemClock.elapsedRealtimeNanos();
+ final StatsEvent statsEvent = StatsEvent.newBuilder()
+ .setAtomId(expectedAtomId)
+ .writeAttributionChain(uids, tags)
+ .writeLong(field2)
+ .build();
+ final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
+
+ assertThat(statsEvent.getAtomId()).isEqualTo(expectedAtomId);
+
+ final ByteBuffer buffer =
+ ByteBuffer.wrap(statsEvent.getBytes()).order(ByteOrder.LITTLE_ENDIAN);
+
+ assertWithMessage("Root element in buffer is not TYPE_OBJECT")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_OBJECT);
+
+ assertWithMessage("Incorrect number of elements in root object")
+ .that(buffer.get()).isEqualTo(4);
+
+ assertWithMessage("First element is not timestamp")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect timestamp")
+ .that(buffer.getLong()).isIn(Range.closed(minTimestamp, maxTimestamp));
+
+ assertWithMessage("Second element is not atom id")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect atom id")
+ .that(buffer.getInt()).isEqualTo(expectedAtomId);
+
+ assertWithMessage("First field is not Attribution Chain")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_ATTRIBUTION_CHAIN);
+
+ assertWithMessage("Incorrect number of attribution nodes")
+ .that(buffer.get()).isEqualTo((byte) uids.length);
+
+ for (int i = 0; i < tags.length; i++) {
+ assertWithMessage("Incorrect uid in Attribution Chain")
+ .that(buffer.getInt()).isEqualTo(uids[i]);
+
+ final String tag = getStringFromByteBuffer(buffer);
+ assertWithMessage("Incorrect tag in Attribution Chain")
+ .that(tag).isEqualTo(tags[i]);
+ }
+
+ assertWithMessage("Second field is not Long")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect field 2")
+ .that(buffer.getLong()).isEqualTo(field2);
+
+ assertThat(statsEvent.getNumBytes()).isEqualTo(buffer.position());
+
+ statsEvent.release();
+ }
+
+ @Test
+ public void testKeyValuePairs() {
+ final int expectedAtomId = 109;
+ final SparseIntArray intMap = new SparseIntArray();
+ final SparseLongArray longMap = new SparseLongArray();
+ final SparseArray<String> stringMap = new SparseArray<>();
+ final SparseArray<Float> floatMap = new SparseArray<>();
+ intMap.put(1, -1);
+ intMap.put(2, -2);
+ stringMap.put(3, "abc");
+ stringMap.put(4, "2h");
+ floatMap.put(9, -234.344f);
+
+ final long minTimestamp = SystemClock.elapsedRealtimeNanos();
+ final StatsEvent statsEvent = StatsEvent.newBuilder()
+ .setAtomId(expectedAtomId)
+ .writeKeyValuePairs(intMap, longMap, stringMap, floatMap)
+ .build();
+ final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
+
+ assertThat(statsEvent.getAtomId()).isEqualTo(expectedAtomId);
+
+ final ByteBuffer buffer =
+ ByteBuffer.wrap(statsEvent.getBytes()).order(ByteOrder.LITTLE_ENDIAN);
+
+ assertWithMessage("Root element in buffer is not TYPE_OBJECT")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_OBJECT);
+
+ assertWithMessage("Incorrect number of elements in root object")
+ .that(buffer.get()).isEqualTo(3);
+
+ assertWithMessage("First element is not timestamp")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect timestamp")
+ .that(buffer.getLong()).isIn(Range.closed(minTimestamp, maxTimestamp));
+
+ assertWithMessage("Second element is not atom id")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect atom id")
+ .that(buffer.getInt()).isEqualTo(expectedAtomId);
+
+ assertWithMessage("First field is not KeyValuePairs")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_KEY_VALUE_PAIRS);
+
+ assertWithMessage("Incorrect number of key value pairs")
+ .that(buffer.get()).isEqualTo(
+ (byte) (intMap.size() + longMap.size() + stringMap.size()
+ + floatMap.size()));
+
+ for (int i = 0; i < intMap.size(); i++) {
+ assertWithMessage("Incorrect key in intMap")
+ .that(buffer.getInt()).isEqualTo(intMap.keyAt(i));
+ assertWithMessage("The type id of the value should be TYPE_INT in intMap")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+ assertWithMessage("Incorrect value in intMap")
+ .that(buffer.getInt()).isEqualTo(intMap.valueAt(i));
+ }
+
+ for (int i = 0; i < longMap.size(); i++) {
+ assertWithMessage("Incorrect key in longMap")
+ .that(buffer.getInt()).isEqualTo(longMap.keyAt(i));
+ assertWithMessage("The type id of the value should be TYPE_LONG in longMap")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+ assertWithMessage("Incorrect value in longMap")
+ .that(buffer.getLong()).isEqualTo(longMap.valueAt(i));
+ }
+
+ for (int i = 0; i < stringMap.size(); i++) {
+ assertWithMessage("Incorrect key in stringMap")
+ .that(buffer.getInt()).isEqualTo(stringMap.keyAt(i));
+ assertWithMessage("The type id of the value should be TYPE_STRING in stringMap")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_STRING);
+ final String value = getStringFromByteBuffer(buffer);
+ assertWithMessage("Incorrect value in stringMap")
+ .that(value).isEqualTo(stringMap.valueAt(i));
+ }
+
+ for (int i = 0; i < floatMap.size(); i++) {
+ assertWithMessage("Incorrect key in floatMap")
+ .that(buffer.getInt()).isEqualTo(floatMap.keyAt(i));
+ assertWithMessage("The type id of the value should be TYPE_FLOAT in floatMap")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_FLOAT);
+ assertWithMessage("Incorrect value in floatMap")
+ .that(buffer.getFloat()).isEqualTo(floatMap.valueAt(i));
+ }
+
+ assertThat(statsEvent.getNumBytes()).isEqualTo(buffer.position());
+
+ statsEvent.release();
+ }
+
+ @Test
+ public void testSingleAnnotations() {
+ final int expectedAtomId = 109;
+ final int field1 = 1;
+ final byte field1AnnotationId = 45;
+ final boolean field1AnnotationValue = false;
+ final boolean field2 = true;
+ final byte field2AnnotationId = 1;
+ final int field2AnnotationValue = 23;
+
+ final long minTimestamp = SystemClock.elapsedRealtimeNanos();
+ final StatsEvent statsEvent = StatsEvent.newBuilder()
+ .setAtomId(expectedAtomId)
+ .writeInt(field1)
+ .addBooleanAnnotation(field1AnnotationId, field1AnnotationValue)
+ .writeBoolean(field2)
+ .addIntAnnotation(field2AnnotationId, field2AnnotationValue)
+ .build();
+ final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
+
+ assertThat(statsEvent.getAtomId()).isEqualTo(expectedAtomId);
+
+ final ByteBuffer buffer =
+ ByteBuffer.wrap(statsEvent.getBytes()).order(ByteOrder.LITTLE_ENDIAN);
+
+ assertWithMessage("Root element in buffer is not TYPE_OBJECT")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_OBJECT);
+
+ assertWithMessage("Incorrect number of elements in root object")
+ .that(buffer.get()).isEqualTo(4);
+
+ assertWithMessage("First element is not timestamp")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_LONG);
+
+ assertWithMessage("Incorrect timestamp")
+ .that(buffer.getLong()).isIn(Range.closed(minTimestamp, maxTimestamp));
+
+ assertWithMessage("Second element is not atom id")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+
+ assertWithMessage("Incorrect atom id")
+ .that(buffer.getInt()).isEqualTo(expectedAtomId);
+
+ final byte field1Header = buffer.get();
+ final int field1AnnotationValueCount = field1Header >> 4;
+ final byte field1Type = (byte) (field1Header & 0x0F);
+ assertWithMessage("First field is not Int")
+ .that(field1Type).isEqualTo(StatsEvent.TYPE_INT);
+ assertWithMessage("First field annotation count is wrong")
+ .that(field1AnnotationValueCount).isEqualTo(1);
+ assertWithMessage("Incorrect field 1")
+ .that(buffer.getInt()).isEqualTo(field1);
+ assertWithMessage("First field's annotation id is wrong")
+ .that(buffer.get()).isEqualTo(field1AnnotationId);
+ assertWithMessage("First field's annotation type is wrong")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_BOOLEAN);
+ assertWithMessage("First field's annotation value is wrong")
+ .that(buffer.get()).isEqualTo(field1AnnotationValue ? 1 : 0);
+
+ final byte field2Header = buffer.get();
+ final int field2AnnotationValueCount = field2Header >> 4;
+ final byte field2Type = (byte) (field2Header & 0x0F);
+ assertWithMessage("Second field is not boolean")
+ .that(field2Type).isEqualTo(StatsEvent.TYPE_BOOLEAN);
+ assertWithMessage("Second field annotation count is wrong")
+ .that(field2AnnotationValueCount).isEqualTo(1);
+ assertWithMessage("Incorrect field 2")
+ .that(buffer.get()).isEqualTo(field2 ? 1 : 0);
+ assertWithMessage("Second field's annotation id is wrong")
+ .that(buffer.get()).isEqualTo(field2AnnotationId);
+ assertWithMessage("Second field's annotation type is wrong")
+ .that(buffer.get()).isEqualTo(StatsEvent.TYPE_INT);
+ assertWithMessage("Second field's annotation value is wrong")
+ .that(buffer.getInt()).isEqualTo(field2AnnotationValue);
+
+ assertThat(statsEvent.getNumBytes()).isEqualTo(buffer.position());
+
+ statsEvent.release();
+ }
+
+ private static byte[] getByteArrayFromByteBuffer(final ByteBuffer buffer) {
+ final int numBytes = buffer.getInt();
+ byte[] bytes = new byte[numBytes];
+ buffer.get(bytes);
+ return bytes;
+ }
+
+ private static String getStringFromByteBuffer(final ByteBuffer buffer) {
+ final byte[] bytes = getByteArrayFromByteBuffer(buffer);
+ return new String(bytes, UTF_8);
+ }
+}
diff --git a/location/java/android/location/Location.java b/location/java/android/location/Location.java
index 27274d1..db48ee7 100644
--- a/location/java/android/location/Location.java
+++ b/location/java/android/location/Location.java
@@ -161,7 +161,10 @@
* <p>By default time, latitude and longitude are 0, and the location
* has no bearing, altitude, speed, accuracy or extras.
*
- * @param provider the name of the provider that generated this location
+ * @param provider the source that provides the location. It can be of type
+ * {@link LocationManager#GPS_PROVIDER}, {@link LocationManager#NETWORK_PROVIDER},
+ * or {@link LocationManager#PASSIVE_PROVIDER}. You can also define your own
+ * provider string, in which case an empty string is a valid provider.
*/
public Location(String provider) {
mProvider = provider;
diff --git a/location/java/android/location/OnNmeaMessageListener.java b/location/java/android/location/OnNmeaMessageListener.java
index ccf6ce8..05647bc 100644
--- a/location/java/android/location/OnNmeaMessageListener.java
+++ b/location/java/android/location/OnNmeaMessageListener.java
@@ -28,7 +28,9 @@
/**
* Called when an NMEA message is received.
* @param message NMEA message
- * @param timestamp milliseconds since January 1, 1970.
+ * @param timestamp Date and time of the location fix, as reported by the GNSS
+ * chipset. The value is specified in milliseconds since 0:00
+ * UTC 1 January 1970.
*/
void onNmeaMessage(String message, long timestamp);
}
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java
index 8cd33a5..b739ee6 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java
@@ -18,6 +18,7 @@
import android.content.Context;
import android.content.Intent;
+import android.content.pm.ActivityInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
@@ -33,7 +34,7 @@
public class ActivityTile extends Tile {
private static final String TAG = "ActivityTile";
- public ActivityTile(ComponentInfo info, String category) {
+ public ActivityTile(ActivityInfo info, String category) {
super(info, category);
setMetaData(info.metaData);
}
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/MasterSwitchController.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/MasterSwitchController.java
new file mode 100644
index 0000000..a12aa83
--- /dev/null
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/MasterSwitchController.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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 com.android.settingslib.drawer;
+
+import android.os.Bundle;
+
+/**
+ * A controller that manages event for master switch.
+ */
+public abstract class MasterSwitchController extends SwitchController {
+
+ @Override
+ protected final MetaData getMetaData() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ final Bundle getBundle() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ProviderTile.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ProviderTile.java
index b2ba5de..312d30e 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ProviderTile.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ProviderTile.java
@@ -42,10 +42,10 @@
private String mAuthority;
private String mKey;
- public ProviderTile(ComponentInfo info, String category, Bundle metaData) {
+ public ProviderTile(ProviderInfo info, String category, Bundle metaData) {
super(info, category);
setMetaData(metaData);
- mAuthority = ((ProviderInfo) info).authority;
+ mAuthority = info.authority;
mKey = metaData.getString(META_DATA_PREFERENCE_KEYHINT);
}
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchController.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchController.java
index e48da86..23669b2 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchController.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchController.java
@@ -108,7 +108,7 @@
Bundle getBundle() {
final MetaData metaData = getMetaData();
if (metaData == null) {
- throw new IllegalArgumentException("Should not return null in getMetaData()");
+ throw new NullPointerException("Should not return null in getMetaData()");
}
final Bundle bundle = metaData.build();
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchesProvider.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchesProvider.java
index a05c7d5..73f1a90 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchesProvider.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/SwitchesProvider.java
@@ -55,7 +55,7 @@
private String mAuthority;
private final Map<String, SwitchController> mControllerMap = new LinkedHashMap<>();
- private final List<Bundle> mSwitchList = new ArrayList<>();
+ private final List<Bundle> mSwitchDataList = new ArrayList<>();
/**
* Get a list of {@link SwitchController} for this provider.
@@ -88,7 +88,9 @@
controller.setAuthority(mAuthority);
mControllerMap.put(key, controller);
- mSwitchList.add(controller.getBundle());
+ if (!(controller instanceof MasterSwitchController)) {
+ mSwitchDataList.add(controller.getBundle());
+ }
});
return true;
}
@@ -101,7 +103,7 @@
: null;
if (TextUtils.isEmpty(key)) {
if (METHOD_GET_SWITCH_DATA.equals(method)) {
- bundle.putParcelableList(EXTRA_SWITCH_DATA, mSwitchList);
+ bundle.putParcelableList(EXTRA_SWITCH_DATA, mSwitchDataList);
return bundle;
}
return null;
@@ -114,7 +116,10 @@
switch (method) {
case METHOD_GET_SWITCH_DATA:
- return controller.getBundle();
+ if (!(controller instanceof MasterSwitchController)) {
+ return controller.getBundle();
+ }
+ break;
case METHOD_GET_PROVIDER_ICON:
if (controller instanceof ProviderIcon) {
return ((ProviderIcon) controller).getProviderIcon();
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
index 71ffff7..f93faeb 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
@@ -244,15 +244,15 @@
// TODO: Needs much optimization, too many PM queries going on here.
if (user.getIdentifier() == ActivityManager.getCurrentUser()) {
// Only add Settings for this user.
- getTilesForAction(context, user, SETTINGS_ACTION, cache, null, tiles, true);
- getTilesForAction(context, user, OPERATOR_SETTINGS, cache,
+ loadTilesForAction(context, user, SETTINGS_ACTION, cache, null, tiles, true);
+ loadTilesForAction(context, user, OPERATOR_SETTINGS, cache,
OPERATOR_DEFAULT_CATEGORY, tiles, false);
- getTilesForAction(context, user, MANUFACTURER_SETTINGS, cache,
+ loadTilesForAction(context, user, MANUFACTURER_SETTINGS, cache,
MANUFACTURER_DEFAULT_CATEGORY, tiles, false);
}
if (setup) {
- getTilesForAction(context, user, EXTRA_SETTINGS_ACTION, cache, null, tiles, false);
- getTilesForAction(context, user, IA_SETTINGS_ACTION, cache, null, tiles, false);
+ loadTilesForAction(context, user, EXTRA_SETTINGS_ACTION, cache, null, tiles, false);
+ loadTilesForAction(context, user, IA_SETTINGS_ACTION, cache, null, tiles, false);
}
}
@@ -284,18 +284,18 @@
}
@VisibleForTesting
- static void getTilesForAction(Context context,
+ static void loadTilesForAction(Context context,
UserHandle user, String action, Map<Pair<String, String>, Tile> addedCache,
String defaultCategory, List<Tile> outTiles, boolean requireSettings) {
final Intent intent = new Intent(action);
if (requireSettings) {
intent.setPackage(SETTING_PKG);
}
- getActivityTiles(context, user, addedCache, defaultCategory, outTiles, intent);
- getProviderTiles(context, user, addedCache, defaultCategory, outTiles, intent);
+ loadActivityTiles(context, user, addedCache, defaultCategory, outTiles, intent);
+ loadProviderTiles(context, user, addedCache, defaultCategory, outTiles, intent);
}
- private static void getActivityTiles(Context context,
+ private static void loadActivityTiles(Context context,
UserHandle user, Map<Pair<String, String>, Tile> addedCache,
String defaultCategory, List<Tile> outTiles, Intent intent) {
final PackageManager pm = context.getPackageManager();
@@ -308,11 +308,11 @@
}
final ActivityInfo activityInfo = resolved.activityInfo;
final Bundle metaData = activityInfo.metaData;
- getTile(user, addedCache, defaultCategory, outTiles, intent, metaData, activityInfo);
+ loadTile(user, addedCache, defaultCategory, outTiles, intent, metaData, activityInfo);
}
}
- private static void getProviderTiles(Context context,
+ private static void loadProviderTiles(Context context,
UserHandle user, Map<Pair<String, String>, Tile> addedCache,
String defaultCategory, List<Tile> outTiles, Intent intent) {
final PackageManager pm = context.getPackageManager();
@@ -330,13 +330,13 @@
continue;
}
for (Bundle metaData : switchData) {
- getTile(user, addedCache, defaultCategory, outTiles, intent, metaData,
+ loadTile(user, addedCache, defaultCategory, outTiles, intent, metaData,
providerInfo);
}
}
}
- private static void getTile(UserHandle user, Map<Pair<String, String>, Tile> addedCache,
+ private static void loadTile(UserHandle user, Map<Pair<String, String>, Tile> addedCache,
String defaultCategory, List<Tile> outTiles, Intent intent, Bundle metaData,
ComponentInfo componentInfo) {
String categoryKey = defaultCategory;
@@ -359,8 +359,8 @@
Tile tile = addedCache.get(key);
if (tile == null) {
tile = isProvider
- ? new ProviderTile(componentInfo, categoryKey, metaData)
- : new ActivityTile(componentInfo, categoryKey);
+ ? new ProviderTile((ProviderInfo) componentInfo, categoryKey, metaData)
+ : new ActivityTile((ActivityInfo) componentInfo, categoryKey);
addedCache.put(key, tile);
} else {
tile.setMetaData(metaData);
@@ -516,7 +516,7 @@
* @param value Boolean associated with the key
* @return Bundle associated with the action, if returned by the content provider
*/
- public static Bundle putBooleanToUri(Context context, Uri uri,
+ public static Bundle putBooleanToUriAndGetResult(Context context, Uri uri,
Map<String, IContentProvider> providerMap, String key, boolean value) {
final Bundle bundle = new Bundle();
bundle.putBoolean(key, value);
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
index 0095692..833c4ac 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
@@ -241,9 +241,7 @@
public void disconnect() {
synchronized (mProfileLock) {
- for (LocalBluetoothProfile profile : mProfiles) {
- disconnect(profile);
- }
+ mLocalAdapter.disconnectAllEnabledProfiles(mDevice);
}
// Disconnect PBAP server in case its connected
// This is to ensure all the profiles are disconnected as some CK/Hs do not
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/MasterSwitchControllerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/MasterSwitchControllerTest.java
new file mode 100644
index 0000000..69d0f2e
--- /dev/null
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/MasterSwitchControllerTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2019 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 com.android.settingslib.drawer;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+@RunWith(RobolectricTestRunner.class)
+public class MasterSwitchControllerTest {
+
+ @Rule
+ public final ExpectedException thrown = ExpectedException.none();
+
+ private MasterSwitchController mController;
+
+ @Before
+ public void setUp() {
+ mController = new TestMasterSwitchController("123");
+ }
+
+ @Test
+ public void getMetaData_shouldThrowUnsupportedOperationException() {
+ thrown.expect(UnsupportedOperationException.class);
+
+ mController.getMetaData();
+ }
+
+ @Test
+ public void getBundle_shouldThrowUnsupportedOperationException() {
+ thrown.expect(UnsupportedOperationException.class);
+
+ mController.getBundle();
+ }
+
+ static class TestMasterSwitchController extends MasterSwitchController {
+
+ private String mKey;
+
+ TestMasterSwitchController(String key) {
+ mKey = key;
+ }
+
+ @Override
+ public String getSwitchKey() {
+ return mKey;
+ }
+
+ @Override
+ protected boolean isChecked() {
+ return true;
+ }
+
+ @Override
+ protected boolean onCheckedChanged(boolean checked) {
+ return true;
+ }
+
+ @Override
+ protected String getErrorMessage(boolean attemptedChecked) {
+ return null;
+ }
+ }
+}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/SwitchesProviderTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/SwitchesProviderTest.java
index 27b3697..a740e68 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/SwitchesProviderTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/SwitchesProviderTest.java
@@ -35,6 +35,7 @@
import android.content.pm.ProviderInfo;
import android.os.Bundle;
+import com.android.settingslib.drawer.MasterSwitchControllerTest.TestMasterSwitchController;
import com.android.settingslib.drawer.SwitchController.MetaData;
import org.junit.Before;
@@ -84,8 +85,8 @@
}
@Test
- public void attachInfo_NoMetaDataInController_shouldThrowIllegalArgumentException() {
- thrown.expect(IllegalArgumentException.class);
+ public void attachInfo_NoMetaDataInController_shouldThrowNullPointerException() {
+ thrown.expect(NullPointerException.class);
final TestSwitchController controller = new TestSwitchController();
controller.setKey("123");
mSwitchesProvider.addSwitchController(controller);
@@ -123,6 +124,19 @@
}
@Test
+ public void getSwitchData_shouldNotReturnMasterSwitchData() {
+ final SwitchController controller = new TestMasterSwitchController("123");
+ mSwitchesProvider.addSwitchController(controller);
+ mSwitchesProvider.attachInfo(mContext, mProviderInfo);
+
+ final Bundle switchData = mSwitchesProvider.call(METHOD_GET_SWITCH_DATA, "uri" ,
+ null /* extras*/);
+
+ final ArrayList<Bundle> dataList = switchData.getParcelableArrayList(EXTRA_SWITCH_DATA);
+ assertThat(dataList).isEmpty();
+ }
+
+ @Test
public void getSwitchData_shouldReturnDataList() {
final TestSwitchController controller = new TestSwitchController();
controller.setKey("123");
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
index b36eb49..9b4b97e 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
@@ -113,7 +113,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles).hasSize(2);
@@ -135,7 +135,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* requiresSettings */);
assertThat(outTiles).hasSize(2);
@@ -156,7 +156,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION,
addedCache, null /* defaultCategory */, outTiles, false /* requiresSettings */);
assertThat(outTiles).isEmpty();
@@ -197,7 +197,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles).hasSize(2);
@@ -222,7 +222,7 @@
when(mResources.getString(eq(123)))
.thenReturn("my localized title");
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles).hasSize(2);
assertThat(outTiles.get(0).getTitle(mContext)).isEqualTo("my localized title");
@@ -245,7 +245,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles.get(0).isIconTintable(mContext)).isFalse();
@@ -266,7 +266,7 @@
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles).hasSize(1);
@@ -276,7 +276,7 @@
resolveInfo.activityInfo.metaData.putInt(META_DATA_PREFERENCE_ICON,
com.android.internal.R.drawable.ic_phone);
outTiles.clear();
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles).hasSize(1);
@@ -300,7 +300,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles.get(0).isIconTintable(mContext)).isTrue();
@@ -321,7 +321,7 @@
when(mPackageManager.queryIntentContentProvidersAsUser(any(Intent.class), anyInt(),
anyInt())).thenReturn(info);
- TileUtils.getTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
+ TileUtils.loadTilesForAction(mContext, UserHandle.CURRENT, IA_SETTINGS_ACTION, addedCache,
null /* defaultCategory */, outTiles, false /* usePriority */);
assertThat(outTiles).hasSize(2);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 55a51da..33e0fd2 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -2248,12 +2248,6 @@
SecureSettingsProto.Notification.IN_CALL_NOTIFICATION_ENABLED);
p.end(notificationToken);
- final long packageVerifierToken = p.start(SecureSettingsProto.PACKAGE_VERIFIER);
- dumpSetting(s, p,
- Settings.Secure.PACKAGE_VERIFIER_USER_CONSENT,
- SecureSettingsProto.PackageVerifier.USER_CONSENT);
- p.end(packageVerifierToken);
-
final long parentalControlToken = p.start(SecureSettingsProto.PARENTAL_CONTROL);
dumpSetting(s, p,
Settings.Secure.PARENTAL_CONTROL_ENABLED,
diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
index 289ac80..7b022a2 100644
--- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
@@ -662,7 +662,6 @@
Settings.Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED,
Settings.Secure.ODI_CAPTIONS_ENABLED,
- Settings.Secure.PACKAGE_VERIFIER_USER_CONSENT,
Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
Settings.Secure.PAYMENT_SERVICE_SEARCH_URI,
Settings.Secure.PRINT_SERVICE_SEARCH_URI,
diff --git a/packages/Tethering/Android.bp b/packages/Tethering/Android.bp
index 61bfb92..7b35f4d 100644
--- a/packages/Tethering/Android.bp
+++ b/packages/Tethering/Android.bp
@@ -20,12 +20,14 @@
srcs: [
"src/**/*.java",
":framework-tethering-shared-srcs",
+ ":net-module-utils-srcs",
":services-tethering-shared-srcs",
":servicescore-tethering-src",
],
static_libs: [
"androidx.annotation_annotation",
"netd_aidl_interface-java",
+ "netlink-client",
"networkstack-aidl-interfaces-java",
"android.hardware.tetheroffload.control-V1.0-java",
"tethering-client",
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
index cb858ac..339fc96 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
@@ -1217,8 +1217,8 @@
if (mAccessibilityFocusedWindowId != windowId) {
clearAccessibilityFocusLocked(mAccessibilityFocusedWindowId);
setAccessibilityFocusedWindowLocked(windowId);
- mAccessibilityFocusNodeId = nodeId;
}
+ mAccessibilityFocusNodeId = nodeId;
}
} break;
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index a75d5d69..7d7104c 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -3185,7 +3185,7 @@
if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
updateAllVpnsCapabilities();
}
- rematchAllNetworksAndRequests(null, 0);
+ rematchAllNetworksAndRequests();
mLingerMonitor.noteDisconnect(nai);
if (nai.created) {
// Tell netd to clean up the configuration for this network
@@ -3271,8 +3271,7 @@
}
}
}
- rematchAllNetworksAndRequests(null, 0);
- ensureRunningOnConnectivityServiceThread();
+ rematchAllNetworksAndRequests();
if (nri.request.isRequest() && nri.mSatisfier == null) {
sendUpdatedScoreToFactories(nri.request, null);
}
@@ -3515,13 +3514,12 @@
}
if (accept != nai.networkMisc.acceptUnvalidated) {
- int oldScore = nai.getCurrentScore();
nai.networkMisc.acceptUnvalidated = accept;
// If network becomes partial connectivity and user already accepted to use this
// network, we should respect the user's option and don't need to popup the
// PARTIAL_CONNECTIVITY notification to user again.
nai.networkMisc.acceptPartialConnectivity = accept;
- rematchAllNetworksAndRequests(nai, oldScore);
+ rematchAllNetworksAndRequests();
sendUpdatedScoreToFactories(nai);
}
@@ -3590,9 +3588,8 @@
return;
}
if (!nai.avoidUnvalidated) {
- int oldScore = nai.getCurrentScore();
nai.avoidUnvalidated = true;
- rematchAllNetworksAndRequests(nai, oldScore);
+ rematchAllNetworksAndRequests();
sendUpdatedScoreToFactories(nai);
}
}
@@ -3693,7 +3690,7 @@
private void rematchForAvoidBadWifiUpdate() {
- rematchAllNetworksAndRequests(null, 0);
+ rematchAllNetworksAndRequests();
for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
sendUpdatedScoreToFactories(nai);
@@ -5965,7 +5962,7 @@
} else {
// If the requestable capabilities have changed or the score changed, we can't have been
// called by rematchNetworkAndRequests, so it's safe to start a rematch.
- rematchAllNetworksAndRequests(nai, oldScore);
+ rematchAllNetworksAndRequests();
notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
}
@@ -6294,6 +6291,41 @@
}
}
+ private ArrayMap<NetworkRequestInfo, NetworkAgentInfo> computeRequestReassignmentForNetwork(
+ @NonNull final NetworkAgentInfo newNetwork) {
+ final int score = newNetwork.getCurrentScore();
+ final ArrayMap<NetworkRequestInfo, NetworkAgentInfo> reassignedRequests = new ArrayMap<>();
+ for (NetworkRequestInfo nri : mNetworkRequests.values()) {
+ // Process requests in the first pass and listens in the second pass. This allows us to
+ // change a network's capabilities depending on which requests it has. This is only
+ // correct if the change in capabilities doesn't affect whether the network satisfies
+ // requests or not, and doesn't affect the network's score.
+ if (nri.request.isListen()) continue;
+
+ final NetworkAgentInfo currentNetwork = nri.mSatisfier;
+ final boolean satisfies = newNetwork.satisfies(nri.request);
+ if (newNetwork == currentNetwork && satisfies) continue;
+
+ // check if it satisfies the NetworkCapabilities
+ if (VDBG) log(" checking if request is satisfied: " + nri.request);
+ if (satisfies) {
+ // next check if it's better than any current network we're using for
+ // this request
+ if (VDBG || DDBG) {
+ log("currentScore = "
+ + (currentNetwork != null ? currentNetwork.getCurrentScore() : 0)
+ + ", newScore = " + score);
+ }
+ if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
+ reassignedRequests.put(nri, newNetwork);
+ }
+ } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
+ reassignedRequests.put(nri, null);
+ }
+ }
+ return reassignedRequests;
+ }
+
// Handles a network appearing or improving its score.
//
// - Evaluates all current NetworkRequests that can be
@@ -6307,10 +6339,6 @@
// - Tears down newNetwork if it just became validated
// but turns out to be unneeded.
//
- // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
- // networks that have no chance (i.e. even if validated)
- // of becoming the highest scoring network.
- //
// NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
// it does not remove NetworkRequests that other Networks could better satisfy.
// If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
@@ -6318,11 +6346,8 @@
// as it performs better by a factor of the number of Networks.
//
// @param newNetwork is the network to be matched against NetworkRequests.
- // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
- // performed to tear down unvalidated networks that have no chance (i.e. even if
- // validated) of becoming the highest scoring network.
- private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
- ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
+ // @param now the time the rematch starts, as returned by SystemClock.elapsedRealtime();
+ private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, long now) {
ensureRunningOnConnectivityServiceThread();
if (!newNetwork.everConnected) return;
boolean keep = newNetwork.isVPN();
@@ -6334,39 +6359,11 @@
if (VDBG || DDBG) log("rematching " + newNetwork.name());
- final ArrayMap<NetworkRequestInfo, NetworkAgentInfo> reassignedRequests = new ArrayMap<>();
+ final ArrayMap<NetworkRequestInfo, NetworkAgentInfo> reassignedRequests =
+ computeRequestReassignmentForNetwork(newNetwork);
NetworkCapabilities nc = newNetwork.networkCapabilities;
if (VDBG) log(" network has: " + nc);
- for (NetworkRequestInfo nri : mNetworkRequests.values()) {
- // Process requests in the first pass and listens in the second pass. This allows us to
- // change a network's capabilities depending on which requests it has. This is only
- // correct if the change in capabilities doesn't affect whether the network satisfies
- // requests or not, and doesn't affect the network's score.
- if (nri.request.isListen()) continue;
-
- ensureRunningOnConnectivityServiceThread();
- final NetworkAgentInfo currentNetwork = nri.mSatisfier;
- final boolean satisfies = newNetwork.satisfies(nri.request);
- if (newNetwork == currentNetwork && satisfies) continue;
-
- // check if it satisfies the NetworkCapabilities
- if (VDBG) log(" checking if request is satisfied: " + nri.request);
- if (satisfies) {
- // next check if it's better than any current network we're using for
- // this request
- if (VDBG || DDBG) {
- log("currentScore = " +
- (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
- ", newScore = " + score);
- }
- if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
- reassignedRequests.put(nri, newNetwork);
- }
- } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
- reassignedRequests.put(nri, null);
- }
- }
// Find and migrate to this Network any NetworkRequests for
// which this network is now the best.
@@ -6549,66 +6546,43 @@
mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
}
}
- if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
- if (unneeded(nai, UnneededFor.TEARDOWN)) {
- if (nai.getLingerExpiry() > 0) {
- // This network has active linger timers and no requests, but is not
- // lingering. Linger it.
- //
- // One way (the only way?) this can happen if this network is unvalidated
- // and became unneeded due to another network improving its score to the
- // point where this network will no longer be able to satisfy any requests
- // even if it validates.
- updateLingerState(nai, now);
- } else {
- if (DBG) log("Reaping " + nai.name());
- teardownUnneededNetwork(nai);
- }
- }
- }
- }
}
/**
* Attempt to rematch all Networks with NetworkRequests. This may result in Networks
* being disconnected.
- * @param changed If only one Network's score or capabilities have been modified since the last
- * time this function was called, pass this Network in this argument, otherwise pass
- * null.
- * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
- * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
- * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
- * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
- * network's score.
*/
- private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
- // TODO: This may get slow. The "changed" parameter is provided for future optimization
- // to avoid the slowness. It is not simply enough to process just "changed", for
- // example in the case where "changed"'s score decreases and another network should begin
- // satisfying a NetworkRequest that "changed" currently satisfies.
-
- // Optimization: Only reprocess "changed" if its score improved. This is safe because it
- // can only add more NetworkRequests satisfied by "changed", and this is exactly what
- // rematchNetworkAndRequests() handles.
+ private void rematchAllNetworksAndRequests() {
+ // TODO: This may be slow, and should be optimized. Unfortunately at this moment the
+ // processing is network-major instead of request-major (the code iterates through all
+ // networks, then for each it iterates for all requests), which is a problem for re-scoring
+ // requests. Once the code has switched to a request-major iteration style, this can
+ // be optimized to only do the processing needed.
final long now = SystemClock.elapsedRealtime();
- if (changed != null && oldScore < changed.getCurrentScore()) {
- rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
- } else {
- final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
- new NetworkAgentInfo[mNetworkAgentInfos.size()]);
- // Rematch higher scoring networks first to prevent requests first matching a lower
- // scoring network and then a higher scoring network, which could produce multiple
- // callbacks and inadvertently unlinger networks.
- Arrays.sort(nais);
- for (NetworkAgentInfo nai : nais) {
- rematchNetworkAndRequests(nai,
- // Only reap the last time through the loop. Reaping before all rematching
- // is complete could incorrectly teardown a network that hasn't yet been
- // rematched.
- (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
- : ReapUnvalidatedNetworks.REAP,
- now);
+ final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
+ new NetworkAgentInfo[mNetworkAgentInfos.size()]);
+ // Rematch higher scoring networks first to prevent requests first matching a lower
+ // scoring network and then a higher scoring network, which could produce multiple
+ // callbacks and inadvertently unlinger networks.
+ Arrays.sort(nais);
+ for (NetworkAgentInfo nai : nais) {
+ rematchNetworkAndRequests(nai, now);
+ }
+ for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ if (unneeded(nai, UnneededFor.TEARDOWN)) {
+ if (nai.getLingerExpiry() > 0) {
+ // This network has active linger timers and no requests, but is not
+ // lingering. Linger it.
+ //
+ // One way (the only way?) this can happen if this network is unvalidated
+ // and became unneeded due to another network improving its score to the
+ // point where this network will no longer be able to satisfy any requests
+ // even if it validates.
+ updateLingerState(nai, now);
+ } else {
+ if (DBG) log("Reaping " + nai.name());
+ teardownUnneededNetwork(nai);
+ }
}
}
}
@@ -6707,8 +6681,7 @@
}
// Consider network even though it is not yet validated.
- final long now = SystemClock.elapsedRealtime();
- rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
+ rematchAllNetworksAndRequests();
// This has to happen after matching the requests, because callbacks are just requests.
notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
@@ -6729,7 +6702,7 @@
state == NetworkInfo.State.SUSPENDED)) {
// going into or coming out of SUSPEND: re-score and notify
if (networkAgent.getCurrentScore() != oldScore) {
- rematchAllNetworksAndRequests(networkAgent, oldScore);
+ rematchAllNetworksAndRequests();
}
updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
networkAgent.networkCapabilities);
@@ -6743,19 +6716,9 @@
}
private void updateNetworkScore(NetworkAgentInfo nai, NetworkScore ns) {
- int score = ns.getIntExtension(NetworkScore.LEGACY_SCORE);
- if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
- if (score < 0) {
- loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
- "). Bumping score to min of 0");
- score = 0;
- }
-
- final int oldScore = nai.getCurrentScore();
+ if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + ns);
nai.setNetworkScore(ns);
-
- rematchAllNetworksAndRequests(nai, oldScore);
-
+ rematchAllNetworksAndRequests();
sendUpdatedScoreToFactories(nai);
}
diff --git a/services/core/java/com/android/server/NetworkScoreService.java b/services/core/java/com/android/server/NetworkScoreService.java
index df5005e..b26ef92 100644
--- a/services/core/java/com/android/server/NetworkScoreService.java
+++ b/services/core/java/com/android/server/NetworkScoreService.java
@@ -58,12 +58,10 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.content.PackageMonitor;
-import com.android.internal.os.TransferPipe;
import com.android.internal.util.DumpUtils;
import com.android.server.pm.permission.PermissionManagerServiceInternal;
import java.io.FileDescriptor;
-import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
@@ -903,17 +901,6 @@
}
writer.println("Current scorer: " + currentScorer);
- sendCacheUpdateCallback(new BiConsumer<INetworkScoreCache, Object>() {
- @Override
- public void accept(INetworkScoreCache networkScoreCache, Object cookie) {
- try {
- TransferPipe.dumpAsync(networkScoreCache.asBinder(), fd, args);
- } catch (IOException | RemoteException e) {
- writer.println("Failed to dump score cache: " + e);
- }
- }
- }, getScoreCacheLists());
-
synchronized (mServiceConnectionLock) {
if (mServiceConnection != null) {
mServiceConnection.dump(fd, writer, args);
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 4a925aa..d8ae1e4 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -80,6 +80,7 @@
import android.os.IStoraged;
import android.os.IVold;
import android.os.IVoldListener;
+import android.os.IVoldMountCallback;
import android.os.IVoldTaskListener;
import android.os.Looper;
import android.os.Message;
@@ -348,10 +349,6 @@
@GuardedBy("mLock")
private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
- /** Map from volume ID to latches */
- @GuardedBy("mLock")
- private ArrayMap<String, CountDownLatch> mFuseVolumeReadyLatches = new ArrayMap<>();
-
@GuardedBy("mLock")
private IPackageMoveObserver mMoveCallback;
@GuardedBy("mLock")
@@ -464,17 +461,6 @@
}
}
- private CountDownLatch findOrCreateFuseVolumeReadyLatch(String volId) {
- synchronized (mLock) {
- CountDownLatch latch = mFuseVolumeReadyLatches.get(volId);
- if (latch == null) {
- latch = new CountDownLatch(1);
- mFuseVolumeReadyLatches.put(volId, latch);
- }
- return latch;
- }
- }
-
/** List of crypto types.
* These must match CRYPT_TYPE_XXX in cryptfs.h AND their
* corresponding commands in CommandListener.cpp */
@@ -612,7 +598,6 @@
private static final int H_ABORT_IDLE_MAINT = 12;
private static final int H_BOOT_COMPLETED = 13;
private static final int H_COMPLETE_UNLOCK_USER = 14;
- private static final int H_VOLUME_READY = 15;
class StorageManagerServiceHandler extends Handler {
public StorageManagerServiceHandler(Looper looper) {
@@ -673,22 +658,6 @@
}
break;
}
- case H_VOLUME_READY: {
- final VolumeInfo vol = (VolumeInfo) msg.obj;
- try {
- mStorageSessionController.onVolumeReady(vol);
-
- synchronized (mLock) {
- CountDownLatch latch = mFuseVolumeReadyLatches.remove(vol.id);
- if (latch != null) {
- latch.countDown();
- }
- }
- } catch (IllegalStateException | ExternalStorageServiceException e) {
- Slog.i(TAG, "Failed to initialise volume " + vol, e);
- }
- break;
- }
case H_VOLUME_MOUNT: {
final VolumeInfo vol = (VolumeInfo) msg.obj;
if (isMountDisallowed(vol)) {
@@ -1431,13 +1400,6 @@
writeSettingsLocked();
}
- if (mIsFuseEnabled && newState == VolumeInfo.STATE_MOUNTED
- && (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_EMULATED)) {
- Slog.i(TAG, "Initialising volume " + vol + " ...");
- // TODO(b/144275217): Delay broadcasts till mount is really ready
- mHandler.obtainMessage(H_VOLUME_READY, vol).sendToTarget();
- }
-
mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
// Do not broadcast before boot has completed to avoid launching the
@@ -1912,33 +1874,29 @@
throw new SecurityException("Mounting " + volId + " restricted by policy");
}
- CountDownLatch latch = null;
- if (mIsFuseEnabled && StorageSessionController.isEmulatedOrPublic(vol)) {
- latch = findOrCreateFuseVolumeReadyLatch(volId);
- }
-
mount(vol);
-
- if (latch != null) {
- try {
- waitForLatch(latch, "mount " + volId, 3 * DateUtils.MINUTE_IN_MILLIS);
- } catch (TimeoutException e) {
- Slog.wtf(TAG, e);
- } finally {
- synchronized (mLock) {
- mFuseVolumeReadyLatches.remove(volId);
- }
- }
- }
}
private void mount(VolumeInfo vol) {
try {
// TODO(b/135341433): Remove paranoid logging when FUSE is stable
Slog.i(TAG, "Mounting volume " + vol);
- FileDescriptor fd = mVold.mount(vol.id, vol.mountFlags, vol.mountUserId);
+ mVold.mount(vol.id, vol.mountFlags, vol.mountUserId, new IVoldMountCallback.Stub() {
+ @Override
+ public boolean onVolumeChecking(FileDescriptor deviceFd, String path,
+ String internalPath) {
+ vol.path = path;
+ vol.internalPath = internalPath;
+ try {
+ mStorageSessionController.onVolumeMount(deviceFd, vol);
+ return true;
+ } catch (ExternalStorageServiceException e) {
+ Slog.i(TAG, "Failed to mount volume " + vol, e);
+ return false;
+ }
+ }
+ });
Slog.i(TAG, "Mounted volume " + vol);
- mStorageSessionController.onVolumeMount(fd, vol);
} catch (Exception e) {
Slog.wtf(TAG, e);
}
@@ -3643,7 +3601,7 @@
try {
mObbState.volId = mVold.createObb(mObbState.canonicalPath, binderKey,
mObbState.ownerGid);
- mVold.mount(mObbState.volId, 0, -1);
+ mVold.mount(mObbState.volId, 0, -1, null);
if (DEBUG_OBB)
Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 88d0e4b..5b7a814 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -568,6 +568,11 @@
private static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds;
private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes.
+ /**
+ * How long between a process kill and we actually receive its death recipient
+ */
+ private static final long PROC_KILL_TIMEOUT = 5000; // 5 seconds;
+
OomAdjuster mOomAdjuster;
final LowMemDetector mLowMemDetector;
@@ -3738,6 +3743,9 @@
"Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
handleAppDiedLocked(app, false, true);
+ // Execute the callback if there is any.
+ doAppDiedCallbackLocked(app);
+
if (doOomAdj) {
updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
}
@@ -3749,6 +3757,10 @@
reportUidInfoMessageLocked(TAG,
"Process " + app.processName + " (pid " + pid
+ ") has died and restarted (pid " + app.pid + ").", app.info.uid);
+
+ // Execute the callback if there is any.
+ doAppDiedCallbackLocked(app);
+
EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
} else if (DEBUG_PROCESSES) {
Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
@@ -3762,6 +3774,39 @@
}
}
+ @GuardedBy("this")
+ private void doAppDiedCallbackLocked(final ProcessRecord app) {
+ if (app.mAppDiedCallback != null) {
+ app.mAppDiedCallback.run();
+ app.mAppDiedCallback = null;
+ }
+ }
+
+ @GuardedBy("this")
+ private void waitForProcKillLocked(final ProcessRecord app, final String formatString,
+ final long startTime) {
+ app.mAppDiedCallback = () -> {
+ synchronized (ActivityManagerService.this) {
+ // called when this app receives appDiedLocked()
+ ActivityManagerService.this.notifyAll();
+ }
+ };
+ checkTime(startTime, String.format(formatString, "before appDied"));
+ long now = SystemClock.uptimeMillis();
+ long timeout = PROC_KILL_TIMEOUT + now;
+ while (app.mAppDiedCallback != null && timeout > now) {
+ try {
+ wait(timeout - now);
+ } catch (InterruptedException e) {
+ }
+ now = SystemClock.uptimeMillis();
+ }
+ checkTime(startTime, String.format(formatString, "after appDied"));
+ if (app.mAppDiedCallback != null) {
+ Slog.w(TAG, String.format(formatString, "waiting for app killing timed out"));
+ }
+ }
+
/**
* If a stack trace dump file is configured, dump process stack traces.
* @param firstPids of dalvik VM processes to dump stack traces for first
@@ -6779,18 +6824,12 @@
// Note if killedByAm is also set, this means the provider process has just been
// killed by AM (in ProcessRecord.kill()), but appDiedLocked() hasn't been called
- // yet. So we need to call appDiedLocked() here and let it clean up.
+ // yet. So we need to wait for appDiedLocked() here and let it clean up.
// (See the commit message on I2c4ba1e87c2d47f2013befff10c49b3dc337a9a7 to see
// how to test this case.)
if (cpr.proc.killed && cpr.proc.killedByAm) {
- checkTime(startTime, "getContentProviderImpl: before appDied (killedByAm)");
- final long iden = Binder.clearCallingIdentity();
- try {
- appDiedLocked(cpr.proc);
- } finally {
- Binder.restoreCallingIdentity(iden);
- }
- checkTime(startTime, "getContentProviderImpl: after appDied (killedByAm)");
+ waitForProcKillLocked(cpr.proc, "getContentProviderImpl: %s (killedByAm)",
+ startTime);
}
}
@@ -6894,9 +6933,7 @@
Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString()
+ " is crashing; detaching " + r);
boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
- checkTime(startTime, "getContentProviderImpl: before appDied");
- appDiedLocked(cpr.proc);
- checkTime(startTime, "getContentProviderImpl: after appDied");
+ waitForProcKillLocked(cpr.proc, "getContentProviderImpl: %s", startTime);
if (!lastRef) {
// This wasn't the last ref our process had on
// the provider... we have now been killed, bail.
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 5db6ff7..867571a 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -329,6 +329,9 @@
boolean mReachable; // Whether or not this process is reachable from given process
+ // A callback that should be executed on app died; after that it'll be set to null
+ Runnable mAppDiedCallback;
+
void setStartParams(int startUid, HostingRecord hostingRecord, String seInfo,
long startTime) {
this.startUid = startUid;
diff --git a/services/core/java/com/android/server/lights/LightsService.java b/services/core/java/com/android/server/lights/LightsService.java
index ac906bb..eaae2ed 100644
--- a/services/core/java/com/android/server/lights/LightsService.java
+++ b/services/core/java/com/android/server/lights/LightsService.java
@@ -84,8 +84,12 @@
if (DEBUG) {
Slog.d(TAG, "Using new setBrightness path!");
}
- SurfaceControl.setDisplayBrightness(mDisplayToken,
- (float) brightness / mSurfaceControlMaximumBrightness);
+ if (brightness == 0) {
+ SurfaceControl.setDisplayBrightness(mDisplayToken, -1.0f);
+ } else {
+ SurfaceControl.setDisplayBrightness(mDisplayToken,
+ (float) (brightness - 1) / (mSurfaceControlMaximumBrightness - 1));
+ }
} else {
int color = brightness & 0x000000ff;
color = 0xff000000 | (color << 16) | (color << 8) | color;
diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
index 08e55d3..c712431 100644
--- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java
+++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
@@ -34,8 +34,6 @@
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.storage.StorageManager;
-import android.provider.DeviceConfig;
-import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;
import android.util.StatsLog;
@@ -86,12 +84,6 @@
// Used for calculating space threshold for downgrading unused apps.
private static final int LOW_THRESHOLD_MULTIPLIER_FOR_DOWNGRADE = 2;
- private static final int DEFAULT_INACTIVE_APP_THRESHOLD_DAYS = 10;
-
- private static final String DOWNGRADE_UNUSED_APPS_ENABLED = "downgrade_unused_apps_enabled";
- private static final String INACTIVE_APP_THRESHOLD_DAYS = "inactive_app_threshold_days";
- private static final String LOW_STORAGE_MULTIPLIER_FOR_DOWNGRADE =
- "low_storage_threshold_multiplier_for_downgrade";
/**
* Set of failed packages remembered across job runs.
@@ -111,6 +103,8 @@
private final AtomicBoolean mExitPostBootUpdate = new AtomicBoolean(false);
private final File mDataDir = Environment.getDataDirectory();
+ private static final long mDowngradeUnusedAppsThresholdInMillis =
+ getDowngradeUnusedAppsThresholdInMillis();
public static void schedule(Context context) {
if (isBackgroundDexoptDisabled()) {
@@ -352,14 +346,14 @@
// Only downgrade apps when space is low on device.
// Threshold is selected above the lowStorageThreshold so that we can pro-actively clean
// up disk before user hits the actual lowStorageThreshold.
- final long lowStorageThresholdForDowngrade = getLowThresholdMultiplierForDowngrade()
+ final long lowStorageThresholdForDowngrade = LOW_THRESHOLD_MULTIPLIER_FOR_DOWNGRADE
* lowStorageThreshold;
boolean shouldDowngrade = shouldDowngrade(lowStorageThresholdForDowngrade);
Log.d(TAG, "Should Downgrade " + shouldDowngrade);
if (shouldDowngrade) {
Set<String> unusedPackages =
- pm.getUnusedPackages(getDowngradeUnusedAppsThresholdInMillis());
- Log.d(TAG, "Unused Packages " + String.join(",", unusedPackages));
+ pm.getUnusedPackages(mDowngradeUnusedAppsThresholdInMillis);
+ Log.d(TAG, "Unsused Packages " + String.join(",", unusedPackages));
if (!unusedPackages.isEmpty()) {
for (String pkg : unusedPackages) {
@@ -368,9 +362,12 @@
// Should be aborted by the scheduler.
return abortCode;
}
- if (downgradePackage(pm, pkg)) {
+ if (downgradePackage(pm, pkg, /*isForPrimaryDex*/ true)) {
updatedPackages.add(pkg);
}
+ if (supportSecondaryDex) {
+ downgradePackage(pm, pkg, /*isForPrimaryDex*/ false);
+ }
}
pkgs = new ArraySet<>(pkgs);
@@ -418,45 +415,39 @@
* Try to downgrade the package to a smaller compilation filter.
* eg. if the package is in speed-profile the package will be downgraded to verify.
* @param pm PackageManagerService
- * @param pkg The package to be downgraded
- * @return true if the package was downgraded
+ * @param pkg The package to be downgraded.
+ * @param isForPrimaryDex. Apps can have several dex file, primary and secondary.
+ * @return true if the package was downgraded.
*/
- private boolean downgradePackage(PackageManagerService pm, String pkg) {
+ private boolean downgradePackage(PackageManagerService pm, String pkg,
+ boolean isForPrimaryDex) {
Log.d(TAG, "Downgrading " + pkg);
- boolean downgradedPrimary = false;
+ boolean dex_opt_performed = false;
int reason = PackageManagerService.REASON_INACTIVE_PACKAGE_DOWNGRADE;
int dexoptFlags = DexoptOptions.DEXOPT_BOOT_COMPLETE
| DexoptOptions.DEXOPT_IDLE_BACKGROUND_JOB
| DexoptOptions.DEXOPT_DOWNGRADE;
-
long package_size_before = getPackageSize(pm, pkg);
- // An aggressive downgrade deletes the oat files.
- boolean aggressive = false;
- // This applies for system apps or if packages location is not a directory, i.e.
- // monolithic install.
- if (!pm.canHaveOatDir(pkg)) {
- // For apps that don't have the oat directory, instead of downgrading,
- // remove their compiler artifacts from dalvik cache.
- pm.deleteOatArtifactsOfPackage(pkg);
- aggressive = true;
- downgradedPrimary = true;
- } else {
- downgradedPrimary = performDexOptPrimary(pm, pkg, reason, dexoptFlags);
- if (supportSecondaryDex()) {
- performDexOptSecondary(pm, pkg, reason, dexoptFlags);
+ if (isForPrimaryDex) {
+ // This applies for system apps or if packages location is not a directory, i.e.
+ // monolithic install.
+ if (!pm.canHaveOatDir(pkg)) {
+ // For apps that don't have the oat directory, instead of downgrading,
+ // remove their compiler artifacts from dalvik cache.
+ pm.deleteOatArtifactsOfPackage(pkg);
+ } else {
+ dex_opt_performed = performDexOptPrimary(pm, pkg, reason, dexoptFlags);
}
+ } else {
+ dex_opt_performed = performDexOptSecondary(pm, pkg, reason, dexoptFlags);
}
- // This metric aims to log the storage savings when downgrading.
- // The way disk size is measured using getPackageSize only looks at the primary apks.
- // Any logs that are due to secondary dex files will show 0% size reduction and pollute
- // the metrics.
- if (downgradedPrimary) {
+ if (dex_opt_performed) {
StatsLog.write(StatsLog.APP_DOWNGRADED, pkg, package_size_before,
- getPackageSize(pm, pkg), aggressive);
+ getPackageSize(pm, pkg), /*aggressive=*/ false);
}
- return downgradedPrimary;
+ return dex_opt_performed;
}
private boolean supportSecondaryDex() {
@@ -480,7 +471,7 @@
* concurrent jobs because PackageDexOptimizer.performDexOpt is synchronized.
* @param pm An instance of PackageManagerService
* @param pkg The package to be downgraded.
- * @param isForPrimaryDex Apps can have several dex file, primary and secondary.
+ * @param isForPrimaryDex. Apps can have several dex file, primary and secondary.
* @return true if the package was downgraded.
*/
private boolean optimizePackage(PackageManagerService pm, String pkg,
@@ -597,6 +588,12 @@
// the checks above. This check is not "live" - the value is determined by a background
// restart with a period of ~1 minute.
PackageManagerService pm = (PackageManagerService)ServiceManager.getService("package");
+ if (pm.isStorageLow()) {
+ if (DEBUG_DEXOPT) {
+ Log.i(TAG, "Low storage, skipping this run");
+ }
+ return false;
+ }
final ArraySet<String> pkgs = pm.getOptimizablePackages();
if (pkgs.isEmpty()) {
@@ -646,77 +643,17 @@
}
private static long getDowngradeUnusedAppsThresholdInMillis() {
- long defaultValue = Long.MAX_VALUE;
- if (isDowngradeFeatureEnabled()) {
- return getInactiveAppsThresholdMillis();
- }
final String sysPropKey = "pm.dexopt.downgrade_after_inactive_days";
String sysPropValue = SystemProperties.get(sysPropKey);
if (sysPropValue == null || sysPropValue.isEmpty()) {
Log.w(TAG, "SysProp " + sysPropKey + " not set");
- return defaultValue;
+ return Long.MAX_VALUE;
}
- try {
- return TimeUnit.DAYS.toMillis(Long.parseLong(sysPropValue));
- } catch (NumberFormatException e) {
- Log.w(TAG, "Couldn't parse long for pm.dexopt.downgrade_after_inactive_days: "
- + sysPropValue + ". Returning default value instead.");
- return defaultValue;
- }
+ return TimeUnit.DAYS.toMillis(Long.parseLong(sysPropValue));
}
private static boolean isBackgroundDexoptDisabled() {
return SystemProperties.getBoolean("pm.dexopt.disable_bg_dexopt" /* key */,
false /* default */);
}
-
- private static boolean isDowngradeFeatureEnabled() {
- // DeviceConfig enables the control of on device features via remotely configurable flags,
- // compared to SystemProperties which is only a way of sharing info system-widely, but are
- // not configurable on the server-side.
- String downgradeUnusedAppsEnabledFlag =
- DeviceConfig.getProperty(
- DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE,
- DOWNGRADE_UNUSED_APPS_ENABLED);
- return !TextUtils.isEmpty(downgradeUnusedAppsEnabledFlag)
- && Boolean.parseBoolean(downgradeUnusedAppsEnabledFlag);
- }
-
- private static long getInactiveAppsThresholdMillis() {
- long defaultValue = TimeUnit.DAYS.toMillis(DEFAULT_INACTIVE_APP_THRESHOLD_DAYS);
- String inactiveAppThresholdDaysFlag =
- DeviceConfig.getProperty(DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE,
- INACTIVE_APP_THRESHOLD_DAYS);
- if (!TextUtils.isEmpty(inactiveAppThresholdDaysFlag)) {
- try {
- return TimeUnit.DAYS.toMillis(Long.parseLong(inactiveAppThresholdDaysFlag));
- } catch (NumberFormatException e) {
- Log.w(TAG, "Couldn't parse long for " + INACTIVE_APP_THRESHOLD_DAYS + " flag: "
- + inactiveAppThresholdDaysFlag + ". Returning default value instead.");
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- private static int getLowThresholdMultiplierForDowngrade() {
- int defaultValue = LOW_THRESHOLD_MULTIPLIER_FOR_DOWNGRADE;
- if (isDowngradeFeatureEnabled()) {
- String lowStorageThresholdMultiplierFlag =
- DeviceConfig.getProperty(DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE,
- LOW_STORAGE_MULTIPLIER_FOR_DOWNGRADE);
- if (!TextUtils.isEmpty(lowStorageThresholdMultiplierFlag)) {
- try {
- return Integer.parseInt(lowStorageThresholdMultiplierFlag);
- } catch (NumberFormatException e) {
- Log.w(TAG, "Couldn't parse long for "
- + LOW_STORAGE_MULTIPLIER_FOR_DOWNGRADE + " flag: "
- + lowStorageThresholdMultiplierFlag
- + ". Returning default value instead.");
- return defaultValue;
- }
- }
- }
- return defaultValue;
- }
}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 5e1d93f..3e528f4 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3334,27 +3334,17 @@
return;
}
Bundle args = null;
- if (deviceId > Integer.MIN_VALUE) {
+ if (deviceId > Integer.MIN_VALUE || hint != null) {
args = new Bundle();
- args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
- }
- if ((mContext.getResources().getConfiguration().uiMode
- & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
- // On TV, use legacy handling until assistants are implemented in the proper way.
- ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
- .launchLegacyAssist(hint, mCurrentUserId, args);
- } else {
+ if (deviceId > Integer.MIN_VALUE) {
+ args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
+ }
if (hint != null) {
- if (args == null) {
- args = new Bundle();
- }
args.putBoolean(hint, true);
}
- StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
- if (statusbar != null) {
- statusbar.startAssist(args);
- }
}
+ ((SearchManager) mContext.createContextAsUser(UserHandle.of(mCurrentUserId), 0)
+ .getSystemService(Context.SEARCH_SERVICE)).launchAssist(args);
}
/** Launches ACTION_VOICE_ASSIST. Does nothing on keyguard. */
diff --git a/services/core/java/com/android/server/search/SearchManagerService.java b/services/core/java/com/android/server/search/SearchManagerService.java
index bc1a12f..1494edf 100644
--- a/services/core/java/com/android/server/search/SearchManagerService.java
+++ b/services/core/java/com/android/server/search/SearchManagerService.java
@@ -18,7 +18,6 @@
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
-import android.app.IActivityManager;
import android.app.IActivityTaskManager;
import android.app.ISearchManager;
import android.app.SearchManager;
@@ -29,6 +28,7 @@
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
+import android.content.res.Configuration;
import android.database.ContentObserver;
import android.os.Binder;
import android.os.Bundle;
@@ -265,11 +265,17 @@
}
@Override
- public void launchAssist(Bundle args) {
- StatusBarManagerInternal statusBarManager =
- LocalServices.getService(StatusBarManagerInternal.class);
- if (statusBarManager != null) {
- statusBarManager.startAssist(args);
+ public void launchAssist(int userHandle, Bundle args) {
+ if ((mContext.getResources().getConfiguration().uiMode
+ & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
+ // On TV, use legacy handling until assistants are implemented in the proper way.
+ launchLegacyAssist(null, userHandle, args);
+ } else {
+ StatusBarManagerInternal statusBarManager =
+ LocalServices.getService(StatusBarManagerInternal.class);
+ if (statusBarManager != null) {
+ statusBarManager.startAssist(args);
+ }
}
}
@@ -298,8 +304,7 @@
return null;
}
- @Override
- public boolean launchLegacyAssist(String hint, int userHandle, Bundle args) {
+ private boolean launchLegacyAssist(String hint, int userHandle, Bundle args) {
ComponentName comp = getLegacyAssistComponent(userHandle);
if (comp == null) {
return false;
diff --git a/services/core/java/com/android/server/storage/StorageSessionController.java b/services/core/java/com/android/server/storage/StorageSessionController.java
index 72a1b9d..d76836f 100644
--- a/services/core/java/com/android/server/storage/StorageSessionController.java
+++ b/services/core/java/com/android/server/storage/StorageSessionController.java
@@ -69,15 +69,21 @@
}
/**
- * Creates a storage session associated with {@code deviceFd} for {@code vol}. Sessions can be
- * started with {@link #onVolumeReady} and removed with {@link #onVolumeUnmount} or
- * {@link #onVolumeRemove}.
+ * Creates and starts a storage session associated with {@code deviceFd} for {@code vol}.
+ * Sessions can be started with {@link #onVolumeReady} and removed with {@link #onVolumeUnmount}
+ * or {@link #onVolumeRemove}.
+ *
+ * Throws an {@link IllegalStateException} if a session for {@code vol} has already been created
*
* Does nothing if {@link #shouldHandle} is {@code false}
*
+ * Blocks until the session is started or fails
+ *
+ * @throws ExternalStorageServiceException if the session fails to start
* @throws IllegalStateException if a session has already been created for {@code vol}
*/
- public void onVolumeMount(FileDescriptor deviceFd, VolumeInfo vol) {
+ public void onVolumeMount(FileDescriptor deviceFd, VolumeInfo vol)
+ throws ExternalStorageServiceException {
if (!shouldHandle(vol)) {
return;
}
@@ -87,71 +93,22 @@
String sessionId = vol.getId();
int userId = vol.getMountUserId();
- if (deviceFd == null) {
- Slog.w(TAG, "Null fd. Session not started for vol: " + vol);
- return;
- }
-
- // Get realpath for the fd, paths that are not /dev/null need additional
- // setup by the ExternalStorageService before they can be ready
- String realPath;
- try {
- realPath = ParcelFileDescriptor.getFile(deviceFd).getPath();
- } catch (IOException e) {
- Slog.wtf(TAG, "Could not get real path from fd: " + deviceFd, e);
- return;
- }
-
- if ("/dev/null".equals(realPath)) {
- Slog.i(TAG, "Volume ready for use with id: " + sessionId);
- return;
- }
-
+ StorageUserConnection connection = null;
synchronized (mLock) {
- StorageUserConnection connection = mConnections.get(userId);
+ connection = mConnections.get(userId);
if (connection == null) {
+ Slog.i(TAG, "Creating connection for user: " + userId);
connection = new StorageUserConnection(mContext, userId, this);
mConnections.put(userId, connection);
}
Slog.i(TAG, "Creating session with id: " + sessionId);
- connection.createSession(sessionId, new ParcelFileDescriptor(deviceFd));
- }
- }
-
- /**
- * Starts a storage session associated with {@code vol} after {@link #onVolumeMount}.
- *
- * Subsequent calls will attempt to start the storage session, but does nothing if already
- * started. If the user associated with {@code vol} is not yet ready, all pending sesssions
- * can be restarted with {@link onUnlockUser}.
- *
- * Does nothing if {@link #shouldHandle} is {@code false}
- *
- * Blocks until the session is started or fails
- *
- * @throws ExternalStorageServiceException if the session fails to start
- */
- public void onVolumeReady(VolumeInfo vol) throws ExternalStorageServiceException {
- if (!shouldHandle(vol)) {
- return;
+ connection.createSession(sessionId, new ParcelFileDescriptor(deviceFd),
+ vol.getPath().getPath(), vol.getInternalPath().getPath());
}
- Slog.i(TAG, "On volume ready " + vol);
- String sessionId = vol.getId();
-
- StorageUserConnection connection = null;
- synchronized (mLock) {
- connection = mConnections.get(vol.getMountUserId());
- if (connection == null) {
- Slog.i(TAG, "Volume ready but no associated connection");
- return;
- }
- }
-
- connection.initSession(sessionId, vol.getPath().getPath(),
- vol.getInternalPath().getPath());
-
- if (isReady()) {
+ // At boot, a volume can be mounted before user is unlocked, in that case, we create it
+ // above and save it so that we can restart all sessions when the user is unlocked
+ if (mExternalStorageServiceComponent != null) {
connection.startSession(sessionId);
} else {
Slog.i(TAG, "Controller not initialised, session not started " + sessionId);
@@ -205,14 +162,10 @@
if (connection != null) {
String sessionId = vol.getId();
- if (isReady()) {
- try {
- connection.removeSessionAndWait(sessionId);
- } catch (ExternalStorageServiceException e) {
- Slog.e(TAG, "Failed to end session for vol with id: " + sessionId, e);
- }
- } else {
- Slog.i(TAG, "Controller not initialised, session not ended " + sessionId);
+ try {
+ connection.removeSessionAndWait(sessionId);
+ } catch (ExternalStorageServiceException e) {
+ Slog.e(TAG, "Failed to end session for vol with id: " + sessionId, e);
}
}
}
@@ -232,7 +185,7 @@
Slog.i(TAG, "On user unlock " + userId);
if (userId == 0) {
- init();
+ initExternalStorageServiceComponent();
}
StorageUserConnection connection = null;
@@ -259,13 +212,6 @@
return;
}
- if (!isReady()) {
- synchronized (mLock) {
- mConnections.clear();
- }
- return;
- }
-
SparseArray<StorageUserConnection> connections = new SparseArray();
synchronized (mLock) {
mIsResetting = true;
@@ -311,7 +257,7 @@
}
}
- private void init() throws ExternalStorageServiceException {
+ private void initExternalStorageServiceComponent() throws ExternalStorageServiceException {
Slog.i(TAG, "Initialialising...");
ProviderInfo provider = mContext.getPackageManager().resolveContentProvider(
MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE
@@ -415,8 +361,4 @@
private boolean shouldHandle(@Nullable VolumeInfo vol) {
return mIsFuseEnabled && !mIsResetting && (vol == null || isEmulatedOrPublic(vol));
}
-
- private boolean isReady() {
- return mExternalStorageServiceComponent != null;
- }
}
diff --git a/services/core/java/com/android/server/storage/StorageUserConnection.java b/services/core/java/com/android/server/storage/StorageUserConnection.java
index 24b56a4..7c47730 100644
--- a/services/core/java/com/android/server/storage/StorageUserConnection.java
+++ b/services/core/java/com/android/server/storage/StorageUserConnection.java
@@ -75,46 +75,20 @@
/**
* Creates and stores a storage {@link Session}.
*
- * Created sessions must be initialised with {@link #initSession} before starting with
- * {@link #startSession}.
- *
* They must also be cleaned up with {@link #removeSession}.
*
* @throws IllegalArgumentException if a {@code Session} with {@code sessionId} already exists
*/
- public void createSession(String sessionId, ParcelFileDescriptor pfd) {
+ public void createSession(String sessionId, ParcelFileDescriptor pfd, String upperPath,
+ String lowerPath) {
Preconditions.checkNotNull(sessionId);
Preconditions.checkNotNull(pfd);
+ Preconditions.checkNotNull(upperPath);
+ Preconditions.checkNotNull(lowerPath);
synchronized (mLock) {
Preconditions.checkArgument(!mSessions.containsKey(sessionId));
- mSessions.put(sessionId, new Session(sessionId, pfd));
- }
- }
-
- /**
- * Initialise a storage {@link Session}.
- *
- * Initialised sessions can be started with {@link #startSession}.
- *
- * They must also be cleaned up with {@link #removeSession}.
- *
- * @throws IllegalArgumentException if {@code sessionId} does not exist or is initialised
- */
- public void initSession(String sessionId, String upperPath, String lowerPath) {
- synchronized (mLock) {
- Session session = mSessions.get(sessionId);
- if (session == null) {
- throw new IllegalStateException("Failed to initialise non existent session. Id: "
- + sessionId + ". Upper path: " + upperPath + ". Lower path: " + lowerPath);
- } else if (session.isInitialisedLocked()) {
- throw new IllegalStateException("Already initialised session. Id: "
- + sessionId + ". Upper path: " + upperPath + ". Lower path: " + lowerPath);
- } else {
- session.upperPath = upperPath;
- session.lowerPath = lowerPath;
- Slog.i(TAG, "Initialised session: " + session);
- }
+ mSessions.put(sessionId, new Session(sessionId, pfd, upperPath, lowerPath));
}
}
@@ -440,14 +414,14 @@
private static final class Session implements AutoCloseable {
public final String sessionId;
public final ParcelFileDescriptor pfd;
- @GuardedBy("mLock")
- public String lowerPath;
- @GuardedBy("mLock")
- public String upperPath;
+ public final String lowerPath;
+ public final String upperPath;
- Session(String sessionId, ParcelFileDescriptor pfd) {
+ Session(String sessionId, ParcelFileDescriptor pfd, String upperPath, String lowerPath) {
this.sessionId = sessionId;
this.pfd = pfd;
+ this.upperPath = upperPath;
+ this.lowerPath = lowerPath;
}
@Override
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index f627dda..e16f3fc 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -6239,9 +6239,6 @@
// relatively fixed.
overrideConfig.colorMode = fullConfig.colorMode;
overrideConfig.densityDpi = fullConfig.densityDpi;
- overrideConfig.screenLayout = fullConfig.screenLayout
- & (Configuration.SCREENLAYOUT_LONG_MASK
- | Configuration.SCREENLAYOUT_SIZE_MASK);
// The smallest screen width is the short side of screen bounds. Because the bounds
// and density won't be changed, smallestScreenWidthDp is also fixed.
overrideConfig.smallestScreenWidthDp = fullConfig.smallestScreenWidthDp;
@@ -6376,6 +6373,10 @@
// Use resolvedBounds to compute other override configurations such as appBounds
task.computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
mCompatDisplayInsets);
+ // Use current screen layout as source because the size of app is independent to parent.
+ resolvedConfig.screenLayout = Task.computeScreenLayoutOverride(
+ getConfiguration().screenLayout, resolvedConfig.screenWidthDp,
+ resolvedConfig.screenHeightDp);
// Use parent orientation if it cannot be decided by bounds, so the activity can fit inside
// the parent bounds appropriately.
diff --git a/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java b/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java
index fe91ba5..413dfd5 100644
--- a/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java
+++ b/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java
@@ -77,10 +77,10 @@
}
private void processTask(Task task) {
+ reset(task);
mRoot = task.getRootActivity(true);
if (mRoot == null) return;
- reset(task);
final boolean isTargetTask = task == mTargetTask;
if (isTargetTask) mTargetTaskFound = true;
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 3b16b59..28c5575 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -2064,17 +2064,22 @@
// could never go away in Honeycomb.
final int compatScreenWidthDp = (int) (mTmpNonDecorBounds.width() / density);
final int compatScreenHeightDp = (int) (mTmpNonDecorBounds.height() / density);
- // We're only overriding LONG, SIZE and COMPAT parts of screenLayout, so we start
- // override calculation with partial default.
// Reducing the screen layout starting from its parent config.
- final int sl = parentConfig.screenLayout
- & (Configuration.SCREENLAYOUT_LONG_MASK | Configuration.SCREENLAYOUT_SIZE_MASK);
- final int longSize = Math.max(compatScreenHeightDp, compatScreenWidthDp);
- final int shortSize = Math.min(compatScreenHeightDp, compatScreenWidthDp);
- inOutConfig.screenLayout = Configuration.reduceScreenLayout(sl, longSize, shortSize);
+ inOutConfig.screenLayout = computeScreenLayoutOverride(parentConfig.screenLayout,
+ compatScreenWidthDp, compatScreenHeightDp);
}
}
+ /** Computes LONG, SIZE and COMPAT parts of {@link Configuration#screenLayout}. */
+ static int computeScreenLayoutOverride(int sourceScreenLayout, int screenWidthDp,
+ int screenHeightDp) {
+ sourceScreenLayout = sourceScreenLayout
+ & (Configuration.SCREENLAYOUT_LONG_MASK | Configuration.SCREENLAYOUT_SIZE_MASK);
+ final int longSize = Math.max(screenWidthDp, screenHeightDp);
+ final int shortSize = Math.min(screenWidthDp, screenHeightDp);
+ return Configuration.reduceScreenLayout(sourceScreenLayout, longSize, shortSize);
+ }
+
@Override
void resolveOverrideConfiguration(Configuration newParentConfig) {
mTmpBounds.set(getResolvedOverrideConfiguration().windowConfiguration.getBounds());
diff --git a/services/core/jni/com_android_server_VibratorService.cpp b/services/core/jni/com_android_server_VibratorService.cpp
index 746610d..612a1e7 100644
--- a/services/core/jni/com_android_server_VibratorService.cpp
+++ b/services/core/jni/com_android_server_VibratorService.cpp
@@ -291,7 +291,7 @@
static void vibratorSetAmplitude(JNIEnv*, jclass, jint amplitude) {
if (auto hal = getHal<aidl::IVibrator>()) {
- auto status = hal->call(&aidl::IVibrator::IVibrator::setAmplitude, amplitude);
+ auto status = hal->call(&aidl::IVibrator::IVibrator::setAmplitude, static_cast<float>(amplitude) / UINT8_MAX);
if (!status.isOk()) {
ALOGE("Failed to set vibrator amplitude: %s", status.toString8().string());
}
diff --git a/services/net/Android.bp b/services/net/Android.bp
index 42c69e0..7ef9f44 100644
--- a/services/net/Android.bp
+++ b/services/net/Android.bp
@@ -8,41 +8,27 @@
java_library_static {
name: "services.net",
srcs: [
+ ":net-module-utils-srcs",
":tethering-servicesnet-srcs",
":services.net-sources",
],
static_libs: [
"dnsresolver_aidl_interface-V2-java",
"netd_aidl_interface-unstable-java",
+ "netlink-client",
"networkstack-client",
"tethering-client",
],
}
filegroup {
- name: "services-networkstack-shared-srcs",
- srcs: [
- "java/android/net/ip/InterfaceController.java", // TODO: move to NetworkStack with tethering
- "java/android/net/util/InterfaceParams.java", // TODO: move to NetworkStack with IpServer
- "java/android/net/shared/*.java",
- "java/android/net/netlink/*.java",
- ],
- path: "java",
- visibility: ["//packages/modules/NetworkStack"],
-}
-
-filegroup {
name: "services-tethering-shared-srcs",
srcs: [
":framework-annotations",
"java/android/net/ConnectivityModuleConnector.java",
"java/android/net/NetworkStackClient.java",
- "java/android/net/ip/InterfaceController.java",
- "java/android/net/netlink/*.java",
- "java/android/net/util/InterfaceParams.java",
"java/android/net/util/NetdService.java",
"java/android/net/util/NetworkConstants.java",
- "java/android/net/util/SharedLog.java"
],
visibility: ["//frameworks/base/packages/Tethering"],
}
diff --git a/services/net/java/android/net/ip/InterfaceController.java b/services/net/java/android/net/ip/InterfaceController.java
deleted file mode 100644
index 970bc9c..0000000
--- a/services/net/java/android/net/ip/InterfaceController.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * 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.ip;
-
-import android.net.INetd;
-import android.net.InterfaceConfigurationParcel;
-import android.net.LinkAddress;
-import android.net.util.SharedLog;
-import android.os.RemoteException;
-import android.os.ServiceSpecificException;
-import android.system.OsConstants;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-
-
-/**
- * Encapsulates the multiple IP configuration operations performed on an interface.
- *
- * TODO: refactor/eliminate the redundant ways to set and clear addresses.
- *
- * @hide
- */
-public class InterfaceController {
- private final static boolean DBG = false;
-
- private final String mIfName;
- private final INetd mNetd;
- private final SharedLog mLog;
-
- public InterfaceController(String ifname, INetd netd, SharedLog log) {
- mIfName = ifname;
- mNetd = netd;
- mLog = log;
- }
-
- private boolean setInterfaceAddress(LinkAddress addr) {
- final InterfaceConfigurationParcel ifConfig = new InterfaceConfigurationParcel();
- ifConfig.ifName = mIfName;
- ifConfig.ipv4Addr = addr.getAddress().getHostAddress();
- ifConfig.prefixLength = addr.getPrefixLength();
- ifConfig.hwAddr = "";
- ifConfig.flags = new String[0];
- try {
- mNetd.interfaceSetCfg(ifConfig);
- } catch (RemoteException | ServiceSpecificException e) {
- logError("Setting IPv4 address to %s/%d failed: %s",
- ifConfig.ipv4Addr, ifConfig.prefixLength, e);
- return false;
- }
- return true;
- }
-
- /**
- * Set the IPv4 address of the interface.
- */
- public boolean setIPv4Address(LinkAddress address) {
- if (!(address.getAddress() instanceof Inet4Address)) {
- return false;
- }
- return setInterfaceAddress(address);
- }
-
- /**
- * Clear the IPv4Address of the interface.
- */
- public boolean clearIPv4Address() {
- return setInterfaceAddress(new LinkAddress("0.0.0.0/0"));
- }
-
- private boolean setEnableIPv6(boolean enabled) {
- try {
- mNetd.interfaceSetEnableIPv6(mIfName, enabled);
- } catch (RemoteException | ServiceSpecificException e) {
- logError("%s IPv6 failed: %s", (enabled ? "enabling" : "disabling"), e);
- return false;
- }
- return true;
- }
-
- /**
- * Enable IPv6 on the interface.
- */
- public boolean enableIPv6() {
- return setEnableIPv6(true);
- }
-
- /**
- * Disable IPv6 on the interface.
- */
- public boolean disableIPv6() {
- return setEnableIPv6(false);
- }
-
- /**
- * Enable or disable IPv6 privacy extensions on the interface.
- * @param enabled Whether the extensions should be enabled.
- */
- public boolean setIPv6PrivacyExtensions(boolean enabled) {
- try {
- mNetd.interfaceSetIPv6PrivacyExtensions(mIfName, enabled);
- } catch (RemoteException | ServiceSpecificException e) {
- logError("error %s IPv6 privacy extensions: %s",
- (enabled ? "enabling" : "disabling"), e);
- return false;
- }
- return true;
- }
-
- /**
- * Set IPv6 address generation mode on the interface.
- *
- * <p>IPv6 should be disabled before changing the mode.
- */
- public boolean setIPv6AddrGenModeIfSupported(int mode) {
- try {
- mNetd.setIPv6AddrGenMode(mIfName, mode);
- } catch (RemoteException e) {
- logError("Unable to set IPv6 addrgen mode: %s", e);
- return false;
- } catch (ServiceSpecificException e) {
- if (e.errorCode != OsConstants.EOPNOTSUPP) {
- logError("Unable to set IPv6 addrgen mode: %s", e);
- return false;
- }
- }
- return true;
- }
-
- /**
- * Add an address to the interface.
- */
- public boolean addAddress(LinkAddress addr) {
- return addAddress(addr.getAddress(), addr.getPrefixLength());
- }
-
- /**
- * Add an address to the interface.
- */
- public boolean addAddress(InetAddress ip, int prefixLen) {
- try {
- mNetd.interfaceAddAddress(mIfName, ip.getHostAddress(), prefixLen);
- } catch (ServiceSpecificException | RemoteException e) {
- logError("failed to add %s/%d: %s", ip, prefixLen, e);
- return false;
- }
- return true;
- }
-
- /**
- * Remove an address from the interface.
- */
- public boolean removeAddress(InetAddress ip, int prefixLen) {
- try {
- mNetd.interfaceDelAddress(mIfName, ip.getHostAddress(), prefixLen);
- } catch (ServiceSpecificException | RemoteException e) {
- logError("failed to remove %s/%d: %s", ip, prefixLen, e);
- return false;
- }
- return true;
- }
-
- /**
- * Remove all addresses from the interface.
- */
- public boolean clearAllAddresses() {
- try {
- mNetd.interfaceClearAddrs(mIfName);
- } catch (Exception e) {
- logError("Failed to clear addresses: %s", e);
- return false;
- }
- return true;
- }
-
- private void logError(String fmt, Object... args) {
- mLog.e(String.format(fmt, args));
- }
-}
diff --git a/services/net/java/android/net/netlink/ConntrackMessage.java b/services/net/java/android/net/netlink/ConntrackMessage.java
deleted file mode 100644
index 6978739..0000000
--- a/services/net/java/android/net/netlink/ConntrackMessage.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.netlink;
-
-import static android.net.netlink.StructNlMsgHdr.NLM_F_ACK;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REPLACE;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
-
-import static java.nio.ByteOrder.BIG_ENDIAN;
-
-import android.system.OsConstants;
-
-import java.net.Inet4Address;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-
-/**
- * A NetlinkMessage subclass for netlink conntrack messages.
- *
- * see also: <linux_src>/include/uapi/linux/netfilter/nfnetlink_conntrack.h
- *
- * @hide
- */
-public class ConntrackMessage extends NetlinkMessage {
- public static final int STRUCT_SIZE = StructNlMsgHdr.STRUCT_SIZE + StructNfGenMsg.STRUCT_SIZE;
-
- public static final short NFNL_SUBSYS_CTNETLINK = 1;
- public static final short IPCTNL_MSG_CT_NEW = 0;
-
- // enum ctattr_type
- public static final short CTA_TUPLE_ORIG = 1;
- public static final short CTA_TUPLE_REPLY = 2;
- public static final short CTA_TIMEOUT = 7;
-
- // enum ctattr_tuple
- public static final short CTA_TUPLE_IP = 1;
- public static final short CTA_TUPLE_PROTO = 2;
-
- // enum ctattr_ip
- public static final short CTA_IP_V4_SRC = 1;
- public static final short CTA_IP_V4_DST = 2;
-
- // enum ctattr_l4proto
- public static final short CTA_PROTO_NUM = 1;
- public static final short CTA_PROTO_SRC_PORT = 2;
- public static final short CTA_PROTO_DST_PORT = 3;
-
- public static byte[] newIPv4TimeoutUpdateRequest(
- int proto, Inet4Address src, int sport, Inet4Address dst, int dport, int timeoutSec) {
- // *** STYLE WARNING ***
- //
- // Code below this point uses extra block indentation to highlight the
- // packing of nested tuple netlink attribute types.
- final StructNlAttr ctaTupleOrig = new StructNlAttr(CTA_TUPLE_ORIG,
- new StructNlAttr(CTA_TUPLE_IP,
- new StructNlAttr(CTA_IP_V4_SRC, src),
- new StructNlAttr(CTA_IP_V4_DST, dst)),
- new StructNlAttr(CTA_TUPLE_PROTO,
- new StructNlAttr(CTA_PROTO_NUM, (byte) proto),
- new StructNlAttr(CTA_PROTO_SRC_PORT, (short) sport, BIG_ENDIAN),
- new StructNlAttr(CTA_PROTO_DST_PORT, (short) dport, BIG_ENDIAN)));
-
- final StructNlAttr ctaTimeout = new StructNlAttr(CTA_TIMEOUT, timeoutSec, BIG_ENDIAN);
-
- final int payloadLength = ctaTupleOrig.getAlignedLength() + ctaTimeout.getAlignedLength();
- final byte[] bytes = new byte[STRUCT_SIZE + payloadLength];
- final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
- byteBuffer.order(ByteOrder.nativeOrder());
-
- final ConntrackMessage ctmsg = new ConntrackMessage();
- ctmsg.mHeader.nlmsg_len = bytes.length;
- ctmsg.mHeader.nlmsg_type = (NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_NEW;
- ctmsg.mHeader.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE;
- ctmsg.mHeader.nlmsg_seq = 1;
- ctmsg.pack(byteBuffer);
-
- ctaTupleOrig.pack(byteBuffer);
- ctaTimeout.pack(byteBuffer);
-
- return bytes;
- }
-
- protected StructNfGenMsg mNfGenMsg;
-
- private ConntrackMessage() {
- super(new StructNlMsgHdr());
- mNfGenMsg = new StructNfGenMsg((byte) OsConstants.AF_INET);
- }
-
- public void pack(ByteBuffer byteBuffer) {
- mHeader.pack(byteBuffer);
- mNfGenMsg.pack(byteBuffer);
- }
-}
diff --git a/services/net/java/android/net/netlink/InetDiagMessage.java b/services/net/java/android/net/netlink/InetDiagMessage.java
deleted file mode 100644
index ca07630..0000000
--- a/services/net/java/android/net/netlink/InetDiagMessage.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2018 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.netlink;
-
-import static android.net.netlink.NetlinkConstants.SOCK_DIAG_BY_FAMILY;
-import static android.net.netlink.NetlinkSocket.DEFAULT_RECV_BUFSIZE;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
-import static android.os.Process.INVALID_UID;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-import static android.system.OsConstants.IPPROTO_UDP;
-import static android.system.OsConstants.NETLINK_INET_DIAG;
-
-import android.annotation.Nullable;
-import android.net.util.SocketUtils;
-import android.system.ErrnoException;
-import android.util.Log;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetSocketAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * A NetlinkMessage subclass for netlink inet_diag messages.
- *
- * see also: <linux_src>/include/uapi/linux/inet_diag.h
- *
- * @hide
- */
-public class InetDiagMessage extends NetlinkMessage {
- public static final String TAG = "InetDiagMessage";
- private static final int TIMEOUT_MS = 500;
-
- public static byte[] InetDiagReqV2(int protocol, InetSocketAddress local,
- InetSocketAddress remote, int family, short flags) {
- return InetDiagReqV2(protocol, local, remote, family, flags, 0 /* pad */,
- 0 /* idiagExt */, StructInetDiagReqV2.INET_DIAG_REQ_V2_ALL_STATES);
- }
-
- /**
- * Construct an inet_diag_req_v2 message. This method will throw {@code NullPointerException}
- * if local and remote are not both null or both non-null.
- *
- * @param protocol the request protocol type. This should be set to one of IPPROTO_TCP,
- * IPPROTO_UDP, or IPPROTO_UDPLITE.
- * @param local local socket address of the target socket. This will be packed into a
- * {@Code StructInetDiagSockId}. Request to diagnose for all sockets if both of
- * local or remote address is null.
- * @param remote remote socket address of the target socket. This will be packed into a
- * {@Code StructInetDiagSockId}. Request to diagnose for all sockets if both of
- * local or remote address is null.
- * @param family the ip family of the request message. This should be set to either AF_INET or
- * AF_INET6 for IPv4 or IPv6 sockets respectively.
- * @param flags message flags. See <linux_src>/include/uapi/linux/netlink.h.
- * @param pad for raw socket protocol specification.
- * @param idiagExt a set of flags defining what kind of extended information to report.
- * @param state a bit mask that defines a filter of socket states.
- *
- * @return bytes array representation of the message
- **/
- public static byte[] InetDiagReqV2(int protocol, @Nullable InetSocketAddress local,
- @Nullable InetSocketAddress remote, int family, short flags, int pad, int idiagExt,
- int state) throws NullPointerException {
- final byte[] bytes = new byte[StructNlMsgHdr.STRUCT_SIZE + StructInetDiagReqV2.STRUCT_SIZE];
- final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
- byteBuffer.order(ByteOrder.nativeOrder());
-
- final StructNlMsgHdr nlMsgHdr = new StructNlMsgHdr();
- nlMsgHdr.nlmsg_len = bytes.length;
- nlMsgHdr.nlmsg_type = SOCK_DIAG_BY_FAMILY;
- nlMsgHdr.nlmsg_flags = flags;
- nlMsgHdr.pack(byteBuffer);
- final StructInetDiagReqV2 inetDiagReqV2 =
- new StructInetDiagReqV2(protocol, local, remote, family, pad, idiagExt, state);
-
- inetDiagReqV2.pack(byteBuffer);
- return bytes;
- }
-
- public StructInetDiagMsg mStructInetDiagMsg;
-
- private InetDiagMessage(StructNlMsgHdr header) {
- super(header);
- mStructInetDiagMsg = new StructInetDiagMsg();
- }
-
- public static InetDiagMessage parse(StructNlMsgHdr header, ByteBuffer byteBuffer) {
- final InetDiagMessage msg = new InetDiagMessage(header);
- msg.mStructInetDiagMsg = StructInetDiagMsg.parse(byteBuffer);
- return msg;
- }
-
- private static int lookupUidByFamily(int protocol, InetSocketAddress local,
- InetSocketAddress remote, int family, short flags,
- FileDescriptor fd)
- throws ErrnoException, InterruptedIOException {
- byte[] msg = InetDiagReqV2(protocol, local, remote, family, flags);
- NetlinkSocket.sendMessage(fd, msg, 0, msg.length, TIMEOUT_MS);
- ByteBuffer response = NetlinkSocket.recvMessage(fd, DEFAULT_RECV_BUFSIZE, TIMEOUT_MS);
-
- final NetlinkMessage nlMsg = NetlinkMessage.parse(response);
- final StructNlMsgHdr hdr = nlMsg.getHeader();
- if (hdr.nlmsg_type == NetlinkConstants.NLMSG_DONE) {
- return INVALID_UID;
- }
- if (nlMsg instanceof InetDiagMessage) {
- return ((InetDiagMessage) nlMsg).mStructInetDiagMsg.idiag_uid;
- }
- return INVALID_UID;
- }
-
- private static final int FAMILY[] = {AF_INET6, AF_INET};
-
- private static int lookupUid(int protocol, InetSocketAddress local,
- InetSocketAddress remote, FileDescriptor fd)
- throws ErrnoException, InterruptedIOException {
- int uid;
-
- for (int family : FAMILY) {
- /**
- * For exact match lookup, swap local and remote for UDP lookups due to kernel
- * bug which will not be fixed. See aosp/755889 and
- * https://www.mail-archive.com/netdev@vger.kernel.org/msg248638.html
- */
- if (protocol == IPPROTO_UDP) {
- uid = lookupUidByFamily(protocol, remote, local, family, NLM_F_REQUEST, fd);
- } else {
- uid = lookupUidByFamily(protocol, local, remote, family, NLM_F_REQUEST, fd);
- }
- if (uid != INVALID_UID) {
- return uid;
- }
- }
-
- /**
- * For UDP it's possible for a socket to send packets to arbitrary destinations, even if the
- * socket is not connected (and even if the socket is connected to a different destination).
- * If we want this API to work for such packets, then on miss we need to do a second lookup
- * with only the local address and port filled in.
- * Always use flags == NLM_F_REQUEST | NLM_F_DUMP for wildcard.
- */
- if (protocol == IPPROTO_UDP) {
- try {
- InetSocketAddress wildcard = new InetSocketAddress(
- Inet6Address.getByName("::"), 0);
- uid = lookupUidByFamily(protocol, local, wildcard, AF_INET6,
- (short) (NLM_F_REQUEST | NLM_F_DUMP), fd);
- if (uid != INVALID_UID) {
- return uid;
- }
- wildcard = new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), 0);
- uid = lookupUidByFamily(protocol, local, wildcard, AF_INET,
- (short) (NLM_F_REQUEST | NLM_F_DUMP), fd);
- if (uid != INVALID_UID) {
- return uid;
- }
- } catch (UnknownHostException e) {
- Log.e(TAG, e.toString());
- }
- }
- return INVALID_UID;
- }
-
- /**
- * Use an inet_diag socket to look up the UID associated with the input local and remote
- * address/port and protocol of a connection.
- */
- public static int getConnectionOwnerUid(int protocol, InetSocketAddress local,
- InetSocketAddress remote) {
- int uid = INVALID_UID;
- FileDescriptor fd = null;
- try {
- fd = NetlinkSocket.forProto(NETLINK_INET_DIAG);
- NetlinkSocket.connectToKernel(fd);
- uid = lookupUid(protocol, local, remote, fd);
- } catch (ErrnoException | SocketException | IllegalArgumentException
- | InterruptedIOException e) {
- Log.e(TAG, e.toString());
- } finally {
- if (fd != null) {
- try {
- SocketUtils.closeSocket(fd);
- } catch (IOException e) {
- Log.e(TAG, e.toString());
- }
- }
- }
- return uid;
- }
-
- @Override
- public String toString() {
- return "InetDiagMessage{ "
- + "nlmsghdr{" + (mHeader == null ? "" : mHeader.toString()) + "}, "
- + "inet_diag_msg{"
- + (mStructInetDiagMsg == null ? "" : mStructInetDiagMsg.toString()) + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/NetlinkConstants.java b/services/net/java/android/net/netlink/NetlinkConstants.java
deleted file mode 100644
index fc1551c..0000000
--- a/services/net/java/android/net/netlink/NetlinkConstants.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.system.OsConstants;
-import com.android.internal.util.HexDump;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * Various constants and static helper methods for netlink communications.
- *
- * Values taken from:
- *
- * <linux_src>/include/uapi/linux/netlink.h
- * <linux_src>/include/uapi/linux/rtnetlink.h
- *
- * @hide
- */
-public class NetlinkConstants {
- private NetlinkConstants() {}
-
- public static final int NLA_ALIGNTO = 4;
-
- public static final int alignedLengthOf(short length) {
- final int intLength = (int) length & 0xffff;
- return alignedLengthOf(intLength);
- }
-
- public static final int alignedLengthOf(int length) {
- if (length <= 0) { return 0; }
- return (((length + NLA_ALIGNTO - 1) / NLA_ALIGNTO) * NLA_ALIGNTO);
- }
-
- public static String stringForAddressFamily(int family) {
- if (family == OsConstants.AF_INET) { return "AF_INET"; }
- if (family == OsConstants.AF_INET6) { return "AF_INET6"; }
- if (family == OsConstants.AF_NETLINK) { return "AF_NETLINK"; }
- return String.valueOf(family);
- }
-
- public static String stringForProtocol(int protocol) {
- if (protocol == OsConstants.IPPROTO_TCP) { return "IPPROTO_TCP"; }
- if (protocol == OsConstants.IPPROTO_UDP) { return "IPPROTO_UDP"; }
- return String.valueOf(protocol);
- }
-
- public static String hexify(byte[] bytes) {
- if (bytes == null) { return "(null)"; }
- return HexDump.toHexString(bytes);
- }
-
- public static String hexify(ByteBuffer buffer) {
- if (buffer == null) { return "(null)"; }
- return HexDump.toHexString(
- buffer.array(), buffer.position(), buffer.remaining());
- }
-
- // Known values for struct nlmsghdr nlm_type.
- public static final short NLMSG_NOOP = 1; // Nothing
- public static final short NLMSG_ERROR = 2; // Error
- public static final short NLMSG_DONE = 3; // End of a dump
- public static final short NLMSG_OVERRUN = 4; // Data lost
- public static final short NLMSG_MAX_RESERVED = 15; // Max reserved value
-
- public static final short RTM_NEWLINK = 16;
- public static final short RTM_DELLINK = 17;
- public static final short RTM_GETLINK = 18;
- public static final short RTM_SETLINK = 19;
- public static final short RTM_NEWADDR = 20;
- public static final short RTM_DELADDR = 21;
- public static final short RTM_GETADDR = 22;
- public static final short RTM_NEWROUTE = 24;
- public static final short RTM_DELROUTE = 25;
- public static final short RTM_GETROUTE = 26;
- public static final short RTM_NEWNEIGH = 28;
- public static final short RTM_DELNEIGH = 29;
- public static final short RTM_GETNEIGH = 30;
- public static final short RTM_NEWRULE = 32;
- public static final short RTM_DELRULE = 33;
- public static final short RTM_GETRULE = 34;
- public static final short RTM_NEWNDUSEROPT = 68;
-
- /* see <linux_src>/include/uapi/linux/sock_diag.h */
- public static final short SOCK_DIAG_BY_FAMILY = 20;
-
- public static String stringForNlMsgType(short nlm_type) {
- switch (nlm_type) {
- case NLMSG_NOOP: return "NLMSG_NOOP";
- case NLMSG_ERROR: return "NLMSG_ERROR";
- case NLMSG_DONE: return "NLMSG_DONE";
- case NLMSG_OVERRUN: return "NLMSG_OVERRUN";
- case RTM_NEWLINK: return "RTM_NEWLINK";
- case RTM_DELLINK: return "RTM_DELLINK";
- case RTM_GETLINK: return "RTM_GETLINK";
- case RTM_SETLINK: return "RTM_SETLINK";
- case RTM_NEWADDR: return "RTM_NEWADDR";
- case RTM_DELADDR: return "RTM_DELADDR";
- case RTM_GETADDR: return "RTM_GETADDR";
- case RTM_NEWROUTE: return "RTM_NEWROUTE";
- case RTM_DELROUTE: return "RTM_DELROUTE";
- case RTM_GETROUTE: return "RTM_GETROUTE";
- case RTM_NEWNEIGH: return "RTM_NEWNEIGH";
- case RTM_DELNEIGH: return "RTM_DELNEIGH";
- case RTM_GETNEIGH: return "RTM_GETNEIGH";
- case RTM_NEWRULE: return "RTM_NEWRULE";
- case RTM_DELRULE: return "RTM_DELRULE";
- case RTM_GETRULE: return "RTM_GETRULE";
- case RTM_NEWNDUSEROPT: return "RTM_NEWNDUSEROPT";
- default:
- return "unknown RTM type: " + String.valueOf(nlm_type);
- }
- }
-}
diff --git a/services/net/java/android/net/netlink/NetlinkErrorMessage.java b/services/net/java/android/net/netlink/NetlinkErrorMessage.java
deleted file mode 100644
index e275574..0000000
--- a/services/net/java/android/net/netlink/NetlinkErrorMessage.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.net.netlink.StructNlMsgHdr;
-import android.net.netlink.NetlinkMessage;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * A NetlinkMessage subclass for netlink error messages.
- *
- * @hide
- */
-public class NetlinkErrorMessage extends NetlinkMessage {
-
- public static NetlinkErrorMessage parse(StructNlMsgHdr header, ByteBuffer byteBuffer) {
- final NetlinkErrorMessage errorMsg = new NetlinkErrorMessage(header);
-
- errorMsg.mNlMsgErr = StructNlMsgErr.parse(byteBuffer);
- if (errorMsg.mNlMsgErr == null) {
- return null;
- }
-
- return errorMsg;
- }
-
- private StructNlMsgErr mNlMsgErr;
-
- NetlinkErrorMessage(StructNlMsgHdr header) {
- super(header);
- mNlMsgErr = null;
- }
-
- public StructNlMsgErr getNlMsgError() {
- return mNlMsgErr;
- }
-
- @Override
- public String toString() {
- return "NetlinkErrorMessage{ "
- + "nlmsghdr{" + (mHeader == null ? "" : mHeader.toString()) + "}, "
- + "nlmsgerr{" + (mNlMsgErr == null ? "" : mNlMsgErr.toString()) + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/NetlinkMessage.java b/services/net/java/android/net/netlink/NetlinkMessage.java
deleted file mode 100644
index a325db8..0000000
--- a/services/net/java/android/net/netlink/NetlinkMessage.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.net.netlink.NetlinkConstants;
-import android.net.netlink.NetlinkErrorMessage;
-import android.net.netlink.RtNetlinkNeighborMessage;
-import android.net.netlink.StructNlAttr;
-import android.net.netlink.StructNlMsgHdr;
-import android.util.Log;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * NetlinkMessage base class for other, more specific netlink message types.
- *
- * Classes that extend NetlinkMessage should:
- * - implement a public static parse(StructNlMsgHdr, ByteBuffer) method
- * - returning either null (parse errors) or a new object of the subclass
- * type (cast-able to NetlinkMessage)
- *
- * NetlinkMessage.parse() should be updated to know which nlmsg_type values
- * correspond with which message subclasses.
- *
- * @hide
- */
-public class NetlinkMessage {
- private final static String TAG = "NetlinkMessage";
-
- public static NetlinkMessage parse(ByteBuffer byteBuffer) {
- final int startPosition = (byteBuffer != null) ? byteBuffer.position() : -1;
- final StructNlMsgHdr nlmsghdr = StructNlMsgHdr.parse(byteBuffer);
- if (nlmsghdr == null) {
- return null;
- }
-
- int payloadLength = NetlinkConstants.alignedLengthOf(nlmsghdr.nlmsg_len);
- payloadLength -= StructNlMsgHdr.STRUCT_SIZE;
- if (payloadLength < 0 || payloadLength > byteBuffer.remaining()) {
- // Malformed message or runt buffer. Pretend the buffer was consumed.
- byteBuffer.position(byteBuffer.limit());
- return null;
- }
-
- switch (nlmsghdr.nlmsg_type) {
- //case NetlinkConstants.NLMSG_NOOP:
- case NetlinkConstants.NLMSG_ERROR:
- return (NetlinkMessage) NetlinkErrorMessage.parse(nlmsghdr, byteBuffer);
- case NetlinkConstants.NLMSG_DONE:
- byteBuffer.position(byteBuffer.position() + payloadLength);
- return new NetlinkMessage(nlmsghdr);
- //case NetlinkConstants.NLMSG_OVERRUN:
- case NetlinkConstants.RTM_NEWNEIGH:
- case NetlinkConstants.RTM_DELNEIGH:
- case NetlinkConstants.RTM_GETNEIGH:
- return (NetlinkMessage) RtNetlinkNeighborMessage.parse(nlmsghdr, byteBuffer);
- case NetlinkConstants.SOCK_DIAG_BY_FAMILY:
- return (NetlinkMessage) InetDiagMessage.parse(nlmsghdr, byteBuffer);
- default:
- if (nlmsghdr.nlmsg_type <= NetlinkConstants.NLMSG_MAX_RESERVED) {
- // Netlink control message. Just parse the header for now,
- // pretending the whole message was consumed.
- byteBuffer.position(byteBuffer.position() + payloadLength);
- return new NetlinkMessage(nlmsghdr);
- }
- return null;
- }
- }
-
- protected StructNlMsgHdr mHeader;
-
- public NetlinkMessage(StructNlMsgHdr nlmsghdr) {
- mHeader = nlmsghdr;
- }
-
- public StructNlMsgHdr getHeader() {
- return mHeader;
- }
-
- @Override
- public String toString() {
- return "NetlinkMessage{" + (mHeader == null ? "" : mHeader.toString()) + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/NetlinkSocket.java b/services/net/java/android/net/netlink/NetlinkSocket.java
deleted file mode 100644
index 7311fc5..0000000
--- a/services/net/java/android/net/netlink/NetlinkSocket.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import static android.net.util.SocketUtils.makeNetlinkSocketAddress;
-import static android.system.OsConstants.AF_NETLINK;
-import static android.system.OsConstants.EIO;
-import static android.system.OsConstants.EPROTO;
-import static android.system.OsConstants.ETIMEDOUT;
-import static android.system.OsConstants.SOCK_DGRAM;
-import static android.system.OsConstants.SOL_SOCKET;
-import static android.system.OsConstants.SO_RCVBUF;
-import static android.system.OsConstants.SO_RCVTIMEO;
-import static android.system.OsConstants.SO_SNDTIMEO;
-
-import android.net.util.SocketUtils;
-import android.system.ErrnoException;
-import android.system.Os;
-import android.system.StructTimeval;
-import android.util.Log;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-
-/**
- * NetlinkSocket
- *
- * A small static class to assist with AF_NETLINK socket operations.
- *
- * @hide
- */
-public class NetlinkSocket {
- private static final String TAG = "NetlinkSocket";
-
- public static final int DEFAULT_RECV_BUFSIZE = 8 * 1024;
- public static final int SOCKET_RECV_BUFSIZE = 64 * 1024;
-
- public static void sendOneShotKernelMessage(int nlProto, byte[] msg) throws ErrnoException {
- final String errPrefix = "Error in NetlinkSocket.sendOneShotKernelMessage";
- final long IO_TIMEOUT = 300L;
-
- final FileDescriptor fd = forProto(nlProto);
-
- try {
- connectToKernel(fd);
- sendMessage(fd, msg, 0, msg.length, IO_TIMEOUT);
- final ByteBuffer bytes = recvMessage(fd, DEFAULT_RECV_BUFSIZE, IO_TIMEOUT);
- // recvMessage() guaranteed to not return null if it did not throw.
- final NetlinkMessage response = NetlinkMessage.parse(bytes);
- if (response != null && response instanceof NetlinkErrorMessage &&
- (((NetlinkErrorMessage) response).getNlMsgError() != null)) {
- final int errno = ((NetlinkErrorMessage) response).getNlMsgError().error;
- if (errno != 0) {
- // TODO: consider ignoring EINVAL (-22), which appears to be
- // normal when probing a neighbor for which the kernel does
- // not already have / no longer has a link layer address.
- Log.e(TAG, errPrefix + ", errmsg=" + response.toString());
- // Note: convert kernel errnos (negative) into userspace errnos (positive).
- throw new ErrnoException(response.toString(), Math.abs(errno));
- }
- } else {
- final String errmsg;
- if (response == null) {
- bytes.position(0);
- errmsg = "raw bytes: " + NetlinkConstants.hexify(bytes);
- } else {
- errmsg = response.toString();
- }
- Log.e(TAG, errPrefix + ", errmsg=" + errmsg);
- throw new ErrnoException(errmsg, EPROTO);
- }
- } catch (InterruptedIOException e) {
- Log.e(TAG, errPrefix, e);
- throw new ErrnoException(errPrefix, ETIMEDOUT, e);
- } catch (SocketException e) {
- Log.e(TAG, errPrefix, e);
- throw new ErrnoException(errPrefix, EIO, e);
- } finally {
- try {
- SocketUtils.closeSocket(fd);
- } catch (IOException e) {
- // Nothing we can do here
- }
- }
- }
-
- public static FileDescriptor forProto(int nlProto) throws ErrnoException {
- final FileDescriptor fd = Os.socket(AF_NETLINK, SOCK_DGRAM, nlProto);
- Os.setsockoptInt(fd, SOL_SOCKET, SO_RCVBUF, SOCKET_RECV_BUFSIZE);
- return fd;
- }
-
- public static void connectToKernel(FileDescriptor fd) throws ErrnoException, SocketException {
- Os.connect(fd, makeNetlinkSocketAddress(0, 0));
- }
-
- private static void checkTimeout(long timeoutMs) {
- if (timeoutMs < 0) {
- throw new IllegalArgumentException("Negative timeouts not permitted");
- }
- }
-
- /**
- * Wait up to |timeoutMs| (or until underlying socket error) for a
- * netlink message of at most |bufsize| size.
- *
- * Multi-threaded calls with different timeouts will cause unexpected results.
- */
- public static ByteBuffer recvMessage(FileDescriptor fd, int bufsize, long timeoutMs)
- throws ErrnoException, IllegalArgumentException, InterruptedIOException {
- checkTimeout(timeoutMs);
-
- Os.setsockoptTimeval(fd, SOL_SOCKET, SO_RCVTIMEO, StructTimeval.fromMillis(timeoutMs));
-
- ByteBuffer byteBuffer = ByteBuffer.allocate(bufsize);
- int length = Os.read(fd, byteBuffer);
- if (length == bufsize) {
- Log.w(TAG, "maximum read");
- }
- byteBuffer.position(0);
- byteBuffer.limit(length);
- byteBuffer.order(ByteOrder.nativeOrder());
- return byteBuffer;
- }
-
- /**
- * Send a message to a peer to which this socket has previously connected,
- * waiting at most |timeoutMs| milliseconds for the send to complete.
- *
- * Multi-threaded calls with different timeouts will cause unexpected results.
- */
- public static int sendMessage(
- FileDescriptor fd, byte[] bytes, int offset, int count, long timeoutMs)
- throws ErrnoException, IllegalArgumentException, InterruptedIOException {
- checkTimeout(timeoutMs);
- Os.setsockoptTimeval(fd, SOL_SOCKET, SO_SNDTIMEO, StructTimeval.fromMillis(timeoutMs));
- return Os.write(fd, bytes, offset, count);
- }
-}
diff --git a/services/net/java/android/net/netlink/RtNetlinkNeighborMessage.java b/services/net/java/android/net/netlink/RtNetlinkNeighborMessage.java
deleted file mode 100644
index e784fbb..0000000
--- a/services/net/java/android/net/netlink/RtNetlinkNeighborMessage.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import static android.net.netlink.StructNlMsgHdr.NLM_F_ACK;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REPLACE;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
-
-import android.net.netlink.StructNdaCacheInfo;
-import android.net.netlink.StructNdMsg;
-import android.net.netlink.StructNlAttr;
-import android.net.netlink.StructNlMsgHdr;
-import android.net.netlink.NetlinkMessage;
-import android.system.OsConstants;
-import android.util.Log;
-
-import java.net.InetAddress;
-import java.net.Inet6Address;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-
-/**
- * A NetlinkMessage subclass for rtnetlink neighbor messages.
- *
- * see also: <linux_src>/include/uapi/linux/neighbour.h
- *
- * @hide
- */
-public class RtNetlinkNeighborMessage extends NetlinkMessage {
- public static final short NDA_UNSPEC = 0;
- public static final short NDA_DST = 1;
- public static final short NDA_LLADDR = 2;
- public static final short NDA_CACHEINFO = 3;
- public static final short NDA_PROBES = 4;
- public static final short NDA_VLAN = 5;
- public static final short NDA_PORT = 6;
- public static final short NDA_VNI = 7;
- public static final short NDA_IFINDEX = 8;
- public static final short NDA_MASTER = 9;
-
- private static StructNlAttr findNextAttrOfType(short attrType, ByteBuffer byteBuffer) {
- while (byteBuffer != null && byteBuffer.remaining() > 0) {
- final StructNlAttr nlAttr = StructNlAttr.peek(byteBuffer);
- if (nlAttr == null) {
- break;
- }
- if (nlAttr.nla_type == attrType) {
- return StructNlAttr.parse(byteBuffer);
- }
- if (byteBuffer.remaining() < nlAttr.getAlignedLength()) {
- break;
- }
- byteBuffer.position(byteBuffer.position() + nlAttr.getAlignedLength());
- }
- return null;
- }
-
- public static RtNetlinkNeighborMessage parse(StructNlMsgHdr header, ByteBuffer byteBuffer) {
- final RtNetlinkNeighborMessage neighMsg = new RtNetlinkNeighborMessage(header);
-
- neighMsg.mNdmsg = StructNdMsg.parse(byteBuffer);
- if (neighMsg.mNdmsg == null) {
- return null;
- }
-
- // Some of these are message-type dependent, and not always present.
- final int baseOffset = byteBuffer.position();
- StructNlAttr nlAttr = findNextAttrOfType(NDA_DST, byteBuffer);
- if (nlAttr != null) {
- neighMsg.mDestination = nlAttr.getValueAsInetAddress();
- }
-
- byteBuffer.position(baseOffset);
- nlAttr = findNextAttrOfType(NDA_LLADDR, byteBuffer);
- if (nlAttr != null) {
- neighMsg.mLinkLayerAddr = nlAttr.nla_value;
- }
-
- byteBuffer.position(baseOffset);
- nlAttr = findNextAttrOfType(NDA_PROBES, byteBuffer);
- if (nlAttr != null) {
- neighMsg.mNumProbes = nlAttr.getValueAsInt(0);
- }
-
- byteBuffer.position(baseOffset);
- nlAttr = findNextAttrOfType(NDA_CACHEINFO, byteBuffer);
- if (nlAttr != null) {
- neighMsg.mCacheInfo = StructNdaCacheInfo.parse(nlAttr.getValueAsByteBuffer());
- }
-
- final int kMinConsumed = StructNlMsgHdr.STRUCT_SIZE + StructNdMsg.STRUCT_SIZE;
- final int kAdditionalSpace = NetlinkConstants.alignedLengthOf(
- neighMsg.mHeader.nlmsg_len - kMinConsumed);
- if (byteBuffer.remaining() < kAdditionalSpace) {
- byteBuffer.position(byteBuffer.limit());
- } else {
- byteBuffer.position(baseOffset + kAdditionalSpace);
- }
-
- return neighMsg;
- }
-
- /**
- * A convenience method to create an RTM_GETNEIGH request message.
- */
- public static byte[] newGetNeighborsRequest(int seqNo) {
- final int length = StructNlMsgHdr.STRUCT_SIZE + StructNdMsg.STRUCT_SIZE;
- final byte[] bytes = new byte[length];
- final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
- byteBuffer.order(ByteOrder.nativeOrder());
-
- final StructNlMsgHdr nlmsghdr = new StructNlMsgHdr();
- nlmsghdr.nlmsg_len = length;
- nlmsghdr.nlmsg_type = NetlinkConstants.RTM_GETNEIGH;
- nlmsghdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
- nlmsghdr.nlmsg_seq = seqNo;
- nlmsghdr.pack(byteBuffer);
-
- final StructNdMsg ndmsg = new StructNdMsg();
- ndmsg.pack(byteBuffer);
-
- return bytes;
- }
-
- /**
- * A convenience method to create an RTM_NEWNEIGH message, to modify
- * the kernel's state information for a specific neighbor.
- */
- public static byte[] newNewNeighborMessage(
- int seqNo, InetAddress ip, short nudState, int ifIndex, byte[] llAddr) {
- final StructNlMsgHdr nlmsghdr = new StructNlMsgHdr();
- nlmsghdr.nlmsg_type = NetlinkConstants.RTM_NEWNEIGH;
- nlmsghdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE;
- nlmsghdr.nlmsg_seq = seqNo;
-
- final RtNetlinkNeighborMessage msg = new RtNetlinkNeighborMessage(nlmsghdr);
- msg.mNdmsg = new StructNdMsg();
- msg.mNdmsg.ndm_family =
- (byte) ((ip instanceof Inet6Address) ? OsConstants.AF_INET6 : OsConstants.AF_INET);
- msg.mNdmsg.ndm_ifindex = ifIndex;
- msg.mNdmsg.ndm_state = nudState;
- msg.mDestination = ip;
- msg.mLinkLayerAddr = llAddr; // might be null
-
- final byte[] bytes = new byte[msg.getRequiredSpace()];
- nlmsghdr.nlmsg_len = bytes.length;
- final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
- byteBuffer.order(ByteOrder.nativeOrder());
- msg.pack(byteBuffer);
- return bytes;
- }
-
- private StructNdMsg mNdmsg;
- private InetAddress mDestination;
- private byte[] mLinkLayerAddr;
- private int mNumProbes;
- private StructNdaCacheInfo mCacheInfo;
-
- private RtNetlinkNeighborMessage(StructNlMsgHdr header) {
- super(header);
- mNdmsg = null;
- mDestination = null;
- mLinkLayerAddr = null;
- mNumProbes = 0;
- mCacheInfo = null;
- }
-
- public StructNdMsg getNdHeader() {
- return mNdmsg;
- }
-
- public InetAddress getDestination() {
- return mDestination;
- }
-
- public byte[] getLinkLayerAddress() {
- return mLinkLayerAddr;
- }
-
- public int getProbes() {
- return mNumProbes;
- }
-
- public StructNdaCacheInfo getCacheInfo() {
- return mCacheInfo;
- }
-
- public int getRequiredSpace() {
- int spaceRequired = StructNlMsgHdr.STRUCT_SIZE + StructNdMsg.STRUCT_SIZE;
- if (mDestination != null) {
- spaceRequired += NetlinkConstants.alignedLengthOf(
- StructNlAttr.NLA_HEADERLEN + mDestination.getAddress().length);
- }
- if (mLinkLayerAddr != null) {
- spaceRequired += NetlinkConstants.alignedLengthOf(
- StructNlAttr.NLA_HEADERLEN + mLinkLayerAddr.length);
- }
- // Currently we don't write messages with NDA_PROBES nor NDA_CACHEINFO
- // attributes appended. Fix later, if necessary.
- return spaceRequired;
- }
-
- private static void packNlAttr(short nlType, byte[] nlValue, ByteBuffer byteBuffer) {
- final StructNlAttr nlAttr = new StructNlAttr();
- nlAttr.nla_type = nlType;
- nlAttr.nla_value = nlValue;
- nlAttr.nla_len = (short) (StructNlAttr.NLA_HEADERLEN + nlAttr.nla_value.length);
- nlAttr.pack(byteBuffer);
- }
-
- public void pack(ByteBuffer byteBuffer) {
- getHeader().pack(byteBuffer) ;
- mNdmsg.pack(byteBuffer);
-
- if (mDestination != null) {
- packNlAttr(NDA_DST, mDestination.getAddress(), byteBuffer);
- }
- if (mLinkLayerAddr != null) {
- packNlAttr(NDA_LLADDR, mLinkLayerAddr, byteBuffer);
- }
- }
-
- @Override
- public String toString() {
- final String ipLiteral = (mDestination == null) ? "" : mDestination.getHostAddress();
- return "RtNetlinkNeighborMessage{ "
- + "nlmsghdr{" + (mHeader == null ? "" : mHeader.toString()) + "}, "
- + "ndmsg{" + (mNdmsg == null ? "" : mNdmsg.toString()) + "}, "
- + "destination{" + ipLiteral + "} "
- + "linklayeraddr{" + NetlinkConstants.hexify(mLinkLayerAddr) + "} "
- + "probes{" + mNumProbes + "} "
- + "cacheinfo{" + (mCacheInfo == null ? "" : mCacheInfo.toString()) + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructInetDiagMsg.java b/services/net/java/android/net/netlink/StructInetDiagMsg.java
deleted file mode 100644
index da824ad..0000000
--- a/services/net/java/android/net/netlink/StructInetDiagMsg.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2018 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.netlink;
-
-import static java.nio.ByteOrder.BIG_ENDIAN;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-
-import java.net.Inet4Address;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import android.util.Log;
-
-/**
- * struct inet_diag_msg
- *
- * see <linux_src>/include/uapi/linux/inet_diag.h
- *
- * struct inet_diag_msg {
- * __u8 idiag_family;
- * __u8 idiag_state;
- * __u8 idiag_timer;
- * __u8 idiag_retrans;
- * struct inet_diag_sockid id;
- * __u32 idiag_expires;
- * __u32 idiag_rqueue;
- * __u32 idiag_wqueue;
- * __u32 idiag_uid;
- * __u32 idiag_inode;
- * };
- *
- * @hide
- */
-public class StructInetDiagMsg {
- public static final int STRUCT_SIZE = 4 + StructInetDiagSockId.STRUCT_SIZE + 20;
- private static final int IDIAG_UID_OFFSET = StructNlMsgHdr.STRUCT_SIZE + 4 +
- StructInetDiagSockId.STRUCT_SIZE + 12;
- public int idiag_uid;
-
- public static StructInetDiagMsg parse(ByteBuffer byteBuffer) {
- StructInetDiagMsg struct = new StructInetDiagMsg();
- struct.idiag_uid = byteBuffer.getInt(IDIAG_UID_OFFSET);
- return struct;
- }
-
- @Override
- public String toString() {
- return "StructInetDiagMsg{ "
- + "idiag_uid{" + idiag_uid + "}, "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructInetDiagReqV2.java b/services/net/java/android/net/netlink/StructInetDiagReqV2.java
deleted file mode 100644
index 2268113..0000000
--- a/services/net/java/android/net/netlink/StructInetDiagReqV2.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2018 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.netlink;
-
-import android.annotation.Nullable;
-
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-
-/**
- * struct inet_diag_req_v2
- *
- * see <linux_src>/include/uapi/linux/inet_diag.h
- *
- * struct inet_diag_req_v2 {
- * __u8 sdiag_family;
- * __u8 sdiag_protocol;
- * __u8 idiag_ext;
- * __u8 pad;
- * __u32 idiag_states;
- * struct inet_diag_sockid id;
- * };
- *
- * @hide
- */
-public class StructInetDiagReqV2 {
- public static final int STRUCT_SIZE = 8 + StructInetDiagSockId.STRUCT_SIZE;
-
- private final byte mSdiagFamily;
- private final byte mSdiagProtocol;
- private final byte mIdiagExt;
- private final byte mPad;
- private final StructInetDiagSockId mId;
- private final int mState;
- public static final int INET_DIAG_REQ_V2_ALL_STATES = (int) 0xffffffff;
-
- public StructInetDiagReqV2(int protocol, InetSocketAddress local, InetSocketAddress remote,
- int family) {
- this(protocol, local, remote, family, 0 /* pad */, 0 /* extension */,
- INET_DIAG_REQ_V2_ALL_STATES);
- }
-
- public StructInetDiagReqV2(int protocol, @Nullable InetSocketAddress local,
- @Nullable InetSocketAddress remote, int family, int pad, int extension, int state)
- throws NullPointerException {
- mSdiagFamily = (byte) family;
- mSdiagProtocol = (byte) protocol;
- // Request for all sockets if no specific socket is requested. Specify the local and remote
- // socket address information for target request socket.
- if ((local == null) != (remote == null)) {
- throw new NullPointerException("Local and remote must be both null or both non-null");
- }
- mId = ((local != null && remote != null) ? new StructInetDiagSockId(local, remote) : null);
- mPad = (byte) pad;
- mIdiagExt = (byte) extension;
- mState = state;
- }
-
- public void pack(ByteBuffer byteBuffer) {
- // The ByteOrder must have already been set by the caller.
- byteBuffer.put((byte) mSdiagFamily);
- byteBuffer.put((byte) mSdiagProtocol);
- byteBuffer.put((byte) mIdiagExt);
- byteBuffer.put((byte) mPad);
- byteBuffer.putInt(mState);
- if (mId != null) mId.pack(byteBuffer);
- }
-
- @Override
- public String toString() {
- final String familyStr = NetlinkConstants.stringForAddressFamily(mSdiagFamily);
- final String protocolStr = NetlinkConstants.stringForAddressFamily(mSdiagProtocol);
-
- return "StructInetDiagReqV2{ "
- + "sdiag_family{" + familyStr + "}, "
- + "sdiag_protocol{" + protocolStr + "}, "
- + "idiag_ext{" + mIdiagExt + ")}, "
- + "pad{" + mPad + "}, "
- + "idiag_states{" + Integer.toHexString(mState) + "}, "
- + ((mId != null) ? mId.toString() : "inet_diag_sockid=null")
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructInetDiagSockId.java b/services/net/java/android/net/netlink/StructInetDiagSockId.java
deleted file mode 100644
index 2e9fa25..0000000
--- a/services/net/java/android/net/netlink/StructInetDiagSockId.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2018 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.netlink;
-
-import static java.nio.ByteOrder.BIG_ENDIAN;
-
-import java.net.Inet4Address;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * struct inet_diag_req_v2
- *
- * see <linux_src>/include/uapi/linux/inet_diag.h
- *
- * struct inet_diag_sockid {
- * __be16 idiag_sport;
- * __be16 idiag_dport;
- * __be32 idiag_src[4];
- * __be32 idiag_dst[4];
- * __u32 idiag_if;
- * __u32 idiag_cookie[2];
- * #define INET_DIAG_NOCOOKIE (~0U)
- * };
- *
- * @hide
- */
-public class StructInetDiagSockId {
- public static final int STRUCT_SIZE = 48;
-
- private final InetSocketAddress mLocSocketAddress;
- private final InetSocketAddress mRemSocketAddress;
- private final byte[] INET_DIAG_NOCOOKIE = new byte[]{
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
- private final byte[] IPV4_PADDING = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-
- public StructInetDiagSockId(InetSocketAddress loc, InetSocketAddress rem) {
- mLocSocketAddress = loc;
- mRemSocketAddress = rem;
- }
-
- public void pack(ByteBuffer byteBuffer) {
- byteBuffer.order(BIG_ENDIAN);
- byteBuffer.putShort((short) mLocSocketAddress.getPort());
- byteBuffer.putShort((short) mRemSocketAddress.getPort());
- byteBuffer.put(mLocSocketAddress.getAddress().getAddress());
- if (mLocSocketAddress.getAddress() instanceof Inet4Address) {
- byteBuffer.put(IPV4_PADDING);
- }
- byteBuffer.put(mRemSocketAddress.getAddress().getAddress());
- if (mRemSocketAddress.getAddress() instanceof Inet4Address) {
- byteBuffer.put(IPV4_PADDING);
- }
- byteBuffer.order(ByteOrder.nativeOrder());
- byteBuffer.putInt(0);
- byteBuffer.put(INET_DIAG_NOCOOKIE);
- }
-
- @Override
- public String toString() {
- return "StructInetDiagSockId{ "
- + "idiag_sport{" + mLocSocketAddress.getPort() + "}, "
- + "idiag_dport{" + mRemSocketAddress.getPort() + "}, "
- + "idiag_src{" + mLocSocketAddress.getAddress().getHostAddress() + "}, "
- + "idiag_dst{" + mRemSocketAddress.getAddress().getHostAddress() + "}, "
- + "idiag_if{" + 0 + "} "
- + "idiag_cookie{INET_DIAG_NOCOOKIE}"
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructNdMsg.java b/services/net/java/android/net/netlink/StructNdMsg.java
deleted file mode 100644
index e34ec39..0000000
--- a/services/net/java/android/net/netlink/StructNdMsg.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.net.netlink.NetlinkConstants;
-import android.system.OsConstants;
-import java.nio.ByteBuffer;
-
-
-/**
- * struct ndmsg
- *
- * see: <linux_src>/include/uapi/linux/neighbour.h
- *
- * @hide
- */
-public class StructNdMsg {
- // Already aligned.
- public static final int STRUCT_SIZE = 12;
-
- // Neighbor Cache Entry States
- public static final short NUD_NONE = 0x00;
- public static final short NUD_INCOMPLETE = 0x01;
- public static final short NUD_REACHABLE = 0x02;
- public static final short NUD_STALE = 0x04;
- public static final short NUD_DELAY = 0x08;
- public static final short NUD_PROBE = 0x10;
- public static final short NUD_FAILED = 0x20;
- public static final short NUD_NOARP = 0x40;
- public static final short NUD_PERMANENT = 0x80;
-
- public static String stringForNudState(short nudState) {
- switch (nudState) {
- case NUD_NONE: return "NUD_NONE";
- case NUD_INCOMPLETE: return "NUD_INCOMPLETE";
- case NUD_REACHABLE: return "NUD_REACHABLE";
- case NUD_STALE: return "NUD_STALE";
- case NUD_DELAY: return "NUD_DELAY";
- case NUD_PROBE: return "NUD_PROBE";
- case NUD_FAILED: return "NUD_FAILED";
- case NUD_NOARP: return "NUD_NOARP";
- case NUD_PERMANENT: return "NUD_PERMANENT";
- default:
- return "unknown NUD state: " + String.valueOf(nudState);
- }
- }
-
- public static boolean isNudStateConnected(short nudState) {
- return ((nudState & (NUD_PERMANENT|NUD_NOARP|NUD_REACHABLE)) != 0);
- }
-
- public static boolean isNudStateValid(short nudState) {
- return (isNudStateConnected(nudState) ||
- ((nudState & (NUD_PROBE|NUD_STALE|NUD_DELAY)) != 0));
- }
-
- // Neighbor Cache Entry Flags
- public static byte NTF_USE = (byte) 0x01;
- public static byte NTF_SELF = (byte) 0x02;
- public static byte NTF_MASTER = (byte) 0x04;
- public static byte NTF_PROXY = (byte) 0x08;
- public static byte NTF_ROUTER = (byte) 0x80;
-
- public static String stringForNudFlags(byte flags) {
- final StringBuilder sb = new StringBuilder();
- if ((flags & NTF_USE) != 0) {
- sb.append("NTF_USE");
- }
- if ((flags & NTF_SELF) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NTF_SELF");
- }
- if ((flags & NTF_MASTER) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NTF_MASTER");
- }
- if ((flags & NTF_PROXY) != 0) {
- if (sb.length() > 0) { sb.append("|");
- }
- sb.append("NTF_PROXY"); }
- if ((flags & NTF_ROUTER) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NTF_ROUTER");
- }
- return sb.toString();
- }
-
- private static boolean hasAvailableSpace(ByteBuffer byteBuffer) {
- return byteBuffer != null && byteBuffer.remaining() >= STRUCT_SIZE;
- }
-
- public static StructNdMsg parse(ByteBuffer byteBuffer) {
- if (!hasAvailableSpace(byteBuffer)) { return null; }
-
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the possible
- // exception of usage within unittests.
- final StructNdMsg struct = new StructNdMsg();
- struct.ndm_family = byteBuffer.get();
- final byte pad1 = byteBuffer.get();
- final short pad2 = byteBuffer.getShort();
- struct.ndm_ifindex = byteBuffer.getInt();
- struct.ndm_state = byteBuffer.getShort();
- struct.ndm_flags = byteBuffer.get();
- struct.ndm_type = byteBuffer.get();
- return struct;
- }
-
- public byte ndm_family;
- public int ndm_ifindex;
- public short ndm_state;
- public byte ndm_flags;
- public byte ndm_type;
-
- public StructNdMsg() {
- ndm_family = (byte) OsConstants.AF_UNSPEC;
- }
-
- public void pack(ByteBuffer byteBuffer) {
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the exception
- // of usage within unittests.
- byteBuffer.put(ndm_family);
- byteBuffer.put((byte) 0); // pad1
- byteBuffer.putShort((short) 0); // pad2
- byteBuffer.putInt(ndm_ifindex);
- byteBuffer.putShort(ndm_state);
- byteBuffer.put(ndm_flags);
- byteBuffer.put(ndm_type);
- }
-
- public boolean nudConnected() {
- return isNudStateConnected(ndm_state);
- }
-
- public boolean nudValid() {
- return isNudStateValid(ndm_state);
- }
-
- @Override
- public String toString() {
- final String stateStr = "" + ndm_state + " (" + stringForNudState(ndm_state) + ")";
- final String flagsStr = "" + ndm_flags + " (" + stringForNudFlags(ndm_flags) + ")";
- return "StructNdMsg{ "
- + "family{" + NetlinkConstants.stringForAddressFamily((int) ndm_family) + "}, "
- + "ifindex{" + ndm_ifindex + "}, "
- + "state{" + stateStr + "}, "
- + "flags{" + flagsStr + "}, "
- + "type{" + ndm_type + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructNdaCacheInfo.java b/services/net/java/android/net/netlink/StructNdaCacheInfo.java
deleted file mode 100644
index 16cf563..0000000
--- a/services/net/java/android/net/netlink/StructNdaCacheInfo.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.system.Os;
-import android.system.OsConstants;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * struct nda_cacheinfo
- *
- * see: <linux_src>/include/uapi/linux/neighbour.h
- *
- * @hide
- */
-public class StructNdaCacheInfo {
- // Already aligned.
- public static final int STRUCT_SIZE = 16;
-
- private static boolean hasAvailableSpace(ByteBuffer byteBuffer) {
- return byteBuffer != null && byteBuffer.remaining() >= STRUCT_SIZE;
- }
-
- public static StructNdaCacheInfo parse(ByteBuffer byteBuffer) {
- if (!hasAvailableSpace(byteBuffer)) { return null; }
-
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the possible
- // exception of usage within unittests.
- final StructNdaCacheInfo struct = new StructNdaCacheInfo();
- struct.ndm_used = byteBuffer.getInt();
- struct.ndm_confirmed = byteBuffer.getInt();
- struct.ndm_updated = byteBuffer.getInt();
- struct.ndm_refcnt = byteBuffer.getInt();
- return struct;
- }
-
- // TODO: investigate whether this can change during device runtime and
- // decide what (if anything) should be done about that.
- private static final long CLOCK_TICKS_PER_SECOND = Os.sysconf(OsConstants._SC_CLK_TCK);
-
- private static long ticksToMilliSeconds(int intClockTicks) {
- final long longClockTicks = (long) intClockTicks & 0xffffffff;
- return (longClockTicks * 1000) / CLOCK_TICKS_PER_SECOND;
- }
-
- /**
- * Explanatory notes, for reference.
- *
- * Before being returned to user space, the neighbor entry times are
- * converted to clock_t's like so:
- *
- * ndm_used = jiffies_to_clock_t(now - neigh->used);
- * ndm_confirmed = jiffies_to_clock_t(now - neigh->confirmed);
- * ndm_updated = jiffies_to_clock_t(now - neigh->updated);
- *
- * meaning that these values are expressed as "clock ticks ago". To
- * convert these clock ticks to seconds divide by sysconf(_SC_CLK_TCK).
- * When _SC_CLK_TCK is 100, for example, the ndm_* times are expressed
- * in centiseconds.
- *
- * These values are unsigned, but fortunately being expressed as "some
- * clock ticks ago", these values are typically very small (and
- * 2^31 centiseconds = 248 days).
- *
- * By observation, it appears that:
- * ndm_used: the last time ARP/ND took place for this neighbor
- * ndm_confirmed: the last time ARP/ND succeeded for this neighbor OR
- * higher layer confirmation (TCP or MSG_CONFIRM)
- * was received
- * ndm_updated: the time when the current NUD state was entered
- */
- public int ndm_used;
- public int ndm_confirmed;
- public int ndm_updated;
- public int ndm_refcnt;
-
- public StructNdaCacheInfo() {}
-
- public long lastUsed() {
- return ticksToMilliSeconds(ndm_used);
- }
-
- public long lastConfirmed() {
- return ticksToMilliSeconds(ndm_confirmed);
- }
-
- public long lastUpdated() {
- return ticksToMilliSeconds(ndm_updated);
- }
-
- @Override
- public String toString() {
- return "NdaCacheInfo{ "
- + "ndm_used{" + lastUsed() + "}, "
- + "ndm_confirmed{" + lastConfirmed() + "}, "
- + "ndm_updated{" + lastUpdated() + "}, "
- + "ndm_refcnt{" + ndm_refcnt + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructNfGenMsg.java b/services/net/java/android/net/netlink/StructNfGenMsg.java
deleted file mode 100644
index 8155977..0000000
--- a/services/net/java/android/net/netlink/StructNfGenMsg.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.netlink;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * struct nfgenmsg
- *
- * see <linux_src>/include/uapi/linux/netfilter/nfnetlink.h
- *
- * @hide
- */
-public class StructNfGenMsg {
- public static final int STRUCT_SIZE = 2 + Short.BYTES;
-
- public static final int NFNETLINK_V0 = 0;
-
- final public byte nfgen_family;
- final public byte version;
- final public short res_id; // N.B.: this is big endian in the kernel
-
- public StructNfGenMsg(byte family) {
- nfgen_family = family;
- version = (byte) NFNETLINK_V0;
- res_id = (short) 0;
- }
-
- public void pack(ByteBuffer byteBuffer) {
- byteBuffer.put(nfgen_family);
- byteBuffer.put(version);
- byteBuffer.putShort(res_id);
- }
-}
diff --git a/services/net/java/android/net/netlink/StructNlAttr.java b/services/net/java/android/net/netlink/StructNlAttr.java
deleted file mode 100644
index 28a4e88..0000000
--- a/services/net/java/android/net/netlink/StructNlAttr.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.net.netlink.NetlinkConstants;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.nio.ByteOrder;
-import java.nio.ByteBuffer;
-
-
-/**
- * struct nlattr
- *
- * see: <linux_src>/include/uapi/linux/netlink.h
- *
- * @hide
- */
-public class StructNlAttr {
- // Already aligned.
- public static final int NLA_HEADERLEN = 4;
- public static final int NLA_F_NESTED = (1 << 15);
-
- public static short makeNestedType(short type) {
- return (short) (type | NLA_F_NESTED);
- }
-
- // Return a (length, type) object only, without consuming any bytes in
- // |byteBuffer| and without copying or interpreting any value bytes.
- // This is used for scanning over a packed set of struct nlattr's,
- // looking for instances of a particular type.
- public static StructNlAttr peek(ByteBuffer byteBuffer) {
- if (byteBuffer == null || byteBuffer.remaining() < NLA_HEADERLEN) {
- return null;
- }
- final int baseOffset = byteBuffer.position();
-
- // Assume the byte order of the buffer is the expected byte order of the value.
- final StructNlAttr struct = new StructNlAttr(byteBuffer.order());
- // The byte order of nla_len and nla_type is always native.
- final ByteOrder originalOrder = byteBuffer.order();
- byteBuffer.order(ByteOrder.nativeOrder());
- try {
- struct.nla_len = byteBuffer.getShort();
- struct.nla_type = byteBuffer.getShort();
- } finally {
- byteBuffer.order(originalOrder);
- }
-
- byteBuffer.position(baseOffset);
- if (struct.nla_len < NLA_HEADERLEN) {
- // Malformed.
- return null;
- }
- return struct;
- }
-
- public static StructNlAttr parse(ByteBuffer byteBuffer) {
- final StructNlAttr struct = peek(byteBuffer);
- if (struct == null || byteBuffer.remaining() < struct.getAlignedLength()) {
- return null;
- }
-
- final int baseOffset = byteBuffer.position();
- byteBuffer.position(baseOffset + NLA_HEADERLEN);
-
- int valueLen = ((int) struct.nla_len) & 0xffff;
- valueLen -= NLA_HEADERLEN;
- if (valueLen > 0) {
- struct.nla_value = new byte[valueLen];
- byteBuffer.get(struct.nla_value, 0, valueLen);
- byteBuffer.position(baseOffset + struct.getAlignedLength());
- }
- return struct;
- }
-
- public short nla_len = (short) NLA_HEADERLEN;
- public short nla_type;
- public byte[] nla_value;
-
- // The byte order used to read/write the value member. Netlink length and
- // type members are always read/written in native order.
- private ByteOrder mByteOrder = ByteOrder.nativeOrder();
-
- public StructNlAttr() {}
-
- public StructNlAttr(ByteOrder byteOrder) {
- mByteOrder = byteOrder;
- }
-
- public StructNlAttr(short type, byte value) {
- nla_type = type;
- setValue(new byte[1]);
- nla_value[0] = value;
- }
-
- public StructNlAttr(short type, short value) {
- this(type, value, ByteOrder.nativeOrder());
- }
-
- public StructNlAttr(short type, short value, ByteOrder order) {
- this(order);
- nla_type = type;
- setValue(new byte[Short.BYTES]);
- getValueAsByteBuffer().putShort(value);
- }
-
- public StructNlAttr(short type, int value) {
- this(type, value, ByteOrder.nativeOrder());
- }
-
- public StructNlAttr(short type, int value, ByteOrder order) {
- this(order);
- nla_type = type;
- setValue(new byte[Integer.BYTES]);
- getValueAsByteBuffer().putInt(value);
- }
-
- public StructNlAttr(short type, InetAddress ip) {
- nla_type = type;
- setValue(ip.getAddress());
- }
-
- public StructNlAttr(short type, StructNlAttr... nested) {
- this();
- nla_type = makeNestedType(type);
-
- int payloadLength = 0;
- for (StructNlAttr nla : nested) payloadLength += nla.getAlignedLength();
- setValue(new byte[payloadLength]);
-
- final ByteBuffer buf = getValueAsByteBuffer();
- for (StructNlAttr nla : nested) {
- nla.pack(buf);
- }
- }
-
- public int getAlignedLength() {
- return NetlinkConstants.alignedLengthOf(nla_len);
- }
-
- public ByteBuffer getValueAsByteBuffer() {
- if (nla_value == null) { return null; }
- final ByteBuffer byteBuffer = ByteBuffer.wrap(nla_value);
- byteBuffer.order(mByteOrder);
- return byteBuffer;
- }
-
- public int getValueAsInt(int defaultValue) {
- final ByteBuffer byteBuffer = getValueAsByteBuffer();
- if (byteBuffer == null || byteBuffer.remaining() != Integer.BYTES) {
- return defaultValue;
- }
- return getValueAsByteBuffer().getInt();
- }
-
- public InetAddress getValueAsInetAddress() {
- if (nla_value == null) { return null; }
-
- try {
- return InetAddress.getByAddress(nla_value);
- } catch (UnknownHostException ignored) {
- return null;
- }
- }
-
- public void pack(ByteBuffer byteBuffer) {
- final ByteOrder originalOrder = byteBuffer.order();
- final int originalPosition = byteBuffer.position();
-
- byteBuffer.order(ByteOrder.nativeOrder());
- try {
- byteBuffer.putShort(nla_len);
- byteBuffer.putShort(nla_type);
- if (nla_value != null) byteBuffer.put(nla_value);
- } finally {
- byteBuffer.order(originalOrder);
- }
- byteBuffer.position(originalPosition + getAlignedLength());
- }
-
- private void setValue(byte[] value) {
- nla_value = value;
- nla_len = (short) (NLA_HEADERLEN + ((nla_value != null) ? nla_value.length : 0));
- }
-
- @Override
- public String toString() {
- return "StructNlAttr{ "
- + "nla_len{" + nla_len + "}, "
- + "nla_type{" + nla_type + "}, "
- + "nla_value{" + NetlinkConstants.hexify(nla_value) + "}, "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructNlMsgErr.java b/services/net/java/android/net/netlink/StructNlMsgErr.java
deleted file mode 100644
index 6fcc6e6..0000000
--- a/services/net/java/android/net/netlink/StructNlMsgErr.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.net.netlink.NetlinkConstants;
-import android.net.netlink.StructNlMsgHdr;
-
-import java.nio.ByteBuffer;
-
-
-/**
- * struct nlmsgerr
- *
- * see <linux_src>/include/uapi/linux/netlink.h
- *
- * @hide
- */
-public class StructNlMsgErr {
- public static final int STRUCT_SIZE = Integer.BYTES + StructNlMsgHdr.STRUCT_SIZE;
-
- public static boolean hasAvailableSpace(ByteBuffer byteBuffer) {
- return byteBuffer != null && byteBuffer.remaining() >= STRUCT_SIZE;
- }
-
- public static StructNlMsgErr parse(ByteBuffer byteBuffer) {
- if (!hasAvailableSpace(byteBuffer)) { return null; }
-
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the exception
- // of usage within unittests.
- final StructNlMsgErr struct = new StructNlMsgErr();
- struct.error = byteBuffer.getInt();
- struct.msg = StructNlMsgHdr.parse(byteBuffer);
- return struct;
- }
-
- public int error;
- public StructNlMsgHdr msg;
-
- public void pack(ByteBuffer byteBuffer) {
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the possible
- // exception of usage within unittests.
- byteBuffer.putInt(error);
- if (msg != null) {
- msg.pack(byteBuffer);
- }
- }
-
- @Override
- public String toString() {
- return "StructNlMsgErr{ "
- + "error{" + error + "}, "
- + "msg{" + (msg == null ? "" : msg.toString()) + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/netlink/StructNlMsgHdr.java b/services/net/java/android/net/netlink/StructNlMsgHdr.java
deleted file mode 100644
index 98ab5e7..0000000
--- a/services/net/java/android/net/netlink/StructNlMsgHdr.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import android.net.netlink.NetlinkConstants;
-import java.nio.ByteBuffer;
-
-
-/**
- * struct nlmsghdr
- *
- * see <linux_src>/include/uapi/linux/netlink.h
- *
- * @hide
- */
-public class StructNlMsgHdr {
- // Already aligned.
- public static final int STRUCT_SIZE = 16;
-
- public static final short NLM_F_REQUEST = 0x0001;
- public static final short NLM_F_MULTI = 0x0002;
- public static final short NLM_F_ACK = 0x0004;
- public static final short NLM_F_ECHO = 0x0008;
- // Flags for a GET request.
- public static final short NLM_F_ROOT = 0x0100;
- public static final short NLM_F_MATCH = 0x0200;
- public static final short NLM_F_DUMP = NLM_F_ROOT|NLM_F_MATCH;
- // Flags for a NEW request.
- public static final short NLM_F_REPLACE = 0x100;
- public static final short NLM_F_EXCL = 0x200;
- public static final short NLM_F_CREATE = 0x400;
- public static final short NLM_F_APPEND = 0x800;
-
-
- public static String stringForNlMsgFlags(short flags) {
- final StringBuilder sb = new StringBuilder();
- if ((flags & NLM_F_REQUEST) != 0) {
- sb.append("NLM_F_REQUEST");
- }
- if ((flags & NLM_F_MULTI) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NLM_F_MULTI");
- }
- if ((flags & NLM_F_ACK) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NLM_F_ACK");
- }
- if ((flags & NLM_F_ECHO) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NLM_F_ECHO");
- }
- if ((flags & NLM_F_ROOT) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NLM_F_ROOT");
- }
- if ((flags & NLM_F_MATCH) != 0) {
- if (sb.length() > 0) { sb.append("|"); }
- sb.append("NLM_F_MATCH");
- }
- return sb.toString();
- }
-
- public static boolean hasAvailableSpace(ByteBuffer byteBuffer) {
- return byteBuffer != null && byteBuffer.remaining() >= STRUCT_SIZE;
- }
-
- public static StructNlMsgHdr parse(ByteBuffer byteBuffer) {
- if (!hasAvailableSpace(byteBuffer)) { return null; }
-
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the exception
- // of usage within unittests.
- final StructNlMsgHdr struct = new StructNlMsgHdr();
- struct.nlmsg_len = byteBuffer.getInt();
- struct.nlmsg_type = byteBuffer.getShort();
- struct.nlmsg_flags = byteBuffer.getShort();
- struct.nlmsg_seq = byteBuffer.getInt();
- struct.nlmsg_pid = byteBuffer.getInt();
-
- if (struct.nlmsg_len < STRUCT_SIZE) {
- // Malformed.
- return null;
- }
- return struct;
- }
-
- public int nlmsg_len;
- public short nlmsg_type;
- public short nlmsg_flags;
- public int nlmsg_seq;
- public int nlmsg_pid;
-
- public StructNlMsgHdr() {
- nlmsg_len = 0;
- nlmsg_type = 0;
- nlmsg_flags = 0;
- nlmsg_seq = 0;
- nlmsg_pid = 0;
- }
-
- public void pack(ByteBuffer byteBuffer) {
- // The ByteOrder must have already been set by the caller. In most
- // cases ByteOrder.nativeOrder() is correct, with the possible
- // exception of usage within unittests.
- byteBuffer.putInt(nlmsg_len);
- byteBuffer.putShort(nlmsg_type);
- byteBuffer.putShort(nlmsg_flags);
- byteBuffer.putInt(nlmsg_seq);
- byteBuffer.putInt(nlmsg_pid);
- }
-
- @Override
- public String toString() {
- final String typeStr = "" + nlmsg_type
- + "(" + NetlinkConstants.stringForNlMsgType(nlmsg_type) + ")";
- final String flagsStr = "" + nlmsg_flags
- + "(" + stringForNlMsgFlags(nlmsg_flags) + ")";
- return "StructNlMsgHdr{ "
- + "nlmsg_len{" + nlmsg_len + "}, "
- + "nlmsg_type{" + typeStr + "}, "
- + "nlmsg_flags{" + flagsStr + ")}, "
- + "nlmsg_seq{" + nlmsg_seq + "}, "
- + "nlmsg_pid{" + nlmsg_pid + "} "
- + "}";
- }
-}
diff --git a/services/net/java/android/net/shared/InitialConfiguration.java b/services/net/java/android/net/shared/InitialConfiguration.java
deleted file mode 100644
index 007c8ca9..0000000
--- a/services/net/java/android/net/shared/InitialConfiguration.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import static android.net.shared.ParcelableUtil.fromParcelableArray;
-import static android.net.shared.ParcelableUtil.toParcelableArray;
-import static android.text.TextUtils.join;
-
-import android.net.InetAddresses;
-import android.net.InitialConfigurationParcelable;
-import android.net.IpPrefix;
-import android.net.LinkAddress;
-import android.net.RouteInfo;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.function.Predicate;
-
-/** @hide */
-public class InitialConfiguration {
- public final Set<LinkAddress> ipAddresses = new HashSet<>();
- public final Set<IpPrefix> directlyConnectedRoutes = new HashSet<>();
- public final Set<InetAddress> dnsServers = new HashSet<>();
-
- private static final int RFC6177_MIN_PREFIX_LENGTH = 48;
- private static final int RFC7421_PREFIX_LENGTH = 64;
-
- public static final InetAddress INET6_ANY = InetAddresses.parseNumericAddress("::");
-
- /**
- * Create a InitialConfiguration that is a copy of the specified configuration.
- */
- public static InitialConfiguration copy(InitialConfiguration config) {
- if (config == null) {
- return null;
- }
- InitialConfiguration configCopy = new InitialConfiguration();
- configCopy.ipAddresses.addAll(config.ipAddresses);
- configCopy.directlyConnectedRoutes.addAll(config.directlyConnectedRoutes);
- configCopy.dnsServers.addAll(config.dnsServers);
- return configCopy;
- }
-
- @Override
- public String toString() {
- return String.format(
- "InitialConfiguration(IPs: {%s}, prefixes: {%s}, DNS: {%s})",
- join(", ", ipAddresses), join(", ", directlyConnectedRoutes),
- join(", ", dnsServers));
- }
-
- /**
- * Tests whether the contents of this IpConfiguration represent a valid configuration.
- */
- public boolean isValid() {
- if (ipAddresses.isEmpty()) {
- return false;
- }
-
- // For every IP address, there must be at least one prefix containing that address.
- for (LinkAddress addr : ipAddresses) {
- if (!any(directlyConnectedRoutes, (p) -> p.contains(addr.getAddress()))) {
- return false;
- }
- }
- // For every dns server, there must be at least one prefix containing that address.
- for (InetAddress addr : dnsServers) {
- if (!any(directlyConnectedRoutes, (p) -> p.contains(addr))) {
- return false;
- }
- }
- // All IPv6 LinkAddresses have an RFC7421-suitable prefix length
- // (read: compliant with RFC4291#section2.5.4).
- if (any(ipAddresses, not(InitialConfiguration::isPrefixLengthCompliant))) {
- return false;
- }
- // If directlyConnectedRoutes contains an IPv6 default route
- // then ipAddresses MUST contain at least one non-ULA GUA.
- if (any(directlyConnectedRoutes, InitialConfiguration::isIPv6DefaultRoute)
- && all(ipAddresses, not(InitialConfiguration::isIPv6GUA))) {
- return false;
- }
- // The prefix length of routes in directlyConnectedRoutes be within reasonable
- // bounds for IPv6: /48-/64 just as we’d accept in RIOs.
- if (any(directlyConnectedRoutes, not(InitialConfiguration::isPrefixLengthCompliant))) {
- return false;
- }
- // There no more than one IPv4 address
- if (ipAddresses.stream().filter(InitialConfiguration::isIPv4).count() > 1) {
- return false;
- }
-
- return true;
- }
-
- /**
- * @return true if the given list of addressess and routes satisfies provisioning for this
- * InitialConfiguration. LinkAddresses and RouteInfo objects are not compared with equality
- * because addresses and routes seen by Netlink will contain additional fields like flags,
- * interfaces, and so on. If this InitialConfiguration has no IP address specified, the
- * provisioning check always fails.
- *
- * If the given list of routes is null, only addresses are taken into considerations.
- */
- public boolean isProvisionedBy(List<LinkAddress> addresses, List<RouteInfo> routes) {
- if (ipAddresses.isEmpty()) {
- return false;
- }
-
- for (LinkAddress addr : ipAddresses) {
- if (!any(addresses, (addrSeen) -> addr.isSameAddressAs(addrSeen))) {
- return false;
- }
- }
-
- if (routes != null) {
- for (IpPrefix prefix : directlyConnectedRoutes) {
- if (!any(routes, (routeSeen) -> isDirectlyConnectedRoute(routeSeen, prefix))) {
- return false;
- }
- }
- }
-
- return true;
- }
-
- /**
- * Convert this configuration to a {@link InitialConfigurationParcelable}.
- */
- public InitialConfigurationParcelable toStableParcelable() {
- final InitialConfigurationParcelable p = new InitialConfigurationParcelable();
- p.ipAddresses = ipAddresses.toArray(new LinkAddress[0]);
- p.directlyConnectedRoutes = directlyConnectedRoutes.toArray(new IpPrefix[0]);
- p.dnsServers = toParcelableArray(
- dnsServers, IpConfigurationParcelableUtil::parcelAddress, String.class);
- return p;
- }
-
- /**
- * Create an instance of {@link InitialConfiguration} based on the contents of the specified
- * {@link InitialConfigurationParcelable}.
- */
- public static InitialConfiguration fromStableParcelable(InitialConfigurationParcelable p) {
- if (p == null) return null;
- final InitialConfiguration config = new InitialConfiguration();
- config.ipAddresses.addAll(Arrays.asList(p.ipAddresses));
- config.directlyConnectedRoutes.addAll(Arrays.asList(p.directlyConnectedRoutes));
- config.dnsServers.addAll(
- fromParcelableArray(p.dnsServers, IpConfigurationParcelableUtil::unparcelAddress));
- return config;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof InitialConfiguration)) return false;
- final InitialConfiguration other = (InitialConfiguration) obj;
- return ipAddresses.equals(other.ipAddresses)
- && directlyConnectedRoutes.equals(other.directlyConnectedRoutes)
- && dnsServers.equals(other.dnsServers);
- }
-
- private static boolean isDirectlyConnectedRoute(RouteInfo route, IpPrefix prefix) {
- return !route.hasGateway() && prefix.equals(route.getDestination());
- }
-
- private static boolean isPrefixLengthCompliant(LinkAddress addr) {
- return isIPv4(addr) || isCompliantIPv6PrefixLength(addr.getPrefixLength());
- }
-
- private static boolean isPrefixLengthCompliant(IpPrefix prefix) {
- return isIPv4(prefix) || isCompliantIPv6PrefixLength(prefix.getPrefixLength());
- }
-
- private static boolean isCompliantIPv6PrefixLength(int prefixLength) {
- return (RFC6177_MIN_PREFIX_LENGTH <= prefixLength)
- && (prefixLength <= RFC7421_PREFIX_LENGTH);
- }
-
- private static boolean isIPv4(IpPrefix prefix) {
- return prefix.getAddress() instanceof Inet4Address;
- }
-
- private static boolean isIPv4(LinkAddress addr) {
- return addr.getAddress() instanceof Inet4Address;
- }
-
- private static boolean isIPv6DefaultRoute(IpPrefix prefix) {
- return prefix.getAddress().equals(INET6_ANY);
- }
-
- private static boolean isIPv6GUA(LinkAddress addr) {
- return addr.isIpv6() && addr.isGlobalPreferred();
- }
-
- // TODO: extract out into CollectionUtils.
-
- /**
- * Indicate whether any element of the specified iterable verifies the specified predicate.
- */
- public static <T> boolean any(Iterable<T> coll, Predicate<T> fn) {
- for (T t : coll) {
- if (fn.test(t)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Indicate whether all elements of the specified iterable verifies the specified predicate.
- */
- public static <T> boolean all(Iterable<T> coll, Predicate<T> fn) {
- return !any(coll, not(fn));
- }
-
- /**
- * Create a predicate that returns the opposite value of the specified predicate.
- */
- public static <T> Predicate<T> not(Predicate<T> fn) {
- return (t) -> !fn.test(t);
- }
-}
diff --git a/services/net/java/android/net/shared/IpConfigurationParcelableUtil.java b/services/net/java/android/net/shared/IpConfigurationParcelableUtil.java
deleted file mode 100644
index 172dc24..0000000
--- a/services/net/java/android/net/shared/IpConfigurationParcelableUtil.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import android.annotation.Nullable;
-import android.net.DhcpResults;
-import android.net.DhcpResultsParcelable;
-import android.net.InetAddresses;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-
-/**
- * Collection of utility methods to convert to and from stable AIDL parcelables for IpClient
- * configuration classes.
- * @hide
- */
-public final class IpConfigurationParcelableUtil {
- /**
- * Convert DhcpResults to a DhcpResultsParcelable.
- */
- public static DhcpResultsParcelable toStableParcelable(@Nullable DhcpResults results) {
- if (results == null) return null;
- final DhcpResultsParcelable p = new DhcpResultsParcelable();
- p.baseConfiguration = results.toStaticIpConfiguration();
- p.leaseDuration = results.leaseDuration;
- p.mtu = results.mtu;
- p.serverAddress = parcelAddress(results.serverAddress);
- p.vendorInfo = results.vendorInfo;
- p.serverHostName = results.serverHostName;
- return p;
- }
-
- /**
- * Convert a DhcpResultsParcelable to DhcpResults.
- */
- public static DhcpResults fromStableParcelable(@Nullable DhcpResultsParcelable p) {
- if (p == null) return null;
- final DhcpResults results = new DhcpResults(p.baseConfiguration);
- results.leaseDuration = p.leaseDuration;
- results.mtu = p.mtu;
- results.serverAddress = (Inet4Address) unparcelAddress(p.serverAddress);
- results.vendorInfo = p.vendorInfo;
- results.serverHostName = p.serverHostName;
- return results;
- }
-
- /**
- * Convert InetAddress to String.
- * TODO: have an InetAddressParcelable
- */
- public static String parcelAddress(@Nullable InetAddress addr) {
- if (addr == null) return null;
- return addr.getHostAddress();
- }
-
- /**
- * Convert String to InetAddress.
- * TODO: have an InetAddressParcelable
- */
- public static InetAddress unparcelAddress(@Nullable String addr) {
- if (addr == null) return null;
- return InetAddresses.parseNumericAddress(addr);
- }
-}
diff --git a/services/net/java/android/net/shared/LinkPropertiesParcelableUtil.java b/services/net/java/android/net/shared/LinkPropertiesParcelableUtil.java
deleted file mode 100644
index 1729da6..0000000
--- a/services/net/java/android/net/shared/LinkPropertiesParcelableUtil.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import android.annotation.Nullable;
-import android.net.LinkProperties;
-import android.net.ProxyInfo;
-
-/**
- * Collection of utility methods to convert to and from stable AIDL parcelables for LinkProperties
- * and its attributes.
- * @hide
- */
-public final class LinkPropertiesParcelableUtil {
- // Temporary methods to facilitate migrating clients away from LinkPropertiesParcelable
- // TODO: remove the following methods after migrating clients.
-
- /**
- * @deprecated conversion to stable parcelable is no longer necessary.
- */
- @Deprecated
- public static LinkProperties toStableParcelable(@Nullable LinkProperties lp) {
- return lp;
- }
-
- /**
- * @deprecated conversion to stable parcelable is no longer necessary.
- */
- @Deprecated
- public static ProxyInfo toStableParcelable(@Nullable ProxyInfo info) {
- return info;
- }
-}
diff --git a/services/net/java/android/net/shared/NetworkMonitorUtils.java b/services/net/java/android/net/shared/NetworkMonitorUtils.java
deleted file mode 100644
index 46e9c73..0000000
--- a/services/net/java/android/net/shared/NetworkMonitorUtils.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2018 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.shared;
-
-import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
-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_TRUSTED;
-
-import android.net.NetworkCapabilities;
-
-/** @hide */
-public class NetworkMonitorUtils {
-
- // Network conditions broadcast constants
- public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
- "android.net.conn.NETWORK_CONDITIONS_MEASURED";
- public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
- public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
- public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
- public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
- public static final String EXTRA_CELL_ID = "extra_cellid";
- public static final String EXTRA_SSID = "extra_ssid";
- public static final String EXTRA_BSSID = "extra_bssid";
- /** real time since boot */
- public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
- public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
- public static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
- "android.permission.ACCESS_NETWORK_CONDITIONS";
-
- /**
- * Return whether validation is required for private DNS in strict mode.
- * @param nc Network capabilities of the network to test.
- */
- public static boolean isPrivateDnsValidationRequired(NetworkCapabilities nc) {
- // TODO: Consider requiring validation for DUN networks.
- return nc != null
- && nc.hasCapability(NET_CAPABILITY_INTERNET)
- && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
- && nc.hasCapability(NET_CAPABILITY_TRUSTED);
- }
-
- /**
- * Return whether validation is required for a network.
- * @param nc Network capabilities of the network to test.
- */
- public static boolean isValidationRequired(NetworkCapabilities nc) {
- // TODO: Consider requiring validation for DUN networks.
- return isPrivateDnsValidationRequired(nc) && nc.hasCapability(NET_CAPABILITY_NOT_VPN);
- }
-}
diff --git a/services/net/java/android/net/shared/ParcelableUtil.java b/services/net/java/android/net/shared/ParcelableUtil.java
deleted file mode 100644
index 3f40300..0000000
--- a/services/net/java/android/net/shared/ParcelableUtil.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import android.annotation.NonNull;
-
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.function.Function;
-
-/**
- * Utility methods to help convert to/from stable parcelables.
- * @hide
- */
-public final class ParcelableUtil {
- // Below methods could be implemented easily with streams, but streams are frowned upon in
- // frameworks code.
-
- /**
- * Convert a list of BaseType items to an array of ParcelableType items using the specified
- * converter function.
- */
- public static <ParcelableType, BaseType> ParcelableType[] toParcelableArray(
- @NonNull Collection<BaseType> base,
- @NonNull Function<BaseType, ParcelableType> conv,
- @NonNull Class<ParcelableType> parcelClass) {
- final ParcelableType[] out = (ParcelableType[]) Array.newInstance(parcelClass, base.size());
- int i = 0;
- for (BaseType b : base) {
- out[i] = conv.apply(b);
- i++;
- }
- return out;
- }
-
- /**
- * Convert an array of ParcelableType items to a list of BaseType items using the specified
- * converter function.
- */
- public static <ParcelableType, BaseType> ArrayList<BaseType> fromParcelableArray(
- @NonNull ParcelableType[] parceled, @NonNull Function<ParcelableType, BaseType> conv) {
- final ArrayList<BaseType> out = new ArrayList<>(parceled.length);
- for (ParcelableType t : parceled) {
- out.add(conv.apply(t));
- }
- return out;
- }
-}
diff --git a/services/net/java/android/net/shared/PrivateDnsConfig.java b/services/net/java/android/net/shared/PrivateDnsConfig.java
deleted file mode 100644
index c7dc530..0000000
--- a/services/net/java/android/net/shared/PrivateDnsConfig.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2018 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.shared;
-
-import static android.net.shared.ParcelableUtil.fromParcelableArray;
-import static android.net.shared.ParcelableUtil.toParcelableArray;
-
-import android.net.PrivateDnsConfigParcel;
-import android.text.TextUtils;
-
-import java.net.InetAddress;
-import java.util.Arrays;
-
-/** @hide */
-public class PrivateDnsConfig {
- public final boolean useTls;
- public final String hostname;
- public final InetAddress[] ips;
-
- public PrivateDnsConfig() {
- this(false);
- }
-
- public PrivateDnsConfig(boolean useTls) {
- this.useTls = useTls;
- this.hostname = "";
- this.ips = new InetAddress[0];
- }
-
- public PrivateDnsConfig(String hostname, InetAddress[] ips) {
- this.useTls = !TextUtils.isEmpty(hostname);
- this.hostname = useTls ? hostname : "";
- this.ips = (ips != null) ? ips : new InetAddress[0];
- }
-
- public PrivateDnsConfig(PrivateDnsConfig cfg) {
- useTls = cfg.useTls;
- hostname = cfg.hostname;
- ips = cfg.ips;
- }
-
- /**
- * Indicates whether this is a strict mode private DNS configuration.
- */
- public boolean inStrictMode() {
- return useTls && !TextUtils.isEmpty(hostname);
- }
-
- @Override
- public String toString() {
- return PrivateDnsConfig.class.getSimpleName()
- + "{" + useTls + ":" + hostname + "/" + Arrays.toString(ips) + "}";
- }
-
- /**
- * Create a stable AIDL-compatible parcel from the current instance.
- */
- public PrivateDnsConfigParcel toParcel() {
- final PrivateDnsConfigParcel parcel = new PrivateDnsConfigParcel();
- parcel.hostname = hostname;
- parcel.ips = toParcelableArray(
- Arrays.asList(ips), IpConfigurationParcelableUtil::parcelAddress, String.class);
-
- return parcel;
- }
-
- /**
- * Build a configuration from a stable AIDL-compatible parcel.
- */
- public static PrivateDnsConfig fromParcel(PrivateDnsConfigParcel parcel) {
- InetAddress[] ips = new InetAddress[parcel.ips.length];
- ips = fromParcelableArray(parcel.ips, IpConfigurationParcelableUtil::unparcelAddress)
- .toArray(ips);
- return new PrivateDnsConfig(parcel.hostname, ips);
- }
-}
diff --git a/services/net/java/android/net/shared/ProvisioningConfiguration.java b/services/net/java/android/net/shared/ProvisioningConfiguration.java
deleted file mode 100644
index 6f9c294..0000000
--- a/services/net/java/android/net/shared/ProvisioningConfiguration.java
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import android.annotation.Nullable;
-import android.net.INetd;
-import android.net.Network;
-import android.net.ProvisioningConfigurationParcelable;
-import android.net.StaticIpConfiguration;
-import android.net.apf.ApfCapabilities;
-import android.net.ip.IIpClient;
-
-import java.util.Objects;
-import java.util.StringJoiner;
-
-/**
- * This class encapsulates parameters to be passed to
- * IpClient#startProvisioning(). A defensive copy is made by IpClient
- * and the values specified herein are in force until IpClient#stop()
- * is called.
- *
- * Example use:
- *
- * final ProvisioningConfiguration config =
- * new ProvisioningConfiguration.Builder()
- * .withPreDhcpAction()
- * .withProvisioningTimeoutMs(36 * 1000)
- * .build();
- * mIpClient.startProvisioning(config.toStableParcelable());
- * ...
- * mIpClient.stop();
- *
- * The specified provisioning configuration will only be active until
- * IIpClient#stop() is called. Future calls to IIpClient#startProvisioning()
- * must specify the configuration again.
- * @hide
- */
-public class ProvisioningConfiguration {
- // TODO: Delete this default timeout once those callers that care are
- // fixed to pass in their preferred timeout.
- //
- // We pick 36 seconds so we can send DHCP requests at
- //
- // t=0, t=2, t=6, t=14, t=30
- //
- // allowing for 10% jitter.
- private static final int DEFAULT_TIMEOUT_MS = 36 * 1000;
-
- /**
- * Builder to create a {@link ProvisioningConfiguration}.
- */
- public static class Builder {
- protected ProvisioningConfiguration mConfig = new ProvisioningConfiguration();
-
- /**
- * Specify that the configuration should not enable IPv4. It is enabled by default.
- */
- public Builder withoutIPv4() {
- mConfig.mEnableIPv4 = false;
- return this;
- }
-
- /**
- * Specify that the configuration should not enable IPv6. It is enabled by default.
- */
- public Builder withoutIPv6() {
- mConfig.mEnableIPv6 = false;
- return this;
- }
-
- /**
- * Specify that the configuration should not use a MultinetworkPolicyTracker. It is used
- * by default.
- */
- public Builder withoutMultinetworkPolicyTracker() {
- mConfig.mUsingMultinetworkPolicyTracker = false;
- return this;
- }
-
- /**
- * Specify that the configuration should not use a IpReachabilityMonitor. It is used by
- * default.
- */
- public Builder withoutIpReachabilityMonitor() {
- mConfig.mUsingIpReachabilityMonitor = false;
- return this;
- }
-
- /**
- * Identical to {@link #withPreDhcpAction(int)}, using a default timeout.
- * @see #withPreDhcpAction(int)
- */
- public Builder withPreDhcpAction() {
- mConfig.mRequestedPreDhcpActionMs = DEFAULT_TIMEOUT_MS;
- return this;
- }
-
- /**
- * Specify that {@link IpClientCallbacks#onPreDhcpAction()} should be called. Clients must
- * call {@link IIpClient#completedPreDhcpAction()} when the callback called. This behavior
- * is disabled by default.
- * @param dhcpActionTimeoutMs Timeout for clients to call completedPreDhcpAction().
- */
- public Builder withPreDhcpAction(int dhcpActionTimeoutMs) {
- mConfig.mRequestedPreDhcpActionMs = dhcpActionTimeoutMs;
- return this;
- }
-
- /**
- * Specify the initial provisioning configuration.
- */
- public Builder withInitialConfiguration(InitialConfiguration initialConfig) {
- mConfig.mInitialConfig = initialConfig;
- return this;
- }
-
- /**
- * Specify a static configuration for provisioning.
- */
- public Builder withStaticConfiguration(StaticIpConfiguration staticConfig) {
- mConfig.mStaticIpConfig = staticConfig;
- return this;
- }
-
- /**
- * Specify ApfCapabilities.
- */
- public Builder withApfCapabilities(ApfCapabilities apfCapabilities) {
- mConfig.mApfCapabilities = apfCapabilities;
- return this;
- }
-
- /**
- * Specify the timeout to use for provisioning.
- */
- public Builder withProvisioningTimeoutMs(int timeoutMs) {
- mConfig.mProvisioningTimeoutMs = timeoutMs;
- return this;
- }
-
- /**
- * Specify that IPv6 address generation should use a random MAC address.
- */
- public Builder withRandomMacAddress() {
- mConfig.mIPv6AddrGenMode = INetd.IPV6_ADDR_GEN_MODE_EUI64;
- return this;
- }
-
- /**
- * Specify that IPv6 address generation should use a stable MAC address.
- */
- public Builder withStableMacAddress() {
- mConfig.mIPv6AddrGenMode = INetd.IPV6_ADDR_GEN_MODE_STABLE_PRIVACY;
- return this;
- }
-
- /**
- * Specify the network to use for provisioning.
- */
- public Builder withNetwork(Network network) {
- mConfig.mNetwork = network;
- return this;
- }
-
- /**
- * Specify the display name that the IpClient should use.
- */
- public Builder withDisplayName(String displayName) {
- mConfig.mDisplayName = displayName;
- return this;
- }
-
- /**
- * Build the configuration using previously specified parameters.
- */
- public ProvisioningConfiguration build() {
- return new ProvisioningConfiguration(mConfig);
- }
- }
-
- public boolean mEnableIPv4 = true;
- public boolean mEnableIPv6 = true;
- public boolean mUsingMultinetworkPolicyTracker = true;
- public boolean mUsingIpReachabilityMonitor = true;
- public int mRequestedPreDhcpActionMs;
- public InitialConfiguration mInitialConfig;
- public StaticIpConfiguration mStaticIpConfig;
- public ApfCapabilities mApfCapabilities;
- public int mProvisioningTimeoutMs = DEFAULT_TIMEOUT_MS;
- public int mIPv6AddrGenMode = INetd.IPV6_ADDR_GEN_MODE_STABLE_PRIVACY;
- public Network mNetwork = null;
- public String mDisplayName = null;
-
- public ProvisioningConfiguration() {} // used by Builder
-
- public ProvisioningConfiguration(ProvisioningConfiguration other) {
- mEnableIPv4 = other.mEnableIPv4;
- mEnableIPv6 = other.mEnableIPv6;
- mUsingMultinetworkPolicyTracker = other.mUsingMultinetworkPolicyTracker;
- mUsingIpReachabilityMonitor = other.mUsingIpReachabilityMonitor;
- mRequestedPreDhcpActionMs = other.mRequestedPreDhcpActionMs;
- mInitialConfig = InitialConfiguration.copy(other.mInitialConfig);
- mStaticIpConfig = other.mStaticIpConfig == null
- ? null
- : new StaticIpConfiguration(other.mStaticIpConfig);
- mApfCapabilities = other.mApfCapabilities;
- mProvisioningTimeoutMs = other.mProvisioningTimeoutMs;
- mIPv6AddrGenMode = other.mIPv6AddrGenMode;
- mNetwork = other.mNetwork;
- mDisplayName = other.mDisplayName;
- }
-
- /**
- * Create a ProvisioningConfigurationParcelable from this ProvisioningConfiguration.
- */
- public ProvisioningConfigurationParcelable toStableParcelable() {
- final ProvisioningConfigurationParcelable p = new ProvisioningConfigurationParcelable();
- p.enableIPv4 = mEnableIPv4;
- p.enableIPv6 = mEnableIPv6;
- p.usingMultinetworkPolicyTracker = mUsingMultinetworkPolicyTracker;
- p.usingIpReachabilityMonitor = mUsingIpReachabilityMonitor;
- p.requestedPreDhcpActionMs = mRequestedPreDhcpActionMs;
- p.initialConfig = mInitialConfig == null ? null : mInitialConfig.toStableParcelable();
- p.staticIpConfig = mStaticIpConfig == null
- ? null
- : new StaticIpConfiguration(mStaticIpConfig);
- p.apfCapabilities = mApfCapabilities; // ApfCapabilities is immutable
- p.provisioningTimeoutMs = mProvisioningTimeoutMs;
- p.ipv6AddrGenMode = mIPv6AddrGenMode;
- p.network = mNetwork;
- p.displayName = mDisplayName;
- return p;
- }
-
- /**
- * Create a ProvisioningConfiguration from a ProvisioningConfigurationParcelable.
- */
- public static ProvisioningConfiguration fromStableParcelable(
- @Nullable ProvisioningConfigurationParcelable p) {
- if (p == null) return null;
- final ProvisioningConfiguration config = new ProvisioningConfiguration();
- config.mEnableIPv4 = p.enableIPv4;
- config.mEnableIPv6 = p.enableIPv6;
- config.mUsingMultinetworkPolicyTracker = p.usingMultinetworkPolicyTracker;
- config.mUsingIpReachabilityMonitor = p.usingIpReachabilityMonitor;
- config.mRequestedPreDhcpActionMs = p.requestedPreDhcpActionMs;
- config.mInitialConfig = InitialConfiguration.fromStableParcelable(p.initialConfig);
- config.mStaticIpConfig = p.staticIpConfig == null
- ? null
- : new StaticIpConfiguration(p.staticIpConfig);
- config.mApfCapabilities = p.apfCapabilities; // ApfCapabilities is immutable
- config.mProvisioningTimeoutMs = p.provisioningTimeoutMs;
- config.mIPv6AddrGenMode = p.ipv6AddrGenMode;
- config.mNetwork = p.network;
- config.mDisplayName = p.displayName;
- return config;
- }
-
- @Override
- public String toString() {
- return new StringJoiner(", ", getClass().getSimpleName() + "{", "}")
- .add("mEnableIPv4: " + mEnableIPv4)
- .add("mEnableIPv6: " + mEnableIPv6)
- .add("mUsingMultinetworkPolicyTracker: " + mUsingMultinetworkPolicyTracker)
- .add("mUsingIpReachabilityMonitor: " + mUsingIpReachabilityMonitor)
- .add("mRequestedPreDhcpActionMs: " + mRequestedPreDhcpActionMs)
- .add("mInitialConfig: " + mInitialConfig)
- .add("mStaticIpConfig: " + mStaticIpConfig)
- .add("mApfCapabilities: " + mApfCapabilities)
- .add("mProvisioningTimeoutMs: " + mProvisioningTimeoutMs)
- .add("mIPv6AddrGenMode: " + mIPv6AddrGenMode)
- .add("mNetwork: " + mNetwork)
- .add("mDisplayName: " + mDisplayName)
- .toString();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof ProvisioningConfiguration)) return false;
- final ProvisioningConfiguration other = (ProvisioningConfiguration) obj;
- return mEnableIPv4 == other.mEnableIPv4
- && mEnableIPv6 == other.mEnableIPv6
- && mUsingMultinetworkPolicyTracker == other.mUsingMultinetworkPolicyTracker
- && mUsingIpReachabilityMonitor == other.mUsingIpReachabilityMonitor
- && mRequestedPreDhcpActionMs == other.mRequestedPreDhcpActionMs
- && Objects.equals(mInitialConfig, other.mInitialConfig)
- && Objects.equals(mStaticIpConfig, other.mStaticIpConfig)
- && Objects.equals(mApfCapabilities, other.mApfCapabilities)
- && mProvisioningTimeoutMs == other.mProvisioningTimeoutMs
- && mIPv6AddrGenMode == other.mIPv6AddrGenMode
- && Objects.equals(mNetwork, other.mNetwork)
- && Objects.equals(mDisplayName, other.mDisplayName);
- }
-
- public boolean isValid() {
- return (mInitialConfig == null) || mInitialConfig.isValid();
- }
-}
diff --git a/services/net/java/android/net/util/InterfaceParams.java b/services/net/java/android/net/util/InterfaceParams.java
deleted file mode 100644
index f6bb873..0000000
--- a/services/net/java/android/net/util/InterfaceParams.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * 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.util;
-
-import static com.android.internal.util.Preconditions.checkArgument;
-
-import android.net.MacAddress;
-import android.text.TextUtils;
-
-import java.net.NetworkInterface;
-import java.net.SocketException;
-
-
-/**
- * Encapsulate the interface parameters common to IpClient/IpServer components.
- *
- * Basically all java.net.NetworkInterface methods throw Exceptions. IpClient
- * and IpServer (sub)components need most or all of this information at some
- * point during their lifecycles, so pass only this simplified object around
- * which can be created once when IpClient/IpServer are told to start.
- *
- * @hide
- */
-public class InterfaceParams {
- public final String name;
- public final int index;
- public final MacAddress macAddr;
- public final int defaultMtu;
-
- // TODO: move the below to NetworkStackConstants when this class is moved to the NetworkStack.
- private static final int ETHER_MTU = 1500;
- private static final int IPV6_MIN_MTU = 1280;
-
-
- public static InterfaceParams getByName(String name) {
- final NetworkInterface netif = getNetworkInterfaceByName(name);
- if (netif == null) return null;
-
- // Not all interfaces have MAC addresses, e.g. rmnet_data0.
- final MacAddress macAddr = getMacAddress(netif);
-
- try {
- return new InterfaceParams(name, netif.getIndex(), macAddr, netif.getMTU());
- } catch (IllegalArgumentException|SocketException e) {
- return null;
- }
- }
-
- public InterfaceParams(String name, int index, MacAddress macAddr) {
- this(name, index, macAddr, ETHER_MTU);
- }
-
- public InterfaceParams(String name, int index, MacAddress macAddr, int defaultMtu) {
- checkArgument((!TextUtils.isEmpty(name)), "impossible interface name");
- checkArgument((index > 0), "invalid interface index");
- this.name = name;
- this.index = index;
- this.macAddr = (macAddr != null) ? macAddr : MacAddress.fromBytes(new byte[] {
- 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 });
- this.defaultMtu = (defaultMtu > IPV6_MIN_MTU) ? defaultMtu : IPV6_MIN_MTU;
- }
-
- @Override
- public String toString() {
- return String.format("%s/%d/%s/%d", name, index, macAddr, defaultMtu);
- }
-
- private static NetworkInterface getNetworkInterfaceByName(String name) {
- try {
- return NetworkInterface.getByName(name);
- } catch (NullPointerException|SocketException e) {
- return null;
- }
- }
-
- private static MacAddress getMacAddress(NetworkInterface netif) {
- try {
- return MacAddress.fromBytes(netif.getHardwareAddress());
- } catch (IllegalArgumentException|NullPointerException|SocketException e) {
- return null;
- }
- }
-}
diff --git a/services/net/java/android/net/util/SharedLog.java b/services/net/java/android/net/util/SharedLog.java
deleted file mode 100644
index 2cdb2b0..0000000
--- a/services/net/java/android/net/util/SharedLog.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * 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.util;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.text.TextUtils;
-import android.util.LocalLog;
-import android.util.Log;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.StringJoiner;
-
-
-/**
- * Class to centralize logging functionality for tethering.
- *
- * All access to class methods other than dump() must be on the same thread.
- *
- * TODO: this is a copy of SharedLog in the NetworkStack. Remove after Tethering is migrated.
- * @hide
- */
-public class SharedLog {
- private static final int DEFAULT_MAX_RECORDS = 500;
- private static final String COMPONENT_DELIMITER = ".";
-
- private enum Category {
- NONE,
- ERROR,
- MARK,
- WARN,
- };
-
- private final LocalLog mLocalLog;
- // The tag to use for output to the system log. This is not output to the
- // LocalLog because that would be redundant.
- private final String mTag;
- // The component (or subcomponent) of a system that is sharing this log.
- // This can grow in depth if components call forSubComponent() to obtain
- // their SharedLog instance. The tag is not included in the component for
- // brevity.
- private final String mComponent;
-
- public SharedLog(String tag) {
- this(DEFAULT_MAX_RECORDS, tag);
- }
-
- public SharedLog(int maxRecords, String tag) {
- this(new LocalLog(maxRecords), tag, tag);
- }
-
- private SharedLog(LocalLog localLog, String tag, String component) {
- mLocalLog = localLog;
- mTag = tag;
- mComponent = component;
- }
-
- public String getTag() {
- return mTag;
- }
-
- /**
- * Create a SharedLog based on this log with an additional component prefix on each logged line.
- */
- public SharedLog forSubComponent(String component) {
- if (!isRootLogInstance()) {
- component = mComponent + COMPONENT_DELIMITER + component;
- }
- return new SharedLog(mLocalLog, mTag, component);
- }
-
- /**
- * Dump the contents of this log.
- *
- * <p>This method may be called on any thread.
- */
- public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
- mLocalLog.readOnlyLocalLog().dump(fd, writer, args);
- }
-
- //////
- // Methods that both log an entry and emit it to the system log.
- //////
-
- /**
- * Log an error due to an exception. This does not include the exception stacktrace.
- *
- * <p>The log entry will be also added to the system log.
- * @see #e(String, Throwable)
- */
- public void e(Exception e) {
- Log.e(mTag, record(Category.ERROR, e.toString()));
- }
-
- /**
- * Log an error message.
- *
- * <p>The log entry will be also added to the system log.
- */
- public void e(String msg) {
- Log.e(mTag, record(Category.ERROR, msg));
- }
-
- /**
- * Log an error due to an exception, with the exception stacktrace if provided.
- *
- * <p>The error and exception message appear in the shared log, but the stacktrace is only
- * logged in general log output (logcat). The log entry will be also added to the system log.
- */
- public void e(@NonNull String msg, @Nullable Throwable exception) {
- if (exception == null) {
- e(msg);
- return;
- }
- Log.e(mTag, record(Category.ERROR, msg + ": " + exception.getMessage()), exception);
- }
-
- /**
- * Log an informational message.
- *
- * <p>The log entry will be also added to the system log.
- */
- public void i(String msg) {
- Log.i(mTag, record(Category.NONE, msg));
- }
-
- /**
- * Log a warning message.
- *
- * <p>The log entry will be also added to the system log.
- */
- public void w(String msg) {
- Log.w(mTag, record(Category.WARN, msg));
- }
-
- //////
- // Methods that only log an entry (and do NOT emit to the system log).
- //////
-
- /**
- * Log a general message to be only included in the in-memory log.
- *
- * <p>The log entry will *not* be added to the system log.
- */
- public void log(String msg) {
- record(Category.NONE, msg);
- }
-
- /**
- * Log a general, formatted message to be only included in the in-memory log.
- *
- * <p>The log entry will *not* be added to the system log.
- * @see String#format(String, Object...)
- */
- public void logf(String fmt, Object... args) {
- log(String.format(fmt, args));
- }
-
- /**
- * Log a message with MARK level.
- *
- * <p>The log entry will *not* be added to the system log.
- */
- public void mark(String msg) {
- record(Category.MARK, msg);
- }
-
- private String record(Category category, String msg) {
- final String entry = logLine(category, msg);
- mLocalLog.log(entry);
- return entry;
- }
-
- private String logLine(Category category, String msg) {
- final StringJoiner sj = new StringJoiner(" ");
- if (!isRootLogInstance()) sj.add("[" + mComponent + "]");
- if (category != Category.NONE) sj.add(category.toString());
- return sj.add(msg).toString();
- }
-
- // Check whether this SharedLog instance is nominally the top level in
- // a potential hierarchy of shared logs (the root of a tree),
- // or is a subcomponent within the hierarchy.
- private boolean isRootLogInstance() {
- return TextUtils.isEmpty(mComponent) || mComponent.equals(mTag);
- }
-}
diff --git a/services/tests/mockingservicestests/Android.bp b/services/tests/mockingservicestests/Android.bp
index 8699669..96fedf9 100644
--- a/services/tests/mockingservicestests/Android.bp
+++ b/services/tests/mockingservicestests/Android.bp
@@ -20,7 +20,7 @@
static_libs: [
"services.core",
"services.net",
- "jobscheduler-service",
+ "service-jobscheduler",
"androidx.test.runner",
"mockito-target-extended-minus-junit4",
"platform-test-annotations",
diff --git a/services/tests/servicestests/Android.bp b/services/tests/servicestests/Android.bp
index 52fb69e..0be5fe0 100644
--- a/services/tests/servicestests/Android.bp
+++ b/services/tests/servicestests/Android.bp
@@ -41,7 +41,7 @@
"hamcrest-library",
"servicestests-utils",
"xml-writer-device-lib",
- "jobscheduler-service",
+ "service-jobscheduler",
],
aidl: {
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index b9e1d4b..212931b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -290,10 +290,12 @@
public void testFixedScreenLayoutSizeBits() {
setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
final int fixedScreenLayout = Configuration.SCREENLAYOUT_LONG_NO
- | Configuration.SCREENLAYOUT_SIZE_NORMAL;
+ | Configuration.SCREENLAYOUT_SIZE_NORMAL
+ | Configuration.SCREENLAYOUT_COMPAT_NEEDED;
final int layoutMask = Configuration.SCREENLAYOUT_LONG_MASK
| Configuration.SCREENLAYOUT_SIZE_MASK
- | Configuration.SCREENLAYOUT_LAYOUTDIR_MASK;
+ | Configuration.SCREENLAYOUT_LAYOUTDIR_MASK
+ | Configuration.SCREENLAYOUT_COMPAT_NEEDED;
Configuration c = new Configuration(mTask.getRequestedOverrideConfiguration());
c.screenLayout = fixedScreenLayout | Configuration.SCREENLAYOUT_LAYOUTDIR_LTR;
mTask.onRequestedOverrideConfigurationChanged(c);
diff --git a/telephony/java/android/provider/Telephony.java b/telephony/java/android/provider/Telephony.java
index add0316..7ed37c4 100644
--- a/telephony/java/android/provider/Telephony.java
+++ b/telephony/java/android/provider/Telephony.java
@@ -25,6 +25,7 @@
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.ChangeId;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
@@ -4033,6 +4034,16 @@
@Retention(RetentionPolicy.SOURCE)
public @interface Skip464XlatStatus {}
+ /**
+ * Compat framework change ID for the APN db read permission change.
+ *
+ * In API level 30 and beyond, accessing the APN database will require the
+ * {@link android.Manifest.permission#WRITE_APN_SETTINGS} permission. This change ID tracks
+ * apps that are affected because they don't hold this permission.
+ * @hide
+ */
+ @ChangeId
+ public static final long APN_READING_PERMISSION_CHANGE_ID = 124107808L;
}
/**
diff --git a/telephony/java/com/android/internal/telephony/SmsMessageBase.java b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
index f0687b4..a3efb75 100644
--- a/telephony/java/com/android/internal/telephony/SmsMessageBase.java
+++ b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
@@ -20,7 +20,6 @@
import android.os.Build;
import android.provider.Telephony;
import android.telephony.SmsMessage;
-import android.text.Emoji;
import com.android.internal.telephony.GsmAlphabet.TextEncodingDetails;
@@ -403,9 +402,9 @@
if (!breakIterator.isBoundary(nextPos)) {
int breakPos = breakIterator.preceding(nextPos);
while (breakPos + 4 <= nextPos
- && Emoji.isRegionalIndicatorSymbol(
+ && isRegionalIndicatorSymbol(
Character.codePointAt(msgBody, breakPos))
- && Emoji.isRegionalIndicatorSymbol(
+ && isRegionalIndicatorSymbol(
Character.codePointAt(msgBody, breakPos + 2))) {
// skip forward over flags (pairs of Regional Indicator Symbol)
breakPos += 4;
@@ -421,6 +420,11 @@
return nextPos;
}
+ private static boolean isRegionalIndicatorSymbol(int codePoint) {
+ /** Based on http://unicode.org/Public/emoji/3.0/emoji-sequences.txt */
+ return 0x1F1E6 <= codePoint && codePoint <= 0x1F1FF;
+ }
+
/**
* Calculate the TextEncodingDetails of a message encoded in Unicode.
*/
diff --git a/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml b/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml
index 7291dc7..aec9f77 100644
--- a/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml
+++ b/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml
@@ -28,8 +28,6 @@
<uses-permission android:name="android.permission.SET_TIME" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
- <uses-permission android:name="android.permission.WRITE_DEVICE_CONFIG" />
- <uses-permission android:name="android.permission.READ_DEVICE_CONFIG" />
<application>
<uses-library android:name="android.test.runner" />
diff --git a/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java b/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java
index 4cd56c3..7d826f7 100644
--- a/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java
+++ b/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java
@@ -22,7 +22,6 @@
import android.os.ParcelFileDescriptor;
import android.os.SystemProperties;
import android.os.storage.StorageManager;
-import android.provider.DeviceConfig;
import android.util.Log;
import androidx.test.InstrumentationRegistry;
@@ -31,9 +30,7 @@
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -55,13 +52,6 @@
* 3. Under low storage conditions and package is recently used, check
* that dexopt upgrades test app to $(getprop pm.dexopt.bg-dexopt).
*
- * When downgrade feature is on (downgrade_unused_apps_enabled flag is set to true):
- * 4 On low storage, check that the inactive packages are downgraded.
- * 5. On low storage, check that used packages are upgraded.
- * 6. On storage completely full, dexopt fails.
- * 7. Not on low storage, unused packages are upgraded.
- * 8. Low storage, unused app is downgraded. When app is used again, app is upgraded.
- *
* Each test case runs "cmd package bg-dexopt-job com.android.frameworks.bgdexopttest".
*
* The setup for these tests make sure this package has been configured to have been recently used
@@ -69,10 +59,6 @@
* recently used, it sets the time forward more than
* `getprop pm.dexopt.downgrade_after_inactive_days` days.
*
- * For some of the tests, the DeviceConfig flags inactive_app_threshold_days and
- * downgrade_unused_apps_enabled are set. These turn on/off the downgrade unused apps feature for
- * all devices and set the time threshold for unused apps.
- *
* For tests that require low storage, the phone is filled up.
*
* Run with "atest BackgroundDexOptServiceIntegrationTests".
@@ -94,14 +80,10 @@
"pm.dexopt.downgrade_after_inactive_days", 0);
// Needs to be between 1.0 and 2.0.
private static final double LOW_STORAGE_MULTIPLIER = 1.5;
- private static final int DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS = 15;
// The file used to fill up storage.
private File mBigFile;
- @Rule
- public ExpectedException mExpectedException = ExpectedException.none();
-
// Remember start time.
@BeforeClass
public static void setUpAll() {
@@ -214,27 +196,11 @@
logSpaceRemaining();
}
- private void fillUpStorageCompletely() throws IOException {
- fillUpStorage((getStorageLowBytes()));
- }
-
// Fill up storage so that device is in low storage condition.
private void fillUpToLowStorage() throws IOException {
fillUpStorage((long) (getStorageLowBytes() * LOW_STORAGE_MULTIPLIER));
}
- private void setInactivePackageThreshold(int threshold) {
- DeviceConfig.setProperty(
- DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE,
- "inactive_app_threshold_days", Integer.toString(threshold), false);
- }
-
- private void enableDowngradeFeature(boolean enabled) {
- DeviceConfig.setProperty(
- DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE,
- "downgrade_unused_apps_enabled", Boolean.toString(enabled), false);
- }
-
// TODO(aeubanks): figure out how to get scheduled bg-dexopt to run
private static void runBackgroundDexOpt() throws IOException {
String result = runShellCommand("cmd package bg-dexopt-job " + PACKAGE_NAME);
@@ -278,7 +244,7 @@
// Test that background dexopt under normal conditions succeeds.
@Test
- public void testBackgroundDexOpt_normalConditions_dexOptSucceeds() throws IOException {
+ public void testBackgroundDexOpt() throws IOException {
// Set filter to quicken.
compilePackageWithFilter(PACKAGE_NAME, "verify");
Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));
@@ -291,16 +257,17 @@
// Test that background dexopt under low storage conditions upgrades used packages.
@Test
- public void testBackgroundDexOpt_lowStorage_usedPkgsUpgraded() throws IOException {
+ public void testBackgroundDexOptDowngradeSkipRecentlyUsedPackage() throws IOException {
// Should be less than DOWNGRADE_AFTER_DAYS.
long deltaDays = DOWNGRADE_AFTER_DAYS - 1;
try {
- enableDowngradeFeature(false);
// Set time to future.
setTimeFutureDays(deltaDays);
+
// Set filter to quicken.
compilePackageWithFilter(PACKAGE_NAME, "quicken");
Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME));
+
// Fill up storage to trigger low storage threshold.
fillUpToLowStorage();
@@ -315,20 +282,18 @@
}
// Test that background dexopt under low storage conditions downgrades unused packages.
- // This happens if the system property pm.dexopt.downgrade_after_inactive_days is set
- // (e.g. on Android Go devices).
@Test
- public void testBackgroundDexOpt_lowStorage_unusedPkgsDowngraded()
- throws IOException {
+ public void testBackgroundDexOptDowngradeSuccessful() throws IOException {
// Should be more than DOWNGRADE_AFTER_DAYS.
long deltaDays = DOWNGRADE_AFTER_DAYS + 1;
try {
- enableDowngradeFeature(false);
// Set time to future.
setTimeFutureDays(deltaDays);
+
// Set filter to quicken.
compilePackageWithFilter(PACKAGE_NAME, "quicken");
Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME));
+
// Fill up storage to trigger low storage threshold.
fillUpToLowStorage();
@@ -342,134 +307,4 @@
}
}
- // Test that the background dexopt downgrades inactive packages when the downgrade feature is
- // enabled.
- @Test
- public void testBackgroundDexOpt_downgradeFeatureEnabled_lowStorage_inactivePkgsDowngraded()
- throws IOException {
- // Should be more than DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS.
- long deltaDays = DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS + 1;
- try {
- enableDowngradeFeature(true);
- setInactivePackageThreshold(DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS);
- // Set time to future.
- setTimeFutureDays(deltaDays);
- // Set filter to quicken.
- compilePackageWithFilter(PACKAGE_NAME, "quicken");
- Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME));
- // Fill up storage to trigger low storage threshold.
- fillUpToLowStorage();
-
- runBackgroundDexOpt();
-
- // Verify that downgrade is successful.
- Assert.assertEquals(DOWNGRADE_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
- } finally {
- // Reset time.
- setTimeFutureDays(-deltaDays);
- }
- }
-
- // Test that the background dexopt upgrades used packages when the downgrade feature is enabled.
- // This test doesn't fill the device storage completely, but to a multiplier of the low storage
- // threshold and this is why apps can still be optimized.
- @Test
- public void testBackgroundDexOpt_downgradeFeatureEnabled_lowStorage_usedPkgsUpgraded()
- throws IOException {
- enableDowngradeFeature(true);
- // Set filter to quicken.
- compilePackageWithFilter(PACKAGE_NAME, "quicken");
- Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME));
- // Fill up storage to trigger low storage threshold.
- fillUpToLowStorage();
-
- runBackgroundDexOpt();
-
- /// Verify that bg-dexopt is successful in upgrading the used packages.
- Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
- }
-
- // Test that the background dexopt fails and doesn't change the compilation filter of used
- // packages when the downgrade feature is enabled and the storage is filled up completely.
- // The bg-dexopt shouldn't optimise nor downgrade these packages.
- @Test
- public void testBackgroundDexOpt_downgradeFeatureEnabled_fillUpStorageCompletely_dexOptFails()
- throws IOException {
- enableDowngradeFeature(true);
- String previousCompilerFilter = getCompilerFilter(PACKAGE_NAME);
-
- // Fill up storage completely, without using a multiplier for the low storage threshold.
- fillUpStorageCompletely();
-
- // When the bg dexopt runs with the storage filled up completely, it will fail.
- mExpectedException.expect(IllegalStateException.class);
- runBackgroundDexOpt();
-
- /// Verify that bg-dexopt doesn't change the compilation filter of used apps.
- Assert.assertEquals(previousCompilerFilter, getCompilerFilter(PACKAGE_NAME));
- }
-
- // Test that the background dexopt upgrades the unused packages when the downgrade feature is
- // on if the device is not low on storage.
- @Test
- public void testBackgroundDexOpt_downgradeFeatureEnabled_notLowStorage_unusedPkgsUpgraded()
- throws IOException {
- // Should be more than DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS.
- long deltaDays = DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS + 1;
- try {
- enableDowngradeFeature(true);
- setInactivePackageThreshold(DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS);
- // Set time to future.
- setTimeFutureDays(deltaDays);
- // Set filter to quicken.
- compilePackageWithFilter(PACKAGE_NAME, "quicken");
- Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME));
-
- runBackgroundDexOpt();
-
- // Verify that bg-dexopt is successful in upgrading the unused packages when the device
- // is not low on storage.
- Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
- } finally {
- // Reset time.
- setTimeFutureDays(-deltaDays);
- }
- }
-
- // Test that when an unused package (which was downgraded) is used again, it's re-optimized when
- // bg-dexopt runs again.
- @Test
- public void testBackgroundDexOpt_downgradeFeatureEnabled_downgradedPkgsUpgradedAfterUse()
- throws IOException {
- // Should be more than DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS.
- long deltaDays = DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS + 1;
- try {
- enableDowngradeFeature(true);
- setInactivePackageThreshold(DOWNGRADE_FEATURE_PKG_INACTIVE_AFTER_DAYS);
- // Set time to future.
- setTimeFutureDays(deltaDays);
- // Fill up storage to trigger low storage threshold.
- fillUpToLowStorage();
- // Set filter to quicken.
- compilePackageWithFilter(PACKAGE_NAME, "quicken");
- Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME));
-
- runBackgroundDexOpt();
-
- // Verify that downgrade is successful.
- Assert.assertEquals(DOWNGRADE_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
-
- // Reset time.
- setTimeFutureDays(-deltaDays);
- deltaDays = 0;
- runBackgroundDexOpt();
-
- // Verify that bg-dexopt is successful in upgrading the unused packages that were used
- // again.
- Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
- } finally {
- // Reset time.
- setTimeFutureDays(-deltaDays);
- }
- }
}
diff --git a/tests/JobSchedulerPerfTests/Android.bp b/tests/JobSchedulerPerfTests/Android.bp
index c51b811..2ae8c33 100644
--- a/tests/JobSchedulerPerfTests/Android.bp
+++ b/tests/JobSchedulerPerfTests/Android.bp
@@ -19,7 +19,7 @@
"androidx.test.rules",
"apct-perftests-utils",
"services",
- "jobscheduler-service",
+ "service-jobscheduler",
],
platform_apis: true,
certificate: "platform",
diff --git a/tests/net/java/android/net/ip/InterfaceControllerTest.java b/tests/net/java/android/net/ip/InterfaceControllerTest.java
deleted file mode 100644
index 7a56b3a..0000000
--- a/tests/net/java/android/net/ip/InterfaceControllerTest.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2019 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.ip;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import android.net.INetd;
-import android.net.InetAddresses;
-import android.net.InterfaceConfigurationParcel;
-import android.net.LinkAddress;
-import android.net.util.SharedLog;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class InterfaceControllerTest {
- private static final String TEST_IFACE = "testif";
- private static final String TEST_IPV4_ADDR = "192.168.123.28";
- private static final int TEST_PREFIXLENGTH = 31;
-
- @Mock private INetd mNetd;
- @Mock private SharedLog mLog;
- @Captor private ArgumentCaptor<InterfaceConfigurationParcel> mConfigCaptor;
-
- private InterfaceController mController;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- mController = new InterfaceController(TEST_IFACE, mNetd, mLog);
-
- doNothing().when(mNetd).interfaceSetCfg(mConfigCaptor.capture());
- }
-
- @Test
- public void testSetIPv4Address() throws Exception {
- mController.setIPv4Address(
- new LinkAddress(InetAddresses.parseNumericAddress(TEST_IPV4_ADDR),
- TEST_PREFIXLENGTH));
- verify(mNetd, times(1)).interfaceSetCfg(any());
- final InterfaceConfigurationParcel parcel = mConfigCaptor.getValue();
- assertEquals(TEST_IFACE, parcel.ifName);
- assertEquals(TEST_IPV4_ADDR, parcel.ipv4Addr);
- assertEquals(TEST_PREFIXLENGTH, parcel.prefixLength);
- assertEquals("", parcel.hwAddr);
- assertArrayEquals(new String[0], parcel.flags);
- }
-
- @Test
- public void testClearIPv4Address() throws Exception {
- mController.clearIPv4Address();
- verify(mNetd, times(1)).interfaceSetCfg(any());
- final InterfaceConfigurationParcel parcel = mConfigCaptor.getValue();
- assertEquals(TEST_IFACE, parcel.ifName);
- assertEquals("0.0.0.0", parcel.ipv4Addr);
- assertEquals(0, parcel.prefixLength);
- assertEquals("", parcel.hwAddr);
- assertArrayEquals(new String[0], parcel.flags);
- }
-}
diff --git a/tests/net/java/android/net/netlink/ConntrackMessageTest.java b/tests/net/java/android/net/netlink/ConntrackMessageTest.java
deleted file mode 100644
index 5c86757..0000000
--- a/tests/net/java/android/net/netlink/ConntrackMessageTest.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * 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.netlink;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assume.assumeTrue;
-
-import android.system.OsConstants;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import libcore.util.HexEncoding;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.nio.ByteOrder;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class ConntrackMessageTest {
- private static final boolean USING_LE = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN);
-
- // Example 1: TCP (192.168.43.209, 44333) -> (23.211.13.26, 443)
- public static final String CT_V4UPDATE_TCP_HEX =
- // struct nlmsghdr
- "50000000" + // length = 80
- "0001" + // type = (1 << 8) | 0
- "0501" + // flags
- "01000000" + // seqno = 1
- "00000000" + // pid = 0
- // struct nfgenmsg
- "02" + // nfgen_family = AF_INET
- "00" + // version = NFNETLINK_V0
- "0000" + // res_id
- // struct nlattr
- "3400" + // nla_len = 52
- "0180" + // nla_type = nested CTA_TUPLE_ORIG
- // struct nlattr
- "1400" + // nla_len = 20
- "0180" + // nla_type = nested CTA_TUPLE_IP
- "0800 0100 C0A82BD1" + // nla_type=CTA_IP_V4_SRC, ip=192.168.43.209
- "0800 0200 17D30D1A" + // nla_type=CTA_IP_V4_DST, ip=23.211.13.26
- // struct nlattr
- "1C00" + // nla_len = 28
- "0280" + // nla_type = nested CTA_TUPLE_PROTO
- "0500 0100 06 000000" + // nla_type=CTA_PROTO_NUM, proto=6
- "0600 0200 AD2D 0000" + // nla_type=CTA_PROTO_SRC_PORT, port=44333 (big endian)
- "0600 0300 01BB 0000" + // nla_type=CTA_PROTO_DST_PORT, port=443 (big endian)
- // struct nlattr
- "0800" + // nla_len = 8
- "0700" + // nla_type = CTA_TIMEOUT
- "00069780"; // nla_value = 432000 (big endian)
- public static final byte[] CT_V4UPDATE_TCP_BYTES =
- HexEncoding.decode(CT_V4UPDATE_TCP_HEX.replaceAll(" ", "").toCharArray(), false);
-
- // Example 2: UDP (100.96.167.146, 37069) -> (216.58.197.10, 443)
- public static final String CT_V4UPDATE_UDP_HEX =
- // struct nlmsghdr
- "50000000" + // length = 80
- "0001" + // type = (1 << 8) | 0
- "0501" + // flags
- "01000000" + // seqno = 1
- "00000000" + // pid = 0
- // struct nfgenmsg
- "02" + // nfgen_family = AF_INET
- "00" + // version = NFNETLINK_V0
- "0000" + // res_id
- // struct nlattr
- "3400" + // nla_len = 52
- "0180" + // nla_type = nested CTA_TUPLE_ORIG
- // struct nlattr
- "1400" + // nla_len = 20
- "0180" + // nla_type = nested CTA_TUPLE_IP
- "0800 0100 6460A792" + // nla_type=CTA_IP_V4_SRC, ip=100.96.167.146
- "0800 0200 D83AC50A" + // nla_type=CTA_IP_V4_DST, ip=216.58.197.10
- // struct nlattr
- "1C00" + // nla_len = 28
- "0280" + // nla_type = nested CTA_TUPLE_PROTO
- "0500 0100 11 000000" + // nla_type=CTA_PROTO_NUM, proto=17
- "0600 0200 90CD 0000" + // nla_type=CTA_PROTO_SRC_PORT, port=37069 (big endian)
- "0600 0300 01BB 0000" + // nla_type=CTA_PROTO_DST_PORT, port=443 (big endian)
- // struct nlattr
- "0800" + // nla_len = 8
- "0700" + // nla_type = CTA_TIMEOUT
- "000000B4"; // nla_value = 180 (big endian)
- public static final byte[] CT_V4UPDATE_UDP_BYTES =
- HexEncoding.decode(CT_V4UPDATE_UDP_HEX.replaceAll(" ", "").toCharArray(), false);
-
- @Test
- public void testConntrackIPv4TcpTimeoutUpdate() throws Exception {
- assumeTrue(USING_LE);
-
- final byte[] tcp = ConntrackMessage.newIPv4TimeoutUpdateRequest(
- OsConstants.IPPROTO_TCP,
- (Inet4Address) InetAddress.getByName("192.168.43.209"), 44333,
- (Inet4Address) InetAddress.getByName("23.211.13.26"), 443,
- 432000);
- assertArrayEquals(CT_V4UPDATE_TCP_BYTES, tcp);
- }
-
- @Test
- public void testConntrackIPv4UdpTimeoutUpdate() throws Exception {
- assumeTrue(USING_LE);
-
- final byte[] udp = ConntrackMessage.newIPv4TimeoutUpdateRequest(
- OsConstants.IPPROTO_UDP,
- (Inet4Address) InetAddress.getByName("100.96.167.146"), 37069,
- (Inet4Address) InetAddress.getByName("216.58.197.10"), 443,
- 180);
- assertArrayEquals(CT_V4UPDATE_UDP_BYTES, udp);
- }
-}
diff --git a/tests/net/java/android/net/netlink/InetDiagSocketTest.java b/tests/net/java/android/net/netlink/InetDiagSocketTest.java
deleted file mode 100644
index 84c5784..0000000
--- a/tests/net/java/android/net/netlink/InetDiagSocketTest.java
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright (C) 2018 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.netlink;
-
-import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-import static android.system.OsConstants.IPPROTO_TCP;
-import static android.system.OsConstants.IPPROTO_UDP;
-import static android.system.OsConstants.SOCK_DGRAM;
-import static android.system.OsConstants.SOCK_STREAM;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import android.app.Instrumentation;
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.netlink.StructNlMsgHdr;
-import android.os.Process;
-import android.system.Os;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import libcore.util.HexEncoding;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.FileDescriptor;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class InetDiagSocketTest {
- private final String TAG = "InetDiagSocketTest";
- private ConnectivityManager mCm;
- private Context mContext;
- private final static int SOCKET_TIMEOUT_MS = 100;
-
- @Before
- public void setUp() throws Exception {
- Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
- mContext = instrumentation.getTargetContext();
- mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- }
-
- private class Connection {
- public int socketDomain;
- public int socketType;
- public InetAddress localAddress;
- public InetAddress remoteAddress;
- public InetAddress localhostAddress;
- public InetSocketAddress local;
- public InetSocketAddress remote;
- public int protocol;
- public FileDescriptor localFd;
- public FileDescriptor remoteFd;
-
- public FileDescriptor createSocket() throws Exception {
- return Os.socket(socketDomain, socketType, protocol);
- }
-
- public Connection(String to, String from) throws Exception {
- remoteAddress = InetAddress.getByName(to);
- if (from != null) {
- localAddress = InetAddress.getByName(from);
- } else {
- localAddress = (remoteAddress instanceof Inet4Address) ?
- Inet4Address.getByName("localhost") : Inet6Address.getByName("::");
- }
- if ((localAddress instanceof Inet4Address) && (remoteAddress instanceof Inet4Address)) {
- socketDomain = AF_INET;
- localhostAddress = Inet4Address.getByName("localhost");
- } else {
- socketDomain = AF_INET6;
- localhostAddress = Inet6Address.getByName("::");
- }
- }
-
- public void close() throws Exception {
- Os.close(localFd);
- }
- }
-
- private class TcpConnection extends Connection {
- public TcpConnection(String to, String from) throws Exception {
- super(to, from);
- protocol = IPPROTO_TCP;
- socketType = SOCK_STREAM;
-
- remoteFd = createSocket();
- Os.bind(remoteFd, remoteAddress, 0);
- Os.listen(remoteFd, 10);
- int remotePort = ((InetSocketAddress) Os.getsockname(remoteFd)).getPort();
-
- localFd = createSocket();
- Os.bind(localFd, localAddress, 0);
- Os.connect(localFd, remoteAddress, remotePort);
-
- local = (InetSocketAddress) Os.getsockname(localFd);
- remote = (InetSocketAddress) Os.getpeername(localFd);
- }
-
- public void close() throws Exception {
- super.close();
- Os.close(remoteFd);
- }
- }
- private class UdpConnection extends Connection {
- public UdpConnection(String to, String from) throws Exception {
- super(to, from);
- protocol = IPPROTO_UDP;
- socketType = SOCK_DGRAM;
-
- remoteFd = null;
- localFd = createSocket();
- Os.bind(localFd, localAddress, 0);
-
- Os.connect(localFd, remoteAddress, 7);
- local = (InetSocketAddress) Os.getsockname(localFd);
- remote = new InetSocketAddress(remoteAddress, 7);
- }
- }
-
- private void checkConnectionOwnerUid(int protocol, InetSocketAddress local,
- InetSocketAddress remote, boolean expectSuccess) {
- final int uid = mCm.getConnectionOwnerUid(protocol, local, remote);
-
- if (expectSuccess) {
- assertEquals(Process.myUid(), uid);
- } else {
- assertNotEquals(Process.myUid(), uid);
- }
- }
-
- private int findLikelyFreeUdpPort(UdpConnection conn) throws Exception {
- UdpConnection udp = new UdpConnection(conn.remoteAddress.getHostAddress(),
- conn.localAddress.getHostAddress());
- final int localPort = udp.local.getPort();
- udp.close();
- return localPort;
- }
-
- /**
- * Create a test connection for UDP and TCP sockets and verify that this
- * {protocol, local, remote} socket result in receiving a valid UID.
- */
- public void checkGetConnectionOwnerUid(String to, String from) throws Exception {
- TcpConnection tcp = new TcpConnection(to, from);
- checkConnectionOwnerUid(tcp.protocol, tcp.local, tcp.remote, true);
- checkConnectionOwnerUid(IPPROTO_UDP, tcp.local, tcp.remote, false);
- checkConnectionOwnerUid(tcp.protocol, new InetSocketAddress(0), tcp.remote, false);
- checkConnectionOwnerUid(tcp.protocol, tcp.local, new InetSocketAddress(0), false);
- tcp.close();
-
- UdpConnection udp = new UdpConnection(to,from);
- checkConnectionOwnerUid(udp.protocol, udp.local, udp.remote, true);
- checkConnectionOwnerUid(IPPROTO_TCP, udp.local, udp.remote, false);
- checkConnectionOwnerUid(udp.protocol, new InetSocketAddress(findLikelyFreeUdpPort(udp)),
- udp.remote, false);
- udp.close();
- }
-
- @Test
- public void testGetConnectionOwnerUid() throws Exception {
- checkGetConnectionOwnerUid("::", null);
- checkGetConnectionOwnerUid("::", "::");
- checkGetConnectionOwnerUid("0.0.0.0", null);
- checkGetConnectionOwnerUid("0.0.0.0", "0.0.0.0");
- checkGetConnectionOwnerUid("127.0.0.1", null);
- checkGetConnectionOwnerUid("127.0.0.1", "127.0.0.2");
- checkGetConnectionOwnerUid("::1", null);
- checkGetConnectionOwnerUid("::1", "::1");
- }
-
- /* Verify fix for b/141603906 */
- @Test
- public void testB141603906() throws Exception {
- final InetSocketAddress src = new InetSocketAddress(0);
- final InetSocketAddress dst = new InetSocketAddress(0);
- final int numThreads = 8;
- final int numSockets = 5000;
- final Thread[] threads = new Thread[numThreads];
-
- for (int i = 0; i < numThreads; i++) {
- threads[i] = new Thread(() -> {
- for (int j = 0; j < numSockets; j++) {
- mCm.getConnectionOwnerUid(IPPROTO_TCP, src, dst);
- }
- });
- }
-
- for (Thread thread : threads) {
- thread.start();
- }
-
- for (Thread thread : threads) {
- thread.join();
- }
- }
-
- // Hexadecimal representation of InetDiagReqV2 request.
- private static final String INET_DIAG_REQ_V2_UDP_INET4_HEX =
- // struct nlmsghdr
- "48000000" + // length = 72
- "1400" + // type = SOCK_DIAG_BY_FAMILY
- "0103" + // flags = NLM_F_REQUEST | NLM_F_DUMP
- "00000000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct inet_diag_req_v2
- "02" + // family = AF_INET
- "11" + // protcol = IPPROTO_UDP
- "00" + // idiag_ext
- "00" + // pad
- "ffffffff" + // idiag_states
- // inet_diag_sockid
- "a5de" + // idiag_sport = 42462
- "b971" + // idiag_dport = 47473
- "0a006402000000000000000000000000" + // idiag_src = 10.0.100.2
- "08080808000000000000000000000000" + // idiag_dst = 8.8.8.8
- "00000000" + // idiag_if
- "ffffffffffffffff"; // idiag_cookie = INET_DIAG_NOCOOKIE
- private static final byte[] INET_DIAG_REQ_V2_UDP_INET4_BYTES =
- HexEncoding.decode(INET_DIAG_REQ_V2_UDP_INET4_HEX.toCharArray(), false);
-
- @Test
- public void testInetDiagReqV2UdpInet4() throws Exception {
- InetSocketAddress local = new InetSocketAddress(InetAddress.getByName("10.0.100.2"),
- 42462);
- InetSocketAddress remote = new InetSocketAddress(InetAddress.getByName("8.8.8.8"),
- 47473);
- final byte[] msg = InetDiagMessage.InetDiagReqV2(IPPROTO_UDP, local, remote, AF_INET,
- (short) (NLM_F_REQUEST | NLM_F_DUMP));
- assertArrayEquals(INET_DIAG_REQ_V2_UDP_INET4_BYTES, msg);
- }
-
- // Hexadecimal representation of InetDiagReqV2 request.
- private static final String INET_DIAG_REQ_V2_TCP_INET6_HEX =
- // struct nlmsghdr
- "48000000" + // length = 72
- "1400" + // type = SOCK_DIAG_BY_FAMILY
- "0100" + // flags = NLM_F_REQUEST
- "00000000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct inet_diag_req_v2
- "0a" + // family = AF_INET6
- "06" + // protcol = IPPROTO_TCP
- "00" + // idiag_ext
- "00" + // pad
- "ffffffff" + // idiag_states
- // inet_diag_sockid
- "a5de" + // idiag_sport = 42462
- "b971" + // idiag_dport = 47473
- "fe8000000000000086c9b2fffe6aed4b" + // idiag_src = fe80::86c9:b2ff:fe6a:ed4b
- "08080808000000000000000000000000" + // idiag_dst = 8.8.8.8
- "00000000" + // idiag_if
- "ffffffffffffffff"; // idiag_cookie = INET_DIAG_NOCOOKIE
- private static final byte[] INET_DIAG_REQ_V2_TCP_INET6_BYTES =
- HexEncoding.decode(INET_DIAG_REQ_V2_TCP_INET6_HEX.toCharArray(), false);
-
- @Test
- public void testInetDiagReqV2TcpInet6() throws Exception {
- InetSocketAddress local = new InetSocketAddress(
- InetAddress.getByName("fe80::86c9:b2ff:fe6a:ed4b"), 42462);
- InetSocketAddress remote = new InetSocketAddress(InetAddress.getByName("8.8.8.8"),
- 47473);
- byte[] msg = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, local, remote, AF_INET6,
- NLM_F_REQUEST);
-
- assertArrayEquals(INET_DIAG_REQ_V2_TCP_INET6_BYTES, msg);
- }
-
- // Hexadecimal representation of InetDiagReqV2 request with extension, INET_DIAG_INFO.
- private static final String INET_DIAG_REQ_V2_TCP_INET_INET_DIAG_HEX =
- // struct nlmsghdr
- "48000000" + // length = 72
- "1400" + // type = SOCK_DIAG_BY_FAMILY
- "0100" + // flags = NLM_F_REQUEST
- "00000000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct inet_diag_req_v2
- "02" + // family = AF_INET
- "06" + // protcol = IPPROTO_TCP
- "02" + // idiag_ext = INET_DIAG_INFO
- "00" + // pad
- "ffffffff" + // idiag_states
- // inet_diag_sockid
- "3039" + // idiag_sport = 12345
- "d431" + // idiag_dport = 54321
- "01020304000000000000000000000000" + // idiag_src = 1.2.3.4
- "08080404000000000000000000000000" + // idiag_dst = 8.8.4.4
- "00000000" + // idiag_if
- "ffffffffffffffff"; // idiag_cookie = INET_DIAG_NOCOOKIE
-
- private static final byte[] INET_DIAG_REQ_V2_TCP_INET_INET_DIAG_BYTES =
- HexEncoding.decode(INET_DIAG_REQ_V2_TCP_INET_INET_DIAG_HEX.toCharArray(), false);
- private static final int TCP_ALL_STATES = 0xffffffff;
- @Test
- public void testInetDiagReqV2TcpInetWithExt() throws Exception {
- InetSocketAddress local = new InetSocketAddress(
- InetAddress.getByName("1.2.3.4"), 12345);
- InetSocketAddress remote = new InetSocketAddress(InetAddress.getByName("8.8.4.4"),
- 54321);
- byte[] msg = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, local, remote, AF_INET,
- NLM_F_REQUEST, 0 /* pad */, 2 /* idiagExt */, TCP_ALL_STATES);
-
- assertArrayEquals(INET_DIAG_REQ_V2_TCP_INET_INET_DIAG_BYTES, msg);
-
- local = new InetSocketAddress(
- InetAddress.getByName("fe80::86c9:b2ff:fe6a:ed4b"), 42462);
- remote = new InetSocketAddress(InetAddress.getByName("8.8.8.8"),
- 47473);
- msg = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, local, remote, AF_INET6,
- NLM_F_REQUEST, 0 /* pad */, 0 /* idiagExt */, TCP_ALL_STATES);
-
- assertArrayEquals(INET_DIAG_REQ_V2_TCP_INET6_BYTES, msg);
- }
-
- // Hexadecimal representation of InetDiagReqV2 request with no socket specified.
- private static final String INET_DIAG_REQ_V2_TCP_INET6_NO_ID_SPECIFIED_HEX =
- // struct nlmsghdr
- "48000000" + // length = 72
- "1400" + // type = SOCK_DIAG_BY_FAMILY
- "0100" + // flags = NLM_F_REQUEST
- "00000000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct inet_diag_req_v2
- "0a" + // family = AF_INET6
- "06" + // protcol = IPPROTO_TCP
- "00" + // idiag_ext
- "00" + // pad
- "ffffffff" + // idiag_states
- // inet_diag_sockid
- "0000" + // idiag_sport
- "0000" + // idiag_dport
- "00000000000000000000000000000000" + // idiag_src
- "00000000000000000000000000000000" + // idiag_dst
- "00000000" + // idiag_if
- "0000000000000000"; // idiag_cookie
-
- private static final byte[] INET_DIAG_REQ_V2_TCP_INET6_NO_ID_SPECIFED_BYTES =
- HexEncoding.decode(INET_DIAG_REQ_V2_TCP_INET6_NO_ID_SPECIFIED_HEX.toCharArray(), false);
-
- @Test
- public void testInetDiagReqV2TcpInet6NoIdSpecified() throws Exception {
- InetSocketAddress local = new InetSocketAddress(
- InetAddress.getByName("fe80::fe6a:ed4b"), 12345);
- InetSocketAddress remote = new InetSocketAddress(InetAddress.getByName("8.8.4.4"),
- 54321);
- // Verify no socket specified if either local or remote socket address is null.
- byte[] msgExt = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, null, null, AF_INET6,
- NLM_F_REQUEST, 0 /* pad */, 0 /* idiagExt */, TCP_ALL_STATES);
- byte[] msg;
- try {
- msg = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, null, remote, AF_INET6,
- NLM_F_REQUEST);
- fail("Both remote and local should be null, expected UnknownHostException");
- } catch (NullPointerException e) {
- }
-
- try {
- msg = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, local, null, AF_INET6,
- NLM_F_REQUEST, 0 /* pad */, 0 /* idiagExt */, TCP_ALL_STATES);
- fail("Both remote and local should be null, expected UnknownHostException");
- } catch (NullPointerException e) {
- }
-
- msg = InetDiagMessage.InetDiagReqV2(IPPROTO_TCP, null, null, AF_INET6,
- NLM_F_REQUEST, 0 /* pad */, 0 /* idiagExt */, TCP_ALL_STATES);
- assertArrayEquals(INET_DIAG_REQ_V2_TCP_INET6_NO_ID_SPECIFED_BYTES, msg);
- assertArrayEquals(INET_DIAG_REQ_V2_TCP_INET6_NO_ID_SPECIFED_BYTES, msgExt);
- }
-
- // Hexadecimal representation of InetDiagReqV2 request.
- private static final String INET_DIAG_MSG_HEX =
- // struct nlmsghdr
- "58000000" + // length = 88
- "1400" + // type = SOCK_DIAG_BY_FAMILY
- "0200" + // flags = NLM_F_MULTI
- "00000000" + // seqno
- "f5220000" + // pid (0 == kernel)
- // struct inet_diag_msg
- "0a" + // family = AF_INET6
- "01" + // idiag_state
- "00" + // idiag_timer
- "00" + // idiag_retrans
- // inet_diag_sockid
- "a817" + // idiag_sport = 43031
- "960f" + // idiag_dport = 38415
- "fe8000000000000086c9b2fffe6aed4b" + // idiag_src = fe80::86c9:b2ff:fe6a:ed4b
- "00000000000000000000ffff08080808" + // idiag_dst = 8.8.8.8
- "00000000" + // idiag_if
- "ffffffffffffffff" + // idiag_cookie = INET_DIAG_NOCOOKIE
- "00000000" + // idiag_expires
- "00000000" + // idiag_rqueue
- "00000000" + // idiag_wqueue
- "a3270000" + // idiag_uid
- "A57E1900"; // idiag_inode
- private static final byte[] INET_DIAG_MSG_BYTES =
- HexEncoding.decode(INET_DIAG_MSG_HEX.toCharArray(), false);
-
- @Test
- public void testParseInetDiagResponse() throws Exception {
- final ByteBuffer byteBuffer = ByteBuffer.wrap(INET_DIAG_MSG_BYTES);
- byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
- final NetlinkMessage msg = NetlinkMessage.parse(byteBuffer);
- assertNotNull(msg);
-
- assertTrue(msg instanceof InetDiagMessage);
- final InetDiagMessage inetDiagMsg = (InetDiagMessage) msg;
- assertEquals(10147, inetDiagMsg.mStructInetDiagMsg.idiag_uid);
-
- final StructNlMsgHdr hdr = inetDiagMsg.getHeader();
- assertNotNull(hdr);
- assertEquals(NetlinkConstants.SOCK_DIAG_BY_FAMILY, hdr.nlmsg_type);
- assertEquals(StructNlMsgHdr.NLM_F_MULTI, hdr.nlmsg_flags);
- assertEquals(0, hdr.nlmsg_seq);
- assertEquals(8949, hdr.nlmsg_pid);
- }
-}
diff --git a/tests/net/java/android/net/netlink/NetlinkErrorMessageTest.java b/tests/net/java/android/net/netlink/NetlinkErrorMessageTest.java
deleted file mode 100644
index 44ab605..0000000
--- a/tests/net/java/android/net/netlink/NetlinkErrorMessageTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import static android.net.netlink.StructNlMsgHdr.NLM_F_ACK;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REPLACE;
-import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import android.net.netlink.NetlinkConstants;
-import android.net.netlink.NetlinkErrorMessage;
-import android.net.netlink.NetlinkMessage;
-import android.net.netlink.StructNlMsgErr;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import libcore.util.HexEncoding;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class NetlinkErrorMessageTest {
- private final String TAG = "NetlinkErrorMessageTest";
-
- // Hexadecimal representation of packet capture.
- public static final String NLM_ERROR_OK_HEX =
- // struct nlmsghdr
- "24000000" + // length = 36
- "0200" + // type = 2 (NLMSG_ERROR)
- "0000" + // flags
- "26350000" + // seqno
- "64100000" + // pid = userspace process
- // error integer
- "00000000" + // "errno" (0 == OK)
- // struct nlmsghdr
- "30000000" + // length (48) of original request
- "1C00" + // type = 28 (RTM_NEWNEIGH)
- "0501" + // flags (NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE)
- "26350000" + // seqno
- "00000000"; // pid = kernel
- public static final byte[] NLM_ERROR_OK =
- HexEncoding.decode(NLM_ERROR_OK_HEX.toCharArray(), false);
-
- @Test
- public void testParseNlmErrorOk() {
- final ByteBuffer byteBuffer = ByteBuffer.wrap(NLM_ERROR_OK);
- byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
- final NetlinkMessage msg = NetlinkMessage.parse(byteBuffer);
- assertNotNull(msg);
- assertTrue(msg instanceof NetlinkErrorMessage);
- final NetlinkErrorMessage errorMsg = (NetlinkErrorMessage) msg;
-
- final StructNlMsgHdr hdr = errorMsg.getHeader();
- assertNotNull(hdr);
- assertEquals(36, hdr.nlmsg_len);
- assertEquals(NetlinkConstants.NLMSG_ERROR, hdr.nlmsg_type);
- assertEquals(0, hdr.nlmsg_flags);
- assertEquals(13606, hdr.nlmsg_seq);
- assertEquals(4196, hdr.nlmsg_pid);
-
- final StructNlMsgErr err = errorMsg.getNlMsgError();
- assertNotNull(err);
- assertEquals(0, err.error);
- assertNotNull(err.msg);
- assertEquals(48, err.msg.nlmsg_len);
- assertEquals(NetlinkConstants.RTM_NEWNEIGH, err.msg.nlmsg_type);
- assertEquals((NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE), err.msg.nlmsg_flags);
- assertEquals(13606, err.msg.nlmsg_seq);
- assertEquals(0, err.msg.nlmsg_pid);
- }
-}
diff --git a/tests/net/java/android/net/netlink/NetlinkSocketTest.java b/tests/net/java/android/net/netlink/NetlinkSocketTest.java
deleted file mode 100644
index 3916578..0000000
--- a/tests/net/java/android/net/netlink/NetlinkSocketTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import static android.net.netlink.NetlinkSocket.DEFAULT_RECV_BUFSIZE;
-import static android.system.OsConstants.NETLINK_ROUTE;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import android.net.netlink.NetlinkSocket;
-import android.net.netlink.RtNetlinkNeighborMessage;
-import android.net.netlink.StructNlMsgHdr;
-import android.system.NetlinkSocketAddress;
-import android.system.Os;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import libcore.io.IoUtils;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.FileDescriptor;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class NetlinkSocketTest {
- private final String TAG = "NetlinkSocketTest";
-
- @Test
- public void testBasicWorkingGetNeighborsQuery() throws Exception {
- final FileDescriptor fd = NetlinkSocket.forProto(NETLINK_ROUTE);
- assertNotNull(fd);
-
- NetlinkSocket.connectToKernel(fd);
-
- final NetlinkSocketAddress localAddr = (NetlinkSocketAddress) Os.getsockname(fd);
- assertNotNull(localAddr);
- assertEquals(0, localAddr.getGroupsMask());
- assertTrue(0 != localAddr.getPortId());
-
- final int TEST_SEQNO = 5;
- final byte[] req = RtNetlinkNeighborMessage.newGetNeighborsRequest(TEST_SEQNO);
- assertNotNull(req);
-
- final long TIMEOUT = 500;
- assertEquals(req.length, NetlinkSocket.sendMessage(fd, req, 0, req.length, TIMEOUT));
-
- int neighMessageCount = 0;
- int doneMessageCount = 0;
-
- while (doneMessageCount == 0) {
- ByteBuffer response = NetlinkSocket.recvMessage(fd, DEFAULT_RECV_BUFSIZE, TIMEOUT);
- assertNotNull(response);
- assertTrue(StructNlMsgHdr.STRUCT_SIZE <= response.limit());
- assertEquals(0, response.position());
- assertEquals(ByteOrder.nativeOrder(), response.order());
-
- // Verify the messages at least appears minimally reasonable.
- while (response.remaining() > 0) {
- final NetlinkMessage msg = NetlinkMessage.parse(response);
- assertNotNull(msg);
- final StructNlMsgHdr hdr = msg.getHeader();
- assertNotNull(hdr);
-
- if (hdr.nlmsg_type == NetlinkConstants.NLMSG_DONE) {
- doneMessageCount++;
- continue;
- }
-
- assertEquals(NetlinkConstants.RTM_NEWNEIGH, hdr.nlmsg_type);
- assertTrue(msg instanceof RtNetlinkNeighborMessage);
- assertTrue((hdr.nlmsg_flags & StructNlMsgHdr.NLM_F_MULTI) != 0);
- assertEquals(TEST_SEQNO, hdr.nlmsg_seq);
- assertEquals(localAddr.getPortId(), hdr.nlmsg_pid);
-
- neighMessageCount++;
- }
- }
-
- assertEquals(1, doneMessageCount);
- // TODO: make sure this test passes sanely in airplane mode.
- assertTrue(neighMessageCount > 0);
-
- IoUtils.closeQuietly(fd);
- }
-}
diff --git a/tests/net/java/android/net/netlink/RtNetlinkNeighborMessageTest.java b/tests/net/java/android/net/netlink/RtNetlinkNeighborMessageTest.java
deleted file mode 100644
index 8162522..0000000
--- a/tests/net/java/android/net/netlink/RtNetlinkNeighborMessageTest.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright (C) 2015 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.netlink;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import android.net.netlink.NetlinkConstants;
-import android.net.netlink.NetlinkMessage;
-import android.net.netlink.RtNetlinkNeighborMessage;
-import android.net.netlink.StructNdMsg;
-import android.net.netlink.StructNlMsgHdr;
-import android.system.OsConstants;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import libcore.util.HexEncoding;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.Arrays;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class RtNetlinkNeighborMessageTest {
- private final String TAG = "RtNetlinkNeighborMessageTest";
-
- // Hexadecimal representation of packet capture.
- public static final String RTM_DELNEIGH_HEX =
- // struct nlmsghdr
- "4c000000" + // length = 76
- "1d00" + // type = 29 (RTM_DELNEIGH)
- "0000" + // flags
- "00000000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct ndmsg
- "02" + // family
- "00" + // pad1
- "0000" + // pad2
- "15000000" + // interface index (21 == wlan0, on test device)
- "0400" + // NUD state (0x04 == NUD_STALE)
- "00" + // flags
- "01" + // type
- // struct nlattr: NDA_DST
- "0800" + // length = 8
- "0100" + // type (1 == NDA_DST, for neighbor messages)
- "c0a89ffe" + // IPv4 address (== 192.168.159.254)
- // struct nlattr: NDA_LLADDR
- "0a00" + // length = 10
- "0200" + // type (2 == NDA_LLADDR, for neighbor messages)
- "00005e000164" + // MAC Address (== 00:00:5e:00:01:64)
- "0000" + // padding, for 4 byte alignment
- // struct nlattr: NDA_PROBES
- "0800" + // length = 8
- "0400" + // type (4 == NDA_PROBES, for neighbor messages)
- "01000000" + // number of probes
- // struct nlattr: NDA_CACHEINFO
- "1400" + // length = 20
- "0300" + // type (3 == NDA_CACHEINFO, for neighbor messages)
- "05190000" + // ndm_used, as "clock ticks ago"
- "05190000" + // ndm_confirmed, as "clock ticks ago"
- "190d0000" + // ndm_updated, as "clock ticks ago"
- "00000000"; // ndm_refcnt
- public static final byte[] RTM_DELNEIGH =
- HexEncoding.decode(RTM_DELNEIGH_HEX.toCharArray(), false);
-
- // Hexadecimal representation of packet capture.
- public static final String RTM_NEWNEIGH_HEX =
- // struct nlmsghdr
- "58000000" + // length = 88
- "1c00" + // type = 28 (RTM_NEWNEIGH)
- "0000" + // flags
- "00000000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct ndmsg
- "0a" + // family
- "00" + // pad1
- "0000" + // pad2
- "15000000" + // interface index (21 == wlan0, on test device)
- "0400" + // NUD state (0x04 == NUD_STALE)
- "80" + // flags
- "01" + // type
- // struct nlattr: NDA_DST
- "1400" + // length = 20
- "0100" + // type (1 == NDA_DST, for neighbor messages)
- "fe8000000000000086c9b2fffe6aed4b" + // IPv6 address (== fe80::86c9:b2ff:fe6a:ed4b)
- // struct nlattr: NDA_LLADDR
- "0a00" + // length = 10
- "0200" + // type (2 == NDA_LLADDR, for neighbor messages)
- "84c9b26aed4b" + // MAC Address (== 84:c9:b2:6a:ed:4b)
- "0000" + // padding, for 4 byte alignment
- // struct nlattr: NDA_PROBES
- "0800" + // length = 8
- "0400" + // type (4 == NDA_PROBES, for neighbor messages)
- "01000000" + // number of probes
- // struct nlattr: NDA_CACHEINFO
- "1400" + // length = 20
- "0300" + // type (3 == NDA_CACHEINFO, for neighbor messages)
- "eb0e0000" + // ndm_used, as "clock ticks ago"
- "861f0000" + // ndm_confirmed, as "clock ticks ago"
- "00000000" + // ndm_updated, as "clock ticks ago"
- "05000000"; // ndm_refcnt
- public static final byte[] RTM_NEWNEIGH =
- HexEncoding.decode(RTM_NEWNEIGH_HEX.toCharArray(), false);
-
- // An example of the full response from an RTM_GETNEIGH query.
- private static final String RTM_GETNEIGH_RESPONSE_HEX =
- // <-- struct nlmsghr -->|<-- struct ndmsg -->|<-- struct nlattr: NDA_DST -->|<-- NDA_LLADDR -->|<-- NDA_PROBES -->|<-- NDA_CACHEINFO -->|
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff020000000000000000000000000001 0a00 0200 333300000001 0000 0800 0400 00000000 1400 0300 a2280000 32110000 32110000 01000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff0200000000000000000001ff000001 0a00 0200 3333ff000001 0000 0800 0400 00000000 1400 0300 0d280000 9d100000 9d100000 00000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 0400 80 01 1400 0100 20010db800040ca00000000000000001 0a00 0200 84c9b26aed4b 0000 0800 0400 04000000 1400 0300 90100000 90100000 90080000 01000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff0200000000000000000001ff47da19 0a00 0200 3333ff47da19 0000 0800 0400 00000000 1400 0300 a1280000 31110000 31110000 01000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 14000000 4000 00 05 1400 0100 ff020000000000000000000000000016 0a00 0200 333300000016 0000 0800 0400 00000000 1400 0300 912a0000 21130000 21130000 00000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 14000000 4000 00 05 1400 0100 ff0200000000000000000001ffeace3b 0a00 0200 3333ffeace3b 0000 0800 0400 00000000 1400 0300 922a0000 22130000 22130000 00000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff0200000000000000000001ff5c2a83 0a00 0200 3333ff5c2a83 0000 0800 0400 00000000 1400 0300 391c0000 c9040000 c9040000 01000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 01000000 4000 00 02 1400 0100 00000000000000000000000000000000 0a00 0200 000000000000 0000 0800 0400 00000000 1400 0300 cd180200 5d010200 5d010200 08000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff020000000000000000000000000002 0a00 0200 333300000002 0000 0800 0400 00000000 1400 0300 352a0000 c5120000 c5120000 00000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff020000000000000000000000000016 0a00 0200 333300000016 0000 0800 0400 00000000 1400 0300 982a0000 28130000 28130000 00000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 0800 80 01 1400 0100 fe8000000000000086c9b2fffe6aed4b 0a00 0200 84c9b26aed4b 0000 0800 0400 00000000 1400 0300 23000000 24000000 57000000 13000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 15000000 4000 00 05 1400 0100 ff0200000000000000000001ffeace3b 0a00 0200 3333ffeace3b 0000 0800 0400 00000000 1400 0300 992a0000 29130000 29130000 01000000" +
- "58000000 1c00 0200 00000000 3e2b0000 0a 00 0000 14000000 4000 00 05 1400 0100 ff020000000000000000000000000002 0a00 0200 333300000002 0000 0800 0400 00000000 1400 0300 2e2a0000 be120000 be120000 00000000" +
- "44000000 1c00 0200 00000000 3e2b0000 02 00 0000 18000000 4000 00 03 0800 0100 00000000 0400 0200 0800 0400 00000000 1400 0300 75280000 05110000 05110000 22000000";
- public static final byte[] RTM_GETNEIGH_RESPONSE =
- HexEncoding.decode(RTM_GETNEIGH_RESPONSE_HEX.replaceAll(" ", "").toCharArray(), false);
-
- @Test
- public void testParseRtmDelNeigh() {
- final ByteBuffer byteBuffer = ByteBuffer.wrap(RTM_DELNEIGH);
- byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
- final NetlinkMessage msg = NetlinkMessage.parse(byteBuffer);
- assertNotNull(msg);
- assertTrue(msg instanceof RtNetlinkNeighborMessage);
- final RtNetlinkNeighborMessage neighMsg = (RtNetlinkNeighborMessage) msg;
-
- final StructNlMsgHdr hdr = neighMsg.getHeader();
- assertNotNull(hdr);
- assertEquals(76, hdr.nlmsg_len);
- assertEquals(NetlinkConstants.RTM_DELNEIGH, hdr.nlmsg_type);
- assertEquals(0, hdr.nlmsg_flags);
- assertEquals(0, hdr.nlmsg_seq);
- assertEquals(0, hdr.nlmsg_pid);
-
- final StructNdMsg ndmsgHdr = neighMsg.getNdHeader();
- assertNotNull(ndmsgHdr);
- assertEquals((byte) OsConstants.AF_INET, ndmsgHdr.ndm_family);
- assertEquals(21, ndmsgHdr.ndm_ifindex);
- assertEquals(StructNdMsg.NUD_STALE, ndmsgHdr.ndm_state);
- final InetAddress destination = neighMsg.getDestination();
- assertNotNull(destination);
- assertEquals(InetAddress.parseNumericAddress("192.168.159.254"), destination);
- }
-
- @Test
- public void testParseRtmNewNeigh() {
- final ByteBuffer byteBuffer = ByteBuffer.wrap(RTM_NEWNEIGH);
- byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
- final NetlinkMessage msg = NetlinkMessage.parse(byteBuffer);
- assertNotNull(msg);
- assertTrue(msg instanceof RtNetlinkNeighborMessage);
- final RtNetlinkNeighborMessage neighMsg = (RtNetlinkNeighborMessage) msg;
-
- final StructNlMsgHdr hdr = neighMsg.getHeader();
- assertNotNull(hdr);
- assertEquals(88, hdr.nlmsg_len);
- assertEquals(NetlinkConstants.RTM_NEWNEIGH, hdr.nlmsg_type);
- assertEquals(0, hdr.nlmsg_flags);
- assertEquals(0, hdr.nlmsg_seq);
- assertEquals(0, hdr.nlmsg_pid);
-
- final StructNdMsg ndmsgHdr = neighMsg.getNdHeader();
- assertNotNull(ndmsgHdr);
- assertEquals((byte) OsConstants.AF_INET6, ndmsgHdr.ndm_family);
- assertEquals(21, ndmsgHdr.ndm_ifindex);
- assertEquals(StructNdMsg.NUD_STALE, ndmsgHdr.ndm_state);
- final InetAddress destination = neighMsg.getDestination();
- assertNotNull(destination);
- assertEquals(InetAddress.parseNumericAddress("fe80::86c9:b2ff:fe6a:ed4b"), destination);
- }
-
- @Test
- public void testParseRtmGetNeighResponse() {
- final ByteBuffer byteBuffer = ByteBuffer.wrap(RTM_GETNEIGH_RESPONSE);
- byteBuffer.order(ByteOrder.LITTLE_ENDIAN); // For testing.
-
- int messageCount = 0;
- while (byteBuffer.remaining() > 0) {
- final NetlinkMessage msg = NetlinkMessage.parse(byteBuffer);
- assertNotNull(msg);
- assertTrue(msg instanceof RtNetlinkNeighborMessage);
- final RtNetlinkNeighborMessage neighMsg = (RtNetlinkNeighborMessage) msg;
-
- final StructNlMsgHdr hdr = neighMsg.getHeader();
- assertNotNull(hdr);
- assertEquals(NetlinkConstants.RTM_NEWNEIGH, hdr.nlmsg_type);
- assertEquals(StructNlMsgHdr.NLM_F_MULTI, hdr.nlmsg_flags);
- assertEquals(0, hdr.nlmsg_seq);
- assertEquals(11070, hdr.nlmsg_pid);
-
- messageCount++;
- }
- // TODO: add more detailed spot checks.
- assertEquals(14, messageCount);
- }
-
- @Test
- public void testCreateRtmNewNeighMessage() {
- final int seqNo = 2635;
- final int ifIndex = 14;
- final byte[] llAddr =
- new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6 };
-
- // Hexadecimal representation of our created packet.
- final String expectedNewNeighHex =
- // struct nlmsghdr
- "30000000" + // length = 48
- "1c00" + // type = 28 (RTM_NEWNEIGH)
- "0501" + // flags (NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE)
- "4b0a0000" + // seqno
- "00000000" + // pid (0 == kernel)
- // struct ndmsg
- "02" + // family
- "00" + // pad1
- "0000" + // pad2
- "0e000000" + // interface index (14)
- "0800" + // NUD state (0x08 == NUD_DELAY)
- "00" + // flags
- "00" + // type
- // struct nlattr: NDA_DST
- "0800" + // length = 8
- "0100" + // type (1 == NDA_DST, for neighbor messages)
- "7f000001" + // IPv4 address (== 127.0.0.1)
- // struct nlattr: NDA_LLADDR
- "0a00" + // length = 10
- "0200" + // type (2 == NDA_LLADDR, for neighbor messages)
- "010203040506" + // MAC Address (== 01:02:03:04:05:06)
- "0000"; // padding, for 4 byte alignment
- final byte[] expectedNewNeigh =
- HexEncoding.decode(expectedNewNeighHex.toCharArray(), false);
-
- final byte[] bytes = RtNetlinkNeighborMessage.newNewNeighborMessage(
- seqNo, Inet4Address.LOOPBACK, StructNdMsg.NUD_DELAY, ifIndex, llAddr);
- if (!Arrays.equals(expectedNewNeigh, bytes)) {
- assertEquals(expectedNewNeigh.length, bytes.length);
- for (int i = 0; i < Math.min(expectedNewNeigh.length, bytes.length); i++) {
- assertEquals(expectedNewNeigh[i], bytes[i]);
- }
- }
- }
-}
diff --git a/tests/net/java/android/net/shared/Inet4AddressUtilsTest.java b/tests/net/java/android/net/shared/Inet4AddressUtilsTest.java
deleted file mode 100644
index 35f8c79..0000000
--- a/tests/net/java/android/net/shared/Inet4AddressUtilsTest.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import static android.net.shared.Inet4AddressUtils.getBroadcastAddress;
-import static android.net.shared.Inet4AddressUtils.getImplicitNetmask;
-import static android.net.shared.Inet4AddressUtils.getPrefixMaskAsInet4Address;
-import static android.net.shared.Inet4AddressUtils.inet4AddressToIntHTH;
-import static android.net.shared.Inet4AddressUtils.inet4AddressToIntHTL;
-import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
-import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTL;
-import static android.net.shared.Inet4AddressUtils.netmaskToPrefixLength;
-import static android.net.shared.Inet4AddressUtils.prefixLengthToV4NetmaskIntHTH;
-import static android.net.shared.Inet4AddressUtils.prefixLengthToV4NetmaskIntHTL;
-
-import static junit.framework.Assert.assertEquals;
-
-import static org.junit.Assert.fail;
-
-import android.net.InetAddresses;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.Inet4Address;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class Inet4AddressUtilsTest {
-
- @Test
- public void testInet4AddressToIntHTL() {
- assertEquals(0, inet4AddressToIntHTL(ipv4Address("0.0.0.0")));
- assertEquals(0x000080ff, inet4AddressToIntHTL(ipv4Address("255.128.0.0")));
- assertEquals(0x0080ff0a, inet4AddressToIntHTL(ipv4Address("10.255.128.0")));
- assertEquals(0x00feff0a, inet4AddressToIntHTL(ipv4Address("10.255.254.0")));
- assertEquals(0xfeffa8c0, inet4AddressToIntHTL(ipv4Address("192.168.255.254")));
- assertEquals(0xffffa8c0, inet4AddressToIntHTL(ipv4Address("192.168.255.255")));
- }
-
- @Test
- public void testIntToInet4AddressHTL() {
- assertEquals(ipv4Address("0.0.0.0"), intToInet4AddressHTL(0));
- assertEquals(ipv4Address("255.128.0.0"), intToInet4AddressHTL(0x000080ff));
- assertEquals(ipv4Address("10.255.128.0"), intToInet4AddressHTL(0x0080ff0a));
- assertEquals(ipv4Address("10.255.254.0"), intToInet4AddressHTL(0x00feff0a));
- assertEquals(ipv4Address("192.168.255.254"), intToInet4AddressHTL(0xfeffa8c0));
- assertEquals(ipv4Address("192.168.255.255"), intToInet4AddressHTL(0xffffa8c0));
- }
-
- @Test
- public void testInet4AddressToIntHTH() {
- assertEquals(0, inet4AddressToIntHTH(ipv4Address("0.0.0.0")));
- assertEquals(0xff800000, inet4AddressToIntHTH(ipv4Address("255.128.0.0")));
- assertEquals(0x0aff8000, inet4AddressToIntHTH(ipv4Address("10.255.128.0")));
- assertEquals(0x0afffe00, inet4AddressToIntHTH(ipv4Address("10.255.254.0")));
- assertEquals(0xc0a8fffe, inet4AddressToIntHTH(ipv4Address("192.168.255.254")));
- assertEquals(0xc0a8ffff, inet4AddressToIntHTH(ipv4Address("192.168.255.255")));
- }
-
- @Test
- public void testIntToInet4AddressHTH() {
- assertEquals(ipv4Address("0.0.0.0"), intToInet4AddressHTH(0));
- assertEquals(ipv4Address("255.128.0.0"), intToInet4AddressHTH(0xff800000));
- assertEquals(ipv4Address("10.255.128.0"), intToInet4AddressHTH(0x0aff8000));
- assertEquals(ipv4Address("10.255.254.0"), intToInet4AddressHTH(0x0afffe00));
- assertEquals(ipv4Address("192.168.255.254"), intToInet4AddressHTH(0xc0a8fffe));
- assertEquals(ipv4Address("192.168.255.255"), intToInet4AddressHTH(0xc0a8ffff));
- }
-
-
- @Test
- public void testPrefixLengthToV4NetmaskIntHTL() {
- assertEquals(0, prefixLengthToV4NetmaskIntHTL(0));
- assertEquals(0x000080ff /* 255.128.0.0 */, prefixLengthToV4NetmaskIntHTL(9));
- assertEquals(0x0080ffff /* 255.255.128.0 */, prefixLengthToV4NetmaskIntHTL(17));
- assertEquals(0x00feffff /* 255.255.254.0 */, prefixLengthToV4NetmaskIntHTL(23));
- assertEquals(0xfeffffff /* 255.255.255.254 */, prefixLengthToV4NetmaskIntHTL(31));
- assertEquals(0xffffffff /* 255.255.255.255 */, prefixLengthToV4NetmaskIntHTL(32));
- }
-
- @Test
- public void testPrefixLengthToV4NetmaskIntHTH() {
- assertEquals(0, prefixLengthToV4NetmaskIntHTH(0));
- assertEquals(0xff800000 /* 255.128.0.0 */, prefixLengthToV4NetmaskIntHTH(9));
- assertEquals(0xffff8000 /* 255.255.128.0 */, prefixLengthToV4NetmaskIntHTH(17));
- assertEquals(0xfffffe00 /* 255.255.254.0 */, prefixLengthToV4NetmaskIntHTH(23));
- assertEquals(0xfffffffe /* 255.255.255.254 */, prefixLengthToV4NetmaskIntHTH(31));
- assertEquals(0xffffffff /* 255.255.255.255 */, prefixLengthToV4NetmaskIntHTH(32));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testPrefixLengthToV4NetmaskIntHTH_NegativeLength() {
- prefixLengthToV4NetmaskIntHTH(-1);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testPrefixLengthToV4NetmaskIntHTH_LengthTooLarge() {
- prefixLengthToV4NetmaskIntHTH(33);
- }
-
- private void checkAddressMasking(String expectedAddr, String addr, int prefixLength) {
- final int prefix = prefixLengthToV4NetmaskIntHTH(prefixLength);
- final int addrInt = inet4AddressToIntHTH(ipv4Address(addr));
- assertEquals(ipv4Address(expectedAddr), intToInet4AddressHTH(prefix & addrInt));
- }
-
- @Test
- public void testPrefixLengthToV4NetmaskIntHTH_MaskAddr() {
- checkAddressMasking("192.168.0.0", "192.168.128.1", 16);
- checkAddressMasking("255.240.0.0", "255.255.255.255", 12);
- checkAddressMasking("255.255.255.255", "255.255.255.255", 32);
- checkAddressMasking("0.0.0.0", "255.255.255.255", 0);
- }
-
- @Test
- public void testGetImplicitNetmask() {
- assertEquals(8, getImplicitNetmask(ipv4Address("4.2.2.2")));
- assertEquals(8, getImplicitNetmask(ipv4Address("10.5.6.7")));
- assertEquals(16, getImplicitNetmask(ipv4Address("173.194.72.105")));
- assertEquals(16, getImplicitNetmask(ipv4Address("172.23.68.145")));
- assertEquals(24, getImplicitNetmask(ipv4Address("192.0.2.1")));
- assertEquals(24, getImplicitNetmask(ipv4Address("192.168.5.1")));
- assertEquals(32, getImplicitNetmask(ipv4Address("224.0.0.1")));
- assertEquals(32, getImplicitNetmask(ipv4Address("255.6.7.8")));
- }
-
- private void assertInvalidNetworkMask(Inet4Address addr) {
- try {
- netmaskToPrefixLength(addr);
- fail("Invalid netmask " + addr.getHostAddress() + " did not cause exception");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- @Test
- public void testNetmaskToPrefixLength() {
- assertEquals(0, netmaskToPrefixLength(ipv4Address("0.0.0.0")));
- assertEquals(9, netmaskToPrefixLength(ipv4Address("255.128.0.0")));
- assertEquals(17, netmaskToPrefixLength(ipv4Address("255.255.128.0")));
- assertEquals(23, netmaskToPrefixLength(ipv4Address("255.255.254.0")));
- assertEquals(31, netmaskToPrefixLength(ipv4Address("255.255.255.254")));
- assertEquals(32, netmaskToPrefixLength(ipv4Address("255.255.255.255")));
-
- assertInvalidNetworkMask(ipv4Address("0.0.0.1"));
- assertInvalidNetworkMask(ipv4Address("255.255.255.253"));
- assertInvalidNetworkMask(ipv4Address("255.255.0.255"));
- }
-
- @Test
- public void testGetPrefixMaskAsAddress() {
- assertEquals("255.255.240.0", getPrefixMaskAsInet4Address(20).getHostAddress());
- assertEquals("255.0.0.0", getPrefixMaskAsInet4Address(8).getHostAddress());
- assertEquals("0.0.0.0", getPrefixMaskAsInet4Address(0).getHostAddress());
- assertEquals("255.255.255.255", getPrefixMaskAsInet4Address(32).getHostAddress());
- }
-
- @Test
- public void testGetBroadcastAddress() {
- assertEquals("192.168.15.255",
- getBroadcastAddress(ipv4Address("192.168.0.123"), 20).getHostAddress());
- assertEquals("192.255.255.255",
- getBroadcastAddress(ipv4Address("192.168.0.123"), 8).getHostAddress());
- assertEquals("192.168.0.123",
- getBroadcastAddress(ipv4Address("192.168.0.123"), 32).getHostAddress());
- assertEquals("255.255.255.255",
- getBroadcastAddress(ipv4Address("192.168.0.123"), 0).getHostAddress());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetBroadcastAddress_PrefixTooLarge() {
- getBroadcastAddress(ipv4Address("192.168.0.123"), 33);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetBroadcastAddress_NegativePrefix() {
- getBroadcastAddress(ipv4Address("192.168.0.123"), -1);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetPrefixMaskAsAddress_PrefixTooLarge() {
- getPrefixMaskAsInet4Address(33);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetPrefixMaskAsAddress_NegativePrefix() {
- getPrefixMaskAsInet4Address(-1);
- }
-
- private Inet4Address ipv4Address(String addr) {
- return (Inet4Address) InetAddresses.parseNumericAddress(addr);
- }
-}
diff --git a/tests/net/java/android/net/shared/InitialConfigurationTest.java b/tests/net/java/android/net/shared/InitialConfigurationTest.java
deleted file mode 100644
index 17f8324..0000000
--- a/tests/net/java/android/net/shared/InitialConfigurationTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import static android.net.InetAddresses.parseNumericAddress;
-
-import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import android.net.IpPrefix;
-import android.net.LinkAddress;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Arrays;
-import java.util.function.Consumer;
-
-/**
- * Tests for {@link InitialConfiguration}
- */
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class InitialConfigurationTest {
- private InitialConfiguration mConfig;
-
- @Before
- public void setUp() {
- mConfig = new InitialConfiguration();
- mConfig.ipAddresses.addAll(Arrays.asList(
- new LinkAddress(parseNumericAddress("192.168.45.45"), 16),
- new LinkAddress(parseNumericAddress("2001:db8::45"), 33)));
- mConfig.directlyConnectedRoutes.addAll(Arrays.asList(
- new IpPrefix(parseNumericAddress("192.168.46.46"), 17),
- new IpPrefix(parseNumericAddress("2001:db8::46"), 34)));
- mConfig.dnsServers.addAll(Arrays.asList(
- parseNumericAddress("192.168.47.47"),
- parseNumericAddress("2001:db8::47")));
- // Any added InitialConfiguration field must be included in equals() to be tested properly
- assertFieldCountEquals(3, InitialConfiguration.class);
- }
-
- @Test
- public void testParcelUnparcelInitialConfiguration() {
- final InitialConfiguration unparceled =
- InitialConfiguration.fromStableParcelable(mConfig.toStableParcelable());
- assertEquals(mConfig, unparceled);
- }
-
- @Test
- public void testEquals() {
- assertEquals(mConfig, InitialConfiguration.copy(mConfig));
-
- assertNotEqualsAfterChange(c -> c.ipAddresses.add(
- new LinkAddress(parseNumericAddress("192.168.47.47"), 24)));
- assertNotEqualsAfterChange(c -> c.directlyConnectedRoutes.add(
- new IpPrefix(parseNumericAddress("192.168.46.46"), 32)));
- assertNotEqualsAfterChange(c -> c.dnsServers.add(parseNumericAddress("2001:db8::49")));
- assertFieldCountEquals(3, InitialConfiguration.class);
- }
-
- private void assertNotEqualsAfterChange(Consumer<InitialConfiguration> mutator) {
- final InitialConfiguration newConfig = InitialConfiguration.copy(mConfig);
- mutator.accept(newConfig);
- assertNotEquals(mConfig, newConfig);
- }
-}
diff --git a/tests/net/java/android/net/shared/IpConfigurationParcelableUtilTest.java b/tests/net/java/android/net/shared/IpConfigurationParcelableUtilTest.java
deleted file mode 100644
index f987389..0000000
--- a/tests/net/java/android/net/shared/IpConfigurationParcelableUtilTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import static android.net.InetAddresses.parseNumericAddress;
-import static android.net.shared.IpConfigurationParcelableUtil.fromStableParcelable;
-import static android.net.shared.IpConfigurationParcelableUtil.toStableParcelable;
-
-import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals;
-
-import static org.junit.Assert.assertEquals;
-
-import android.net.DhcpResults;
-import android.net.LinkAddress;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.Inet4Address;
-
-/**
- * Tests for {@link IpConfigurationParcelableUtil}.
- */
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class IpConfigurationParcelableUtilTest {
- private DhcpResults mDhcpResults;
-
- @Before
- public void setUp() {
- mDhcpResults = new DhcpResults();
- mDhcpResults.ipAddress = new LinkAddress(parseNumericAddress("2001:db8::42"), 64);
- mDhcpResults.gateway = parseNumericAddress("192.168.42.42");
- mDhcpResults.dnsServers.add(parseNumericAddress("2001:db8::43"));
- mDhcpResults.dnsServers.add(parseNumericAddress("192.168.43.43"));
- mDhcpResults.domains = "example.com";
- mDhcpResults.serverAddress = (Inet4Address) parseNumericAddress("192.168.44.44");
- mDhcpResults.vendorInfo = "TEST_VENDOR_INFO";
- mDhcpResults.leaseDuration = 3600;
- mDhcpResults.serverHostName = "dhcp.example.com";
- mDhcpResults.mtu = 1450;
- // Any added DhcpResults field must be included in equals() to be tested properly
- assertFieldCountEquals(9, DhcpResults.class);
- }
-
- @Test
- public void testParcelUnparcelDhcpResults() {
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_NullIpAddress() {
- mDhcpResults.ipAddress = null;
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_NullGateway() {
- mDhcpResults.gateway = null;
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_NullDomains() {
- mDhcpResults.domains = null;
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_EmptyDomains() {
- mDhcpResults.domains = "";
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_NullServerAddress() {
- mDhcpResults.serverAddress = null;
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_NullVendorInfo() {
- mDhcpResults.vendorInfo = null;
- doDhcpResultsParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcelDhcpResults_NullServerHostName() {
- mDhcpResults.serverHostName = null;
- doDhcpResultsParcelUnparcelTest();
- }
-
- private void doDhcpResultsParcelUnparcelTest() {
- final DhcpResults unparceled = fromStableParcelable(toStableParcelable(mDhcpResults));
- assertEquals(mDhcpResults, unparceled);
- }
-}
diff --git a/tests/net/java/android/net/shared/ProvisioningConfigurationTest.java b/tests/net/java/android/net/shared/ProvisioningConfigurationTest.java
deleted file mode 100644
index 7079a28..0000000
--- a/tests/net/java/android/net/shared/ProvisioningConfigurationTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2019 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.shared;
-
-import static android.net.InetAddresses.parseNumericAddress;
-import static android.net.shared.ProvisioningConfiguration.fromStableParcelable;
-
-import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import android.net.LinkAddress;
-import android.net.Network;
-import android.net.StaticIpConfiguration;
-import android.net.apf.ApfCapabilities;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.function.Consumer;
-
-/**
- * Tests for {@link ProvisioningConfiguration}.
- */
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class ProvisioningConfigurationTest {
- private ProvisioningConfiguration mConfig;
-
- @Before
- public void setUp() {
- mConfig = new ProvisioningConfiguration();
- mConfig.mEnableIPv4 = true;
- mConfig.mEnableIPv6 = true;
- mConfig.mUsingMultinetworkPolicyTracker = true;
- mConfig.mUsingIpReachabilityMonitor = true;
- mConfig.mRequestedPreDhcpActionMs = 42;
- mConfig.mInitialConfig = new InitialConfiguration();
- mConfig.mInitialConfig.ipAddresses.add(
- new LinkAddress(parseNumericAddress("192.168.42.42"), 24));
- mConfig.mStaticIpConfig = new StaticIpConfiguration();
- mConfig.mStaticIpConfig.ipAddress =
- new LinkAddress(parseNumericAddress("2001:db8::42"), 90);
- // Not testing other InitialConfig or StaticIpConfig members: they have their own unit tests
- mConfig.mApfCapabilities = new ApfCapabilities(1, 2, 3);
- mConfig.mProvisioningTimeoutMs = 4200;
- mConfig.mIPv6AddrGenMode = 123;
- mConfig.mNetwork = new Network(321);
- mConfig.mDisplayName = "test_config";
- // Any added field must be included in equals() to be tested properly
- assertFieldCountEquals(12, ProvisioningConfiguration.class);
- }
-
- @Test
- public void testParcelUnparcel() {
- doParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcel_NullInitialConfiguration() {
- mConfig.mInitialConfig = null;
- doParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcel_NullStaticConfiguration() {
- mConfig.mStaticIpConfig = null;
- doParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcel_NullApfCapabilities() {
- mConfig.mApfCapabilities = null;
- doParcelUnparcelTest();
- }
-
- @Test
- public void testParcelUnparcel_NullNetwork() {
- mConfig.mNetwork = null;
- doParcelUnparcelTest();
- }
-
- private void doParcelUnparcelTest() {
- final ProvisioningConfiguration unparceled =
- fromStableParcelable(mConfig.toStableParcelable());
- assertEquals(mConfig, unparceled);
- }
-
- @Test
- public void testEquals() {
- assertEquals(mConfig, new ProvisioningConfiguration(mConfig));
-
- assertNotEqualsAfterChange(c -> c.mEnableIPv4 = false);
- assertNotEqualsAfterChange(c -> c.mEnableIPv6 = false);
- assertNotEqualsAfterChange(c -> c.mUsingMultinetworkPolicyTracker = false);
- assertNotEqualsAfterChange(c -> c.mUsingIpReachabilityMonitor = false);
- assertNotEqualsAfterChange(c -> c.mRequestedPreDhcpActionMs++);
- assertNotEqualsAfterChange(c -> c.mInitialConfig.ipAddresses.add(
- new LinkAddress(parseNumericAddress("192.168.47.47"), 16)));
- assertNotEqualsAfterChange(c -> c.mInitialConfig = null);
- assertNotEqualsAfterChange(c -> c.mStaticIpConfig.ipAddress =
- new LinkAddress(parseNumericAddress("2001:db8::47"), 64));
- assertNotEqualsAfterChange(c -> c.mStaticIpConfig = null);
- assertNotEqualsAfterChange(c -> c.mApfCapabilities = new ApfCapabilities(4, 5, 6));
- assertNotEqualsAfterChange(c -> c.mApfCapabilities = null);
- assertNotEqualsAfterChange(c -> c.mProvisioningTimeoutMs++);
- assertNotEqualsAfterChange(c -> c.mIPv6AddrGenMode++);
- assertNotEqualsAfterChange(c -> c.mNetwork = new Network(123));
- assertNotEqualsAfterChange(c -> c.mNetwork = null);
- assertNotEqualsAfterChange(c -> c.mDisplayName = "other_test");
- assertNotEqualsAfterChange(c -> c.mDisplayName = null);
- assertFieldCountEquals(12, ProvisioningConfiguration.class);
- }
-
- private void assertNotEqualsAfterChange(Consumer<ProvisioningConfiguration> mutator) {
- final ProvisioningConfiguration newConfig = new ProvisioningConfiguration(mConfig);
- mutator.accept(newConfig);
- assertNotEquals(mConfig, newConfig);
- }
-}
diff --git a/tests/net/java/android/net/util/InterfaceParamsTest.java b/tests/net/java/android/net/util/InterfaceParamsTest.java
deleted file mode 100644
index 141455c..0000000
--- a/tests/net/java/android/net/util/InterfaceParamsTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.util;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class InterfaceParamsTest {
- @Test
- public void testNullInterfaceReturnsNull() {
- assertNull(InterfaceParams.getByName(null));
- }
-
- @Test
- public void testNonExistentInterfaceReturnsNull() {
- assertNull(InterfaceParams.getByName("doesnotexist0"));
- }
-
- @Test
- public void testLoopback() {
- final InterfaceParams ifParams = InterfaceParams.getByName("lo");
- assertNotNull(ifParams);
- assertEquals("lo", ifParams.name);
- assertTrue(ifParams.index > 0);
- assertNotNull(ifParams.macAddr);
- assertTrue(ifParams.defaultMtu >= NetworkConstants.ETHER_MTU);
- }
-}
diff --git a/tests/net/java/android/net/util/SharedLogTest.java b/tests/net/java/android/net/util/SharedLogTest.java
deleted file mode 100644
index e1dba36..0000000
--- a/tests/net/java/android/net/util/SharedLogTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.util;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintWriter;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class SharedLogTest {
- private static final String TIMESTAMP_PATTERN = "\\d{2}:\\d{2}:\\d{2}";
- private static final String TIMESTAMP = "HH:MM:SS";
-
- @Test
- public void testBasicOperation() {
- final SharedLog logTop = new SharedLog("top");
- logTop.mark("first post!");
-
- final SharedLog logLevel2a = logTop.forSubComponent("twoA");
- final SharedLog logLevel2b = logTop.forSubComponent("twoB");
- logLevel2b.e("2b or not 2b");
- logLevel2b.e("No exception", null);
- logLevel2b.e("Wait, here's one", new Exception("Test"));
- logLevel2a.w("second post?");
-
- final SharedLog logLevel3 = logLevel2a.forSubComponent("three");
- logTop.log("still logging");
- logLevel3.log("3 >> 2");
- logLevel2a.mark("ok: last post");
-
- final String[] expected = {
- " - MARK first post!",
- " - [twoB] ERROR 2b or not 2b",
- " - [twoB] ERROR No exception",
- // No stacktrace in shared log, only in logcat
- " - [twoB] ERROR Wait, here's one: Test",
- " - [twoA] WARN second post?",
- " - still logging",
- " - [twoA.three] 3 >> 2",
- " - [twoA] MARK ok: last post",
- };
- // Verify the logs are all there and in the correct order.
- verifyLogLines(expected, logTop);
-
- // In fact, because they all share the same underlying LocalLog,
- // every subcomponent SharedLog's dump() is identical.
- verifyLogLines(expected, logLevel2a);
- verifyLogLines(expected, logLevel2b);
- verifyLogLines(expected, logLevel3);
- }
-
- private static void verifyLogLines(String[] expected, SharedLog log) {
- final ByteArrayOutputStream ostream = new ByteArrayOutputStream();
- final PrintWriter pw = new PrintWriter(ostream, true);
- log.dump(null, pw, null);
-
- final String dumpOutput = ostream.toString();
- assertTrue(dumpOutput != null);
- assertTrue(!"".equals(dumpOutput));
-
- final String[] lines = dumpOutput.split("\n");
- assertEquals(expected.length, lines.length);
-
- for (int i = 0; i < expected.length; i++) {
- String got = lines[i];
- String want = expected[i];
- assertTrue(String.format("'%s' did not contain '%s'", got, want), got.endsWith(want));
- assertTrue(String.format("'%s' did not contain a %s timestamp", got, TIMESTAMP),
- got.replaceFirst(TIMESTAMP_PATTERN, TIMESTAMP).contains(TIMESTAMP));
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkScoreCache.java b/wifi/java/android/net/wifi/WifiNetworkScoreCache.java
index b22ae070..5a212a8 100755
--- a/wifi/java/android/net/wifi/WifiNetworkScoreCache.java
+++ b/wifi/java/android/net/wifi/WifiNetworkScoreCache.java
@@ -22,6 +22,7 @@
import android.content.Context;
import android.net.INetworkScoreCache;
import android.net.NetworkKey;
+import android.net.NetworkScoreManager;
import android.net.ScoredNetwork;
import android.os.Handler;
import android.os.Process;
@@ -40,7 +41,8 @@
*
* @hide
*/
-public class WifiNetworkScoreCache extends INetworkScoreCache.Stub {
+public class WifiNetworkScoreCache extends INetworkScoreCache.Stub
+ implements NetworkScoreManager.NetworkScoreCallback {
private static final String TAG = "WifiNetworkScoreCache";
private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
@@ -246,6 +248,17 @@
}
@Override protected final void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
+ WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
+ dumpWithLatestScanResults(fd, writer, args, wifiManager.getScanResults());
+ }
+
+ /**
+ * This is directly invoked from within Wifi-Service (on it's instance of this class), hence
+ * avoid making the WifiManager.getScanResults() call to avoid a deadlock.
+ */
+ public final void dumpWithLatestScanResults(
+ FileDescriptor fd, PrintWriter writer, String[] args,
+ List<ScanResult> latestScanResults) {
mContext.enforceCallingOrSelfPermission(permission.DUMP, TAG);
String header = String.format("WifiNetworkScoreCache (%s/%d)",
mContext.getPackageName(), Process.myUid());
@@ -256,8 +269,7 @@
writer.println(" " + score);
}
writer.println(" Network scores for latest ScanResults:");
- WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
- for (ScanResult scanResult : wifiManager.getScanResults()) {
+ for (ScanResult scanResult : latestScanResults) {
writer.println(
" " + buildNetworkKey(scanResult) + ": " + getNetworkScore(scanResult));
}