use of android.net.NetworkPolicy in project android_frameworks_base by DirtyUnicorns.
the class NetworkPolicyManagerServiceTest method testLastCycleBoundaryLastMonth.
public void testLastCycleBoundaryLastMonth() throws Exception {
// assume cycle day of "20th", which should be in last month
final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
final NetworkPolicy policy = new NetworkPolicy(sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
final long actualCycle = computeLastCycleBoundary(currentTime, policy);
assertTimeEquals(expectedCycle, actualCycle);
}
use of android.net.NetworkPolicy in project android_frameworks_base by DirtyUnicorns.
the class NetworkPolicyManagerService method updateNetworkRulesNL.
/**
* Examine all connected {@link NetworkState}, looking for
* {@link NetworkPolicy} that need to be enforced. When matches found, set
* remaining quota based on usage cycle and historical stats.
*/
void updateNetworkRulesNL() {
if (LOGV)
Slog.v(TAG, "updateNetworkRulesNL()");
final NetworkState[] states;
try {
states = mConnManager.getAllNetworkState();
} catch (RemoteException e) {
// ignored; service lives in system_server
return;
}
// First, generate identities of all connected networks so we can
// quickly compare them against all defined policies below.
final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
for (NetworkState state : states) {
if (state.networkInfo != null && state.networkInfo.isConnected()) {
final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
final String baseIface = state.linkProperties.getInterfaceName();
if (baseIface != null) {
connIdents.add(Pair.create(baseIface, ident));
}
// Stacked interfaces are considered to have same identity as
// their parent network.
final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
for (LinkProperties stackedLink : stackedLinks) {
final String stackedIface = stackedLink.getInterfaceName();
if (stackedIface != null) {
connIdents.add(Pair.create(stackedIface, ident));
}
}
}
}
// Apply policies against all connected interfaces found above
mNetworkRules.clear();
final ArrayList<String> ifaceList = Lists.newArrayList();
for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
ifaceList.clear();
for (int j = connIdents.size() - 1; j >= 0; j--) {
final Pair<String, NetworkIdentity> ident = connIdents.get(j);
if (policy.template.matches(ident.second)) {
ifaceList.add(ident.first);
}
}
if (ifaceList.size() > 0) {
final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
mNetworkRules.put(policy, ifaces);
}
}
long lowestRule = Long.MAX_VALUE;
final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
// apply each policy that we found ifaces for; compute remaining data
// based on current cycle and historical stats, and push to kernel.
final long currentTime = currentTimeMillis();
for (int i = mNetworkRules.size() - 1; i >= 0; i--) {
final NetworkPolicy policy = mNetworkRules.keyAt(i);
final String[] ifaces = mNetworkRules.valueAt(i);
final long start;
final long totalBytes;
if (policy.hasCycle()) {
start = computeLastCycleBoundary(currentTime, policy);
totalBytes = getTotalBytes(policy.template, start, currentTime);
} else {
start = Long.MAX_VALUE;
totalBytes = 0;
}
if (LOGD) {
Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
}
final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
if (hasLimit || policy.metered) {
final long quotaBytes;
if (!hasLimit) {
// metered network, but no policy limit; we still need to
// restrict apps, so push really high quota.
quotaBytes = Long.MAX_VALUE;
} else if (policy.lastLimitSnooze >= start) {
// snoozing past quota, but we still need to restrict apps,
// so push really high quota.
quotaBytes = Long.MAX_VALUE;
} else {
// remaining "quota" bytes are based on total usage in
// current cycle. kernel doesn't like 0-byte rules, so we
// set 1-byte quota and disable the radio later.
quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
}
if (ifaces.length > 1) {
// TODO: switch to shared quota once NMS supports
Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
}
for (String iface : ifaces) {
// long quotaBytes split up into two ints to fit in message
mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
newMeteredIfaces.add(iface);
}
}
// keep track of lowest warning or limit of active policies
if (hasWarning && policy.warningBytes < lowestRule) {
lowestRule = policy.warningBytes;
}
if (hasLimit && policy.limitBytes < lowestRule) {
lowestRule = policy.limitBytes;
}
}
for (int i = connIfaces.size() - 1; i >= 0; i--) {
String iface = connIfaces.valueAt(i);
// long quotaBytes split up into two ints to fit in message
mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface).sendToTarget();
newMeteredIfaces.add(iface);
}
mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
// remove quota on any trailing interfaces
for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
final String iface = mMeteredIfaces.valueAt(i);
if (!newMeteredIfaces.contains(iface)) {
mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
}
}
mMeteredIfaces = newMeteredIfaces;
final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
}
use of android.net.NetworkPolicy in project android_frameworks_base by DirtyUnicorns.
the class NetworkPolicyManagerService method readPolicyAL.
private void readPolicyAL() {
if (LOGV)
Slog.v(TAG, "readPolicyAL()");
// clear any existing policy and read from disk
mNetworkPolicy.clear();
mUidPolicy.clear();
FileInputStream fis = null;
try {
fis = mPolicyFile.openRead();
final XmlPullParser in = Xml.newPullParser();
in.setInput(fis, StandardCharsets.UTF_8.name());
int type;
int version = VERSION_INIT;
boolean insideWhitelist = false;
while ((type = in.next()) != END_DOCUMENT) {
final String tag = in.getName();
if (type == START_TAG) {
if (TAG_POLICY_LIST.equals(tag)) {
final boolean oldValue = mRestrictBackground;
version = readIntAttribute(in, ATTR_VERSION);
if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
mRestrictBackground = readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
} else {
mRestrictBackground = false;
}
if (mRestrictBackground != oldValue) {
// Some early services may have read the default value,
// so notify them that it's changed
mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0).sendToTarget();
}
} else if (TAG_NETWORK_POLICY.equals(tag)) {
final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
final String networkId;
if (version >= VERSION_ADDED_NETWORK_ID) {
networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
} else {
networkId = null;
}
final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
final String cycleTimezone;
if (version >= VERSION_ADDED_TIMEZONE) {
cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
} else {
cycleTimezone = Time.TIMEZONE_UTC;
}
final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
final long lastLimitSnooze;
if (version >= VERSION_SPLIT_SNOOZE) {
lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
} else if (version >= VERSION_ADDED_SNOOZE) {
lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
} else {
lastLimitSnooze = SNOOZE_NEVER;
}
final boolean metered;
if (version >= VERSION_ADDED_METERED) {
metered = readBooleanAttribute(in, ATTR_METERED);
} else {
switch(networkTemplate) {
case MATCH_MOBILE_3G_LOWER:
case MATCH_MOBILE_4G:
case MATCH_MOBILE_ALL:
metered = true;
break;
default:
metered = false;
}
}
final long lastWarningSnooze;
if (version >= VERSION_SPLIT_SNOOZE) {
lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
} else {
lastWarningSnooze = SNOOZE_NEVER;
}
final boolean inferred;
if (version >= VERSION_ADDED_INFERRED) {
inferred = readBooleanAttribute(in, ATTR_INFERRED);
} else {
inferred = false;
}
final NetworkTemplate template = new NetworkTemplate(networkTemplate, subscriberId, networkId);
if (template.isPersistable()) {
mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay, cycleTimezone, warningBytes, limitBytes, lastWarningSnooze, lastLimitSnooze, metered, inferred));
}
} else if (TAG_UID_POLICY.equals(tag)) {
final int uid = readIntAttribute(in, ATTR_UID);
final int policy = readIntAttribute(in, ATTR_POLICY);
if (UserHandle.isApp(uid)) {
setUidPolicyUncheckedUL(uid, policy, false);
} else {
Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
}
} else if (TAG_APP_POLICY.equals(tag)) {
final int appId = readIntAttribute(in, ATTR_APP_ID);
final int policy = readIntAttribute(in, ATTR_POLICY);
// TODO: set for other users during upgrade
// app policy is deprecated so this is only used in pre system user split.
final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
if (UserHandle.isApp(uid)) {
setUidPolicyUncheckedUL(uid, policy, false);
} else {
Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
}
} else if (TAG_WHITELIST.equals(tag)) {
insideWhitelist = true;
} else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
final int uid = readIntAttribute(in, ATTR_UID);
mRestrictBackgroundWhitelistUids.put(uid, true);
} else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
final int uid = readIntAttribute(in, ATTR_UID);
mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
}
} else if (type == END_TAG) {
if (TAG_WHITELIST.equals(tag)) {
insideWhitelist = false;
}
}
}
} catch (FileNotFoundException e) {
// missing policy is okay, probably first boot
upgradeLegacyBackgroundDataUL();
} catch (IOException e) {
Log.wtf(TAG, "problem reading network policy", e);
} catch (XmlPullParserException e) {
Log.wtf(TAG, "problem reading network policy", e);
} finally {
IoUtils.closeQuietly(fis);
}
}
use of android.net.NetworkPolicy in project android_frameworks_base by DirtyUnicorns.
the class NetworkPolicyManagerService method normalizePoliciesNL.
private void normalizePoliciesNL(NetworkPolicy[] policies) {
final TelephonyManager tele = TelephonyManager.from(mContext);
final String[] merged = tele.getMergedSubscriberIds();
mNetworkPolicy.clear();
for (NetworkPolicy policy : policies) {
// When two normalized templates conflict, prefer the most
// restrictive policy
policy.template = NetworkTemplate.normalize(policy.template, merged);
final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
if (existing == null || existing.compareTo(policy) > 0) {
if (existing != null) {
Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
}
mNetworkPolicy.put(policy.template, policy);
}
}
}
use of android.net.NetworkPolicy in project android_frameworks_base by DirtyUnicorns.
the class NetworkPolicyManagerShellCommand method setMeteredWifiNetwork.
private int setMeteredWifiNetwork() throws RemoteException {
final PrintWriter pw = getOutPrintWriter();
final String id = getNextArg();
if (id == null) {
pw.println("Error: didn't specify ID");
return -1;
}
final String arg = getNextArg();
if (arg == null) {
pw.println("Error: didn't specify BOOLEAN");
return -1;
}
final boolean metered = Boolean.valueOf(arg);
final NetworkPolicy[] policies = mInterface.getNetworkPolicies(null);
boolean changed = false;
// First try to find a policy with such id
for (NetworkPolicy policy : policies) {
if (policy.template.isMatchRuleMobile() || policy.metered == metered) {
continue;
}
final String networkId = getNetworkId(policy);
if (id.equals(networkId)) {
Log.i(TAG, "Changing " + networkId + " metered status to " + metered);
policy.metered = metered;
changed = true;
}
}
if (changed) {
mInterface.setNetworkPolicies(policies);
return 0;
}
// Policy not found: check if there is a saved wi-fi with such id.
for (WifiConfiguration config : mWifiManager.getConfiguredNetworks()) {
final String ssid = removeDoubleQuotes(config.SSID);
if (id.equals(ssid)) {
final NetworkPolicy policy = newPolicy(ssid);
policy.metered = true;
Log.i(TAG, "Creating new policy for " + ssid + ": " + policy);
final NetworkPolicy[] newPolicies = new NetworkPolicy[policies.length + 1];
System.arraycopy(policies, 0, newPolicies, 0, policies.length);
newPolicies[newPolicies.length - 1] = policy;
mInterface.setNetworkPolicies(newPolicies);
}
}
return 0;
}
Aggregations