NetworkPolicyManagerService.java revision f02b60aa4f367516f40cf3d60fffae0c6fe3e1b8
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
19import static android.Manifest.permission.ACCESS_NETWORK_STATE;
20import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
21import static android.Manifest.permission.DUMP;
22import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
23import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
24import static android.Manifest.permission.READ_PHONE_STATE;
25import static android.content.Intent.ACTION_PACKAGE_ADDED;
26import static android.content.Intent.ACTION_UID_REMOVED;
27import static android.content.Intent.EXTRA_UID;
28import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
29import static android.net.ConnectivityManager.TYPE_ETHERNET;
30import static android.net.ConnectivityManager.TYPE_MOBILE;
31import static android.net.ConnectivityManager.TYPE_WIFI;
32import static android.net.ConnectivityManager.TYPE_WIMAX;
33import static android.net.ConnectivityManager.isNetworkTypeMobile;
34import static android.net.NetworkPolicy.CYCLE_NONE;
35import static android.net.NetworkPolicy.LIMIT_DISABLED;
36import static android.net.NetworkPolicy.SNOOZE_NEVER;
37import static android.net.NetworkPolicy.WARNING_DISABLED;
38import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
39import static android.net.NetworkPolicyManager.POLICY_NONE;
40import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
41import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
42import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
43import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
44import static android.net.NetworkPolicyManager.dumpPolicy;
45import static android.net.NetworkPolicyManager.dumpRules;
46import static android.net.NetworkTemplate.MATCH_ETHERNET;
47import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
48import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
49import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
50import static android.net.NetworkTemplate.MATCH_WIFI;
51import static android.net.NetworkTemplate.buildTemplateMobileAll;
52import static android.net.TrafficStats.MB_IN_BYTES;
53import static android.net.wifi.WifiInfo.removeDoubleQuotes;
54import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
55import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
56import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
57import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
58import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
59import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
60import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
61import static android.telephony.TelephonyManager.SIM_STATE_READY;
62import static android.text.format.DateUtils.DAY_IN_MILLIS;
63import static com.android.internal.util.ArrayUtils.appendInt;
64import static com.android.internal.util.Preconditions.checkNotNull;
65import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
66import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readBooleanAttribute;
67import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readIntAttribute;
68import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readLongAttribute;
69import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeBooleanAttribute;
70import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeIntAttribute;
71import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeLongAttribute;
72import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
73import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
74import static org.xmlpull.v1.XmlPullParser.START_TAG;
75
76import android.app.IActivityManager;
77import android.app.INotificationManager;
78import android.app.IProcessObserver;
79import android.app.Notification;
80import android.app.PendingIntent;
81import android.content.BroadcastReceiver;
82import android.content.ComponentName;
83import android.content.Context;
84import android.content.Intent;
85import android.content.IntentFilter;
86import android.content.pm.ApplicationInfo;
87import android.content.pm.PackageManager;
88import android.content.pm.UserInfo;
89import android.content.res.Resources;
90import android.net.ConnectivityManager;
91import android.net.IConnectivityManager;
92import android.net.INetworkManagementEventObserver;
93import android.net.INetworkPolicyListener;
94import android.net.INetworkPolicyManager;
95import android.net.INetworkStatsService;
96import android.net.NetworkIdentity;
97import android.net.NetworkInfo;
98import android.net.NetworkPolicy;
99import android.net.NetworkQuotaInfo;
100import android.net.NetworkState;
101import android.net.NetworkTemplate;
102import android.net.wifi.WifiConfiguration;
103import android.net.wifi.WifiInfo;
104import android.net.wifi.WifiManager;
105import android.os.Binder;
106import android.os.Environment;
107import android.os.Handler;
108import android.os.HandlerThread;
109import android.os.INetworkManagementService;
110import android.os.IPowerManager;
111import android.os.Message;
112import android.os.MessageQueue.IdleHandler;
113import android.os.RemoteCallbackList;
114import android.os.RemoteException;
115import android.os.UserHandle;
116import android.os.UserManager;
117import android.provider.Settings;
118import android.telephony.TelephonyManager;
119import android.text.format.Formatter;
120import android.text.format.Time;
121import android.util.AtomicFile;
122import android.util.Log;
123import android.util.NtpTrustedTime;
124import android.util.Slog;
125import android.util.SparseArray;
126import android.util.SparseBooleanArray;
127import android.util.SparseIntArray;
128import android.util.TrustedTime;
129import android.util.Xml;
130
131import com.android.internal.R;
132import com.android.internal.util.FastXmlSerializer;
133import com.android.internal.util.IndentingPrintWriter;
134import com.android.internal.util.Objects;
135import com.google.android.collect.Lists;
136import com.google.android.collect.Maps;
137import com.google.android.collect.Sets;
138
139import org.xmlpull.v1.XmlPullParser;
140import org.xmlpull.v1.XmlPullParserException;
141import org.xmlpull.v1.XmlSerializer;
142
143import java.io.File;
144import java.io.FileDescriptor;
145import java.io.FileInputStream;
146import java.io.FileNotFoundException;
147import java.io.FileOutputStream;
148import java.io.IOException;
149import java.io.PrintWriter;
150import java.net.ProtocolException;
151import java.util.ArrayList;
152import java.util.Arrays;
153import java.util.HashMap;
154import java.util.HashSet;
155import java.util.List;
156import java.util.Map;
157
158import libcore.io.IoUtils;
159
160/**
161 * Service that maintains low-level network policy rules, using
162 * {@link NetworkStatsService} statistics to drive those rules.
163 * <p>
164 * Derives active rules by combining a given policy with other system status,
165 * and delivers to listeners, such as {@link ConnectivityManager}, for
166 * enforcement.
167 */
168public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
169    private static final String TAG = "NetworkPolicy";
170    private static final boolean LOGD = false;
171    private static final boolean LOGV = false;
172
173    private static final int VERSION_INIT = 1;
174    private static final int VERSION_ADDED_SNOOZE = 2;
175    private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
176    private static final int VERSION_ADDED_METERED = 4;
177    private static final int VERSION_SPLIT_SNOOZE = 5;
178    private static final int VERSION_ADDED_TIMEZONE = 6;
179    private static final int VERSION_ADDED_INFERRED = 7;
180    private static final int VERSION_SWITCH_APP_ID = 8;
181    private static final int VERSION_ADDED_NETWORK_ID = 9;
182    private static final int VERSION_LATEST = VERSION_ADDED_NETWORK_ID;
183
184    // @VisibleForTesting
185    public static final int TYPE_WARNING = 0x1;
186    public static final int TYPE_LIMIT = 0x2;
187    public static final int TYPE_LIMIT_SNOOZED = 0x3;
188
189    private static final String TAG_POLICY_LIST = "policy-list";
190    private static final String TAG_NETWORK_POLICY = "network-policy";
191    private static final String TAG_UID_POLICY = "uid-policy";
192    private static final String TAG_APP_POLICY = "app-policy";
193
194    private static final String ATTR_VERSION = "version";
195    private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
196    private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
197    private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
198    private static final String ATTR_NETWORK_ID = "networkId";
199    private static final String ATTR_CYCLE_DAY = "cycleDay";
200    private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
201    private static final String ATTR_WARNING_BYTES = "warningBytes";
202    private static final String ATTR_LIMIT_BYTES = "limitBytes";
203    private static final String ATTR_LAST_SNOOZE = "lastSnooze";
204    private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
205    private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
206    private static final String ATTR_METERED = "metered";
207    private static final String ATTR_INFERRED = "inferred";
208    private static final String ATTR_UID = "uid";
209    private static final String ATTR_APP_ID = "appId";
210    private static final String ATTR_POLICY = "policy";
211
212    private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
213
214    // @VisibleForTesting
215    public static final String ACTION_ALLOW_BACKGROUND =
216            "com.android.server.net.action.ALLOW_BACKGROUND";
217    public static final String ACTION_SNOOZE_WARNING =
218            "com.android.server.net.action.SNOOZE_WARNING";
219
220    private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
221
222    private static final int MSG_RULES_CHANGED = 1;
223    private static final int MSG_METERED_IFACES_CHANGED = 2;
224    private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
225    private static final int MSG_PROCESS_DIED = 4;
226    private static final int MSG_LIMIT_REACHED = 5;
227    private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
228    private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
229    private static final int MSG_SCREEN_ON_CHANGED = 8;
230
231    private final Context mContext;
232    private final IActivityManager mActivityManager;
233    private final IPowerManager mPowerManager;
234    private final INetworkStatsService mNetworkStats;
235    private final INetworkManagementService mNetworkManager;
236    private final TrustedTime mTime;
237
238    private IConnectivityManager mConnManager;
239    private INotificationManager mNotifManager;
240
241    private final Object mRulesLock = new Object();
242
243    private volatile boolean mScreenOn;
244    private volatile boolean mRestrictBackground;
245
246    private final boolean mSuppressDefaultPolicy;
247
248    /** Defined network policies. */
249    private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
250    /** Currently active network rules for ifaces. */
251    private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
252
253    /** Defined app policies. */
254    private SparseIntArray mAppPolicy = new SparseIntArray();
255    /** Currently derived rules for each UID. */
256    private SparseIntArray mUidRules = new SparseIntArray();
257
258    /** Set of ifaces that are metered. */
259    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
260    /** Set of over-limit templates that have been notified. */
261    private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
262
263    /** Set of currently active {@link Notification} tags. */
264    private HashSet<String> mActiveNotifs = Sets.newHashSet();
265
266    /** Foreground at both UID and PID granularity. */
267    private SparseBooleanArray mUidForeground = new SparseBooleanArray();
268    private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
269            SparseBooleanArray>();
270
271    private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
272            INetworkPolicyListener>();
273
274    private final HandlerThread mHandlerThread;
275    private final Handler mHandler;
276
277    private final AtomicFile mPolicyFile;
278
279    // TODO: keep whitelist of system-critical services that should never have
280    // rules enforced, such as system, phone, and radio UIDs.
281
282    // TODO: migrate notifications to SystemUI
283
284    public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
285            IPowerManager powerManager, INetworkStatsService networkStats,
286            INetworkManagementService networkManagement) {
287        this(context, activityManager, powerManager, networkStats, networkManagement,
288                NtpTrustedTime.getInstance(context), getSystemDir(), false);
289    }
290
291    private static File getSystemDir() {
292        return new File(Environment.getDataDirectory(), "system");
293    }
294
295    public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
296            IPowerManager powerManager, INetworkStatsService networkStats,
297            INetworkManagementService networkManagement, TrustedTime time, File systemDir,
298            boolean suppressDefaultPolicy) {
299        mContext = checkNotNull(context, "missing context");
300        mActivityManager = checkNotNull(activityManager, "missing activityManager");
301        mPowerManager = checkNotNull(powerManager, "missing powerManager");
302        mNetworkStats = checkNotNull(networkStats, "missing networkStats");
303        mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
304        mTime = checkNotNull(time, "missing TrustedTime");
305
306        mHandlerThread = new HandlerThread(TAG);
307        mHandlerThread.start();
308        mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
309
310        mSuppressDefaultPolicy = suppressDefaultPolicy;
311
312        mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
313    }
314
315    public void bindConnectivityManager(IConnectivityManager connManager) {
316        mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
317    }
318
319    public void bindNotificationManager(INotificationManager notifManager) {
320        mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
321    }
322
323    public void systemReady() {
324        if (!isBandwidthControlEnabled()) {
325            Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
326            return;
327        }
328
329        synchronized (mRulesLock) {
330            // read policy from disk
331            readPolicyLocked();
332
333            if (mRestrictBackground) {
334                updateRulesForRestrictBackgroundLocked();
335                updateNotificationsLocked();
336            }
337        }
338
339        updateScreenOn();
340
341        try {
342            mActivityManager.registerProcessObserver(mProcessObserver);
343            mNetworkManager.registerObserver(mAlertObserver);
344        } catch (RemoteException e) {
345            // ignored; both services live in system_server
346        }
347
348        // TODO: traverse existing processes to know foreground state, or have
349        // activitymanager dispatch current state when new observer attached.
350
351        final IntentFilter screenFilter = new IntentFilter();
352        screenFilter.addAction(Intent.ACTION_SCREEN_ON);
353        screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
354        mContext.registerReceiver(mScreenReceiver, screenFilter);
355
356        // watch for network interfaces to be claimed
357        final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
358        mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
359
360        // listen for package/uid changes to update policy
361        final IntentFilter packageFilter = new IntentFilter();
362        packageFilter.addAction(ACTION_PACKAGE_ADDED);
363        packageFilter.addAction(ACTION_UID_REMOVED);
364        mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
365
366        // listen for stats update events
367        final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
368        mContext.registerReceiver(
369                mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
370
371        // listen for restrict background changes from notifications
372        final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
373        mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
374
375        // listen for snooze warning from notifications
376        final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
377        mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
378                MANAGE_NETWORK_POLICY, mHandler);
379
380        // listen for configured wifi networks to be removed
381        final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
382        mContext.registerReceiver(
383                mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
384
385        // listen for wifi state changes to catch metered hint
386        final IntentFilter wifiStateFilter = new IntentFilter(
387                WifiManager.NETWORK_STATE_CHANGED_ACTION);
388        mContext.registerReceiver(
389                mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
390
391    }
392
393    private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
394        @Override
395        public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
396            mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
397                    pid, uid, foregroundActivities).sendToTarget();
398        }
399
400        @Override
401        public void onImportanceChanged(int pid, int uid, int importance) {
402        }
403
404        @Override
405        public void onProcessDied(int pid, int uid) {
406            mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
407        }
408    };
409
410    private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
411        @Override
412        public void onReceive(Context context, Intent intent) {
413            synchronized (mRulesLock) {
414                // screen-related broadcasts are protected by system, no need
415                // for permissions check.
416                mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
417            }
418        }
419    };
420
421    private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
422        @Override
423        public void onReceive(Context context, Intent intent) {
424            // on background handler thread, and PACKAGE_ADDED and UID_REMOVED
425            // are protected broadcasts.
426
427            final String action = intent.getAction();
428            final int uid = intent.getIntExtra(EXTRA_UID, 0);
429            final int appId = UserHandle.getAppId(uid);
430            synchronized (mRulesLock) {
431                if (ACTION_PACKAGE_ADDED.equals(action)) {
432                    // NOTE: PACKAGE_ADDED is currently only sent once, and is
433                    // not broadcast when users are added.
434
435                    // update rules for UID, since it might be subject to
436                    // global background data policy.
437                    if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
438                    updateRulesForAppLocked(appId);
439
440                } else if (ACTION_UID_REMOVED.equals(action)) {
441                    // NOTE: UID_REMOVED is currently only sent once, and is not
442                    // broadcast when users are removed.
443
444                    // remove any policy and update rules to clean up.
445                    if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
446
447                    mAppPolicy.delete(appId);
448                    updateRulesForAppLocked(appId);
449                    writePolicyLocked();
450                }
451            }
452        }
453    };
454
455    /**
456     * Receiver that watches for {@link INetworkStatsService} updates, which we
457     * use to check against {@link NetworkPolicy#warningBytes}.
458     */
459    private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
460        @Override
461        public void onReceive(Context context, Intent intent) {
462            // on background handler thread, and verified
463            // READ_NETWORK_USAGE_HISTORY permission above.
464
465            maybeRefreshTrustedTime();
466            synchronized (mRulesLock) {
467                updateNetworkEnabledLocked();
468                updateNotificationsLocked();
469            }
470        }
471    };
472
473    /**
474     * Receiver that watches for {@link Notification} control of
475     * {@link #mRestrictBackground}.
476     */
477    private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
478        @Override
479        public void onReceive(Context context, Intent intent) {
480            // on background handler thread, and verified MANAGE_NETWORK_POLICY
481            // permission above.
482
483            setRestrictBackground(false);
484        }
485    };
486
487    /**
488     * Receiver that watches for {@link Notification} control of
489     * {@link NetworkPolicy#lastWarningSnooze}.
490     */
491    private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
492        @Override
493        public void onReceive(Context context, Intent intent) {
494            // on background handler thread, and verified MANAGE_NETWORK_POLICY
495            // permission above.
496
497            final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
498            performSnooze(template, TYPE_WARNING);
499        }
500    };
501
502    /**
503     * Receiver that watches for {@link WifiConfiguration} to be changed.
504     */
505    private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
506        @Override
507        public void onReceive(Context context, Intent intent) {
508            // on background handler thread, and verified CONNECTIVITY_INTERNAL
509            // permission above.
510
511            final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
512            if (reason == CHANGE_REASON_REMOVED) {
513                final WifiConfiguration config = intent.getParcelableExtra(
514                        EXTRA_WIFI_CONFIGURATION);
515                if (config.SSID != null) {
516                    final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
517                            removeDoubleQuotes(config.SSID));
518                    synchronized (mRulesLock) {
519                        if (mNetworkPolicy.containsKey(template)) {
520                            mNetworkPolicy.remove(template);
521                            writePolicyLocked();
522                        }
523                    }
524                }
525            }
526        }
527    };
528
529    /**
530     * Receiver that watches {@link WifiInfo} state changes to infer metered
531     * state. Ignores hints when policy is user-defined.
532     */
533    private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
534        @Override
535        public void onReceive(Context context, Intent intent) {
536            // on background handler thread, and verified CONNECTIVITY_INTERNAL
537            // permission above.
538
539            // ignore when not connected
540            final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
541            if (!netInfo.isConnected()) return;
542
543            final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
544            final boolean meteredHint = info.getMeteredHint();
545
546            final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
547                    removeDoubleQuotes(info.getSSID()));
548            synchronized (mRulesLock) {
549                NetworkPolicy policy = mNetworkPolicy.get(template);
550                if (policy == null && meteredHint) {
551                    // policy doesn't exist, and AP is hinting that it's
552                    // metered: create an inferred policy.
553                    policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
554                            WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
555                            meteredHint, true);
556                    addNetworkPolicyLocked(policy);
557
558                } else if (policy != null && policy.inferred) {
559                    // policy exists, and was inferred: update its current
560                    // metered state.
561                    policy.metered = meteredHint;
562
563                    // since this is inferred for each wifi session, just update
564                    // rules without persisting.
565                    updateNetworkRulesLocked();
566                }
567            }
568        }
569    };
570
571    /**
572     * Observer that watches for {@link INetworkManagementService} alerts.
573     */
574    private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
575        @Override
576        public void limitReached(String limitName, String iface) {
577            // only someone like NMS should be calling us
578            mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
579
580            if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
581                mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
582            }
583        }
584    };
585
586    /**
587     * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
588     * to show visible notifications as needed.
589     */
590    private void updateNotificationsLocked() {
591        if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
592
593        // keep track of previously active notifications
594        final HashSet<String> beforeNotifs = Sets.newHashSet();
595        beforeNotifs.addAll(mActiveNotifs);
596        mActiveNotifs.clear();
597
598        // TODO: when switching to kernel notifications, compute next future
599        // cycle boundary to recompute notifications.
600
601        // examine stats for each active policy
602        final long currentTime = currentTimeMillis();
603        for (NetworkPolicy policy : mNetworkPolicy.values()) {
604            // ignore policies that aren't relevant to user
605            if (!isTemplateRelevant(policy.template)) continue;
606            if (!policy.hasCycle()) continue;
607
608            final long start = computeLastCycleBoundary(currentTime, policy);
609            final long end = currentTime;
610            final long totalBytes = getTotalBytes(policy.template, start, end);
611
612            if (policy.isOverLimit(totalBytes)) {
613                if (policy.lastLimitSnooze >= start) {
614                    enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
615                } else {
616                    enqueueNotification(policy, TYPE_LIMIT, totalBytes);
617                    notifyOverLimitLocked(policy.template);
618                }
619
620            } else {
621                notifyUnderLimitLocked(policy.template);
622
623                if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
624                    enqueueNotification(policy, TYPE_WARNING, totalBytes);
625                }
626            }
627        }
628
629        // ongoing notification when restricting background data
630        if (mRestrictBackground) {
631            enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
632        }
633
634        // cancel stale notifications that we didn't renew above
635        for (String tag : beforeNotifs) {
636            if (!mActiveNotifs.contains(tag)) {
637                cancelNotification(tag);
638            }
639        }
640    }
641
642    /**
643     * Test if given {@link NetworkTemplate} is relevant to user based on
644     * current device state, such as when
645     * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
646     * data connection status.
647     */
648    private boolean isTemplateRelevant(NetworkTemplate template) {
649        final TelephonyManager tele = TelephonyManager.from(mContext);
650
651        switch (template.getMatchRule()) {
652            case MATCH_MOBILE_3G_LOWER:
653            case MATCH_MOBILE_4G:
654            case MATCH_MOBILE_ALL:
655                // mobile templates are relevant when SIM is ready and
656                // subscriberId matches.
657                if (tele.getSimState() == SIM_STATE_READY) {
658                    return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
659                } else {
660                    return false;
661                }
662        }
663        return true;
664    }
665
666    /**
667     * Notify that given {@link NetworkTemplate} is over
668     * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
669     */
670    private void notifyOverLimitLocked(NetworkTemplate template) {
671        if (!mOverLimitNotified.contains(template)) {
672            mContext.startActivity(buildNetworkOverLimitIntent(template));
673            mOverLimitNotified.add(template);
674        }
675    }
676
677    private void notifyUnderLimitLocked(NetworkTemplate template) {
678        mOverLimitNotified.remove(template);
679    }
680
681    /**
682     * Build unique tag that identifies an active {@link NetworkPolicy}
683     * notification of a specific type, like {@link #TYPE_LIMIT}.
684     */
685    private String buildNotificationTag(NetworkPolicy policy, int type) {
686        return TAG + ":" + policy.template.hashCode() + ":" + type;
687    }
688
689    /**
690     * Show notification for combined {@link NetworkPolicy} and specific type,
691     * like {@link #TYPE_LIMIT}. Okay to call multiple times.
692     */
693    private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
694        final String tag = buildNotificationTag(policy, type);
695        final Notification.Builder builder = new Notification.Builder(mContext);
696        builder.setOnlyAlertOnce(true);
697        builder.setWhen(0L);
698
699        final Resources res = mContext.getResources();
700        switch (type) {
701            case TYPE_WARNING: {
702                final CharSequence title = res.getText(R.string.data_usage_warning_title);
703                final CharSequence body = res.getString(R.string.data_usage_warning_body);
704
705                builder.setSmallIcon(R.drawable.stat_notify_error);
706                builder.setTicker(title);
707                builder.setContentTitle(title);
708                builder.setContentText(body);
709
710                final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
711                builder.setDeleteIntent(PendingIntent.getBroadcast(
712                        mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
713
714                final Intent viewIntent = buildViewDataUsageIntent(policy.template);
715                builder.setContentIntent(PendingIntent.getActivity(
716                        mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
717
718                break;
719            }
720            case TYPE_LIMIT: {
721                final CharSequence body = res.getText(R.string.data_usage_limit_body);
722
723                final CharSequence title;
724                switch (policy.template.getMatchRule()) {
725                    case MATCH_MOBILE_3G_LOWER:
726                        title = res.getText(R.string.data_usage_3g_limit_title);
727                        break;
728                    case MATCH_MOBILE_4G:
729                        title = res.getText(R.string.data_usage_4g_limit_title);
730                        break;
731                    case MATCH_MOBILE_ALL:
732                        title = res.getText(R.string.data_usage_mobile_limit_title);
733                        break;
734                    case MATCH_WIFI:
735                        title = res.getText(R.string.data_usage_wifi_limit_title);
736                        break;
737                    default:
738                        title = null;
739                        break;
740                }
741
742                builder.setOngoing(true);
743                builder.setSmallIcon(R.drawable.stat_notify_disabled);
744                builder.setTicker(title);
745                builder.setContentTitle(title);
746                builder.setContentText(body);
747
748                final Intent intent = buildNetworkOverLimitIntent(policy.template);
749                builder.setContentIntent(PendingIntent.getActivity(
750                        mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
751                break;
752            }
753            case TYPE_LIMIT_SNOOZED: {
754                final long overBytes = totalBytes - policy.limitBytes;
755                final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
756                        Formatter.formatFileSize(mContext, overBytes));
757
758                final CharSequence title;
759                switch (policy.template.getMatchRule()) {
760                    case MATCH_MOBILE_3G_LOWER:
761                        title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
762                        break;
763                    case MATCH_MOBILE_4G:
764                        title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
765                        break;
766                    case MATCH_MOBILE_ALL:
767                        title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
768                        break;
769                    case MATCH_WIFI:
770                        title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
771                        break;
772                    default:
773                        title = null;
774                        break;
775                }
776
777                builder.setOngoing(true);
778                builder.setSmallIcon(R.drawable.stat_notify_error);
779                builder.setTicker(title);
780                builder.setContentTitle(title);
781                builder.setContentText(body);
782
783                final Intent intent = buildViewDataUsageIntent(policy.template);
784                builder.setContentIntent(PendingIntent.getActivity(
785                        mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
786                break;
787            }
788        }
789
790        // TODO: move to NotificationManager once we can mock it
791        try {
792            final String packageName = mContext.getPackageName();
793            final int[] idReceived = new int[1];
794            mNotifManager.enqueueNotificationWithTag(
795                    packageName, tag, 0x0, builder.getNotification(), idReceived);
796            mActiveNotifs.add(tag);
797        } catch (RemoteException e) {
798            // ignored; service lives in system_server
799        }
800    }
801
802    /**
803     * Show ongoing notification to reflect that {@link #mRestrictBackground}
804     * has been enabled.
805     */
806    private void enqueueRestrictedNotification(String tag) {
807        final Resources res = mContext.getResources();
808        final Notification.Builder builder = new Notification.Builder(mContext);
809
810        final CharSequence title = res.getText(R.string.data_usage_restricted_title);
811        final CharSequence body = res.getString(R.string.data_usage_restricted_body);
812
813        builder.setOnlyAlertOnce(true);
814        builder.setOngoing(true);
815        builder.setSmallIcon(R.drawable.stat_notify_error);
816        builder.setTicker(title);
817        builder.setContentTitle(title);
818        builder.setContentText(body);
819
820        final Intent intent = buildAllowBackgroundDataIntent();
821        builder.setContentIntent(
822                PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
823
824        // TODO: move to NotificationManager once we can mock it
825        try {
826            final String packageName = mContext.getPackageName();
827            final int[] idReceived = new int[1];
828            mNotifManager.enqueueNotificationWithTag(packageName, tag,
829                    0x0, builder.getNotification(), idReceived);
830            mActiveNotifs.add(tag);
831        } catch (RemoteException e) {
832            // ignored; service lives in system_server
833        }
834    }
835
836    private void cancelNotification(String tag) {
837        // TODO: move to NotificationManager once we can mock it
838        try {
839            final String packageName = mContext.getPackageName();
840            mNotifManager.cancelNotificationWithTag(
841                    packageName, tag, 0x0);
842        } catch (RemoteException e) {
843            // ignored; service lives in system_server
844        }
845    }
846
847    /**
848     * Receiver that watches for {@link IConnectivityManager} to claim network
849     * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
850     */
851    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
852        @Override
853        public void onReceive(Context context, Intent intent) {
854            // on background handler thread, and verified CONNECTIVITY_INTERNAL
855            // permission above.
856
857            maybeRefreshTrustedTime();
858            synchronized (mRulesLock) {
859                ensureActiveMobilePolicyLocked();
860                updateNetworkEnabledLocked();
861                updateNetworkRulesLocked();
862                updateNotificationsLocked();
863            }
864        }
865    };
866
867    /**
868     * Proactively control network data connections when they exceed
869     * {@link NetworkPolicy#limitBytes}.
870     */
871    private void updateNetworkEnabledLocked() {
872        if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
873
874        // TODO: reset any policy-disabled networks when any policy is removed
875        // completely, which is currently rare case.
876
877        final long currentTime = currentTimeMillis();
878        for (NetworkPolicy policy : mNetworkPolicy.values()) {
879            // shortcut when policy has no limit
880            if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
881                setNetworkTemplateEnabled(policy.template, true);
882                continue;
883            }
884
885            final long start = computeLastCycleBoundary(currentTime, policy);
886            final long end = currentTime;
887            final long totalBytes = getTotalBytes(policy.template, start, end);
888
889            // disable data connection when over limit and not snoozed
890            final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
891                    && policy.lastLimitSnooze < start;
892            final boolean networkEnabled = !overLimitWithoutSnooze;
893
894            setNetworkTemplateEnabled(policy.template, networkEnabled);
895        }
896    }
897
898    /**
899     * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
900     * for the given {@link NetworkTemplate}.
901     */
902    private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
903        final TelephonyManager tele = TelephonyManager.from(mContext);
904
905        switch (template.getMatchRule()) {
906            case MATCH_MOBILE_3G_LOWER:
907            case MATCH_MOBILE_4G:
908            case MATCH_MOBILE_ALL:
909                // TODO: offer more granular control over radio states once
910                // 4965893 is available.
911                if (tele.getSimState() == SIM_STATE_READY
912                        && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
913                    setPolicyDataEnable(TYPE_MOBILE, enabled);
914                    setPolicyDataEnable(TYPE_WIMAX, enabled);
915                }
916                break;
917            case MATCH_WIFI:
918                setPolicyDataEnable(TYPE_WIFI, enabled);
919                break;
920            case MATCH_ETHERNET:
921                setPolicyDataEnable(TYPE_ETHERNET, enabled);
922                break;
923            default:
924                throw new IllegalArgumentException("unexpected template");
925        }
926    }
927
928    /**
929     * Examine all connected {@link NetworkState}, looking for
930     * {@link NetworkPolicy} that need to be enforced. When matches found, set
931     * remaining quota based on usage cycle and historical stats.
932     */
933    private void updateNetworkRulesLocked() {
934        if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
935
936        final NetworkState[] states;
937        try {
938            states = mConnManager.getAllNetworkState();
939        } catch (RemoteException e) {
940            // ignored; service lives in system_server
941            return;
942        }
943
944        // first, derive identity for all connected networks, which can be used
945        // to match against templates.
946        final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
947        for (NetworkState state : states) {
948            // stash identity and iface away for later use
949            if (state.networkInfo.isConnected()) {
950                final String iface = state.linkProperties.getInterfaceName();
951                final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
952                networks.put(ident, iface);
953            }
954        }
955
956        // build list of rules and ifaces to enforce them against
957        mNetworkRules.clear();
958        final ArrayList<String> ifaceList = Lists.newArrayList();
959        for (NetworkPolicy policy : mNetworkPolicy.values()) {
960
961            // collect all active ifaces that match this template
962            ifaceList.clear();
963            for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
964                final NetworkIdentity ident = entry.getKey();
965                if (policy.template.matches(ident)) {
966                    final String iface = entry.getValue();
967                    ifaceList.add(iface);
968                }
969            }
970
971            if (ifaceList.size() > 0) {
972                final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
973                mNetworkRules.put(policy, ifaces);
974            }
975        }
976
977        long lowestRule = Long.MAX_VALUE;
978        final HashSet<String> newMeteredIfaces = Sets.newHashSet();
979
980        // apply each policy that we found ifaces for; compute remaining data
981        // based on current cycle and historical stats, and push to kernel.
982        final long currentTime = currentTimeMillis();
983        for (NetworkPolicy policy : mNetworkRules.keySet()) {
984            final String[] ifaces = mNetworkRules.get(policy);
985
986            final long start;
987            final long totalBytes;
988            if (policy.hasCycle()) {
989                start = computeLastCycleBoundary(currentTime, policy);
990                totalBytes = getTotalBytes(policy.template, start, currentTime);
991            } else {
992                start = Long.MAX_VALUE;
993                totalBytes = 0;
994            }
995
996            if (LOGD) {
997                Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
998                        + Arrays.toString(ifaces));
999            }
1000
1001            final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
1002            final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
1003            if (hasLimit || policy.metered) {
1004                final long quotaBytes;
1005                if (!hasLimit) {
1006                    // metered network, but no policy limit; we still need to
1007                    // restrict apps, so push really high quota.
1008                    quotaBytes = Long.MAX_VALUE;
1009                } else if (policy.lastLimitSnooze >= start) {
1010                    // snoozing past quota, but we still need to restrict apps,
1011                    // so push really high quota.
1012                    quotaBytes = Long.MAX_VALUE;
1013                } else {
1014                    // remaining "quota" bytes are based on total usage in
1015                    // current cycle. kernel doesn't like 0-byte rules, so we
1016                    // set 1-byte quota and disable the radio later.
1017                    quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1018                }
1019
1020                if (ifaces.length > 1) {
1021                    // TODO: switch to shared quota once NMS supports
1022                    Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
1023                }
1024
1025                for (String iface : ifaces) {
1026                    removeInterfaceQuota(iface);
1027                    setInterfaceQuota(iface, quotaBytes);
1028                    newMeteredIfaces.add(iface);
1029                }
1030            }
1031
1032            // keep track of lowest warning or limit of active policies
1033            if (hasWarning && policy.warningBytes < lowestRule) {
1034                lowestRule = policy.warningBytes;
1035            }
1036            if (hasLimit && policy.limitBytes < lowestRule) {
1037                lowestRule = policy.limitBytes;
1038            }
1039        }
1040
1041        mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
1042
1043        // remove quota on any trailing interfaces
1044        for (String iface : mMeteredIfaces) {
1045            if (!newMeteredIfaces.contains(iface)) {
1046                removeInterfaceQuota(iface);
1047            }
1048        }
1049        mMeteredIfaces = newMeteredIfaces;
1050
1051        final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
1052        mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
1053    }
1054
1055    /**
1056     * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1057     * have at least a default mobile policy defined.
1058     */
1059    private void ensureActiveMobilePolicyLocked() {
1060        if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
1061        if (mSuppressDefaultPolicy) return;
1062
1063        final TelephonyManager tele = TelephonyManager.from(mContext);
1064
1065        // avoid creating policy when SIM isn't ready
1066        if (tele.getSimState() != SIM_STATE_READY) return;
1067
1068        final String subscriberId = tele.getSubscriberId();
1069        final NetworkIdentity probeIdent = new NetworkIdentity(
1070                TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1071
1072        // examine to see if any policy is defined for active mobile
1073        boolean mobileDefined = false;
1074        for (NetworkPolicy policy : mNetworkPolicy.values()) {
1075            if (policy.template.matches(probeIdent)) {
1076                mobileDefined = true;
1077            }
1078        }
1079
1080        if (!mobileDefined) {
1081            Slog.i(TAG, "no policy for active mobile network; generating default policy");
1082
1083            // build default mobile policy, and assume usage cycle starts today
1084            final long warningBytes = mContext.getResources().getInteger(
1085                    com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1086                    * MB_IN_BYTES;
1087
1088            final Time time = new Time();
1089            time.setToNow();
1090
1091            final int cycleDay = time.monthDay;
1092            final String cycleTimezone = time.timezone;
1093
1094            final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1095            final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1096                    warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1097            addNetworkPolicyLocked(policy);
1098        }
1099    }
1100
1101    private void readPolicyLocked() {
1102        if (LOGV) Slog.v(TAG, "readPolicyLocked()");
1103
1104        // clear any existing policy and read from disk
1105        mNetworkPolicy.clear();
1106        mAppPolicy.clear();
1107
1108        FileInputStream fis = null;
1109        try {
1110            fis = mPolicyFile.openRead();
1111            final XmlPullParser in = Xml.newPullParser();
1112            in.setInput(fis, null);
1113
1114            int type;
1115            int version = VERSION_INIT;
1116            while ((type = in.next()) != END_DOCUMENT) {
1117                final String tag = in.getName();
1118                if (type == START_TAG) {
1119                    if (TAG_POLICY_LIST.equals(tag)) {
1120                        version = readIntAttribute(in, ATTR_VERSION);
1121                        if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1122                            mRestrictBackground = readBooleanAttribute(
1123                                    in, ATTR_RESTRICT_BACKGROUND);
1124                        } else {
1125                            mRestrictBackground = false;
1126                        }
1127
1128                    } else if (TAG_NETWORK_POLICY.equals(tag)) {
1129                        final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1130                        final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
1131                        final String networkId;
1132                        if (version >= VERSION_ADDED_NETWORK_ID) {
1133                            networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1134                        } else {
1135                            networkId = null;
1136                        }
1137                        final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1138                        final String cycleTimezone;
1139                        if (version >= VERSION_ADDED_TIMEZONE) {
1140                            cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1141                        } else {
1142                            cycleTimezone = Time.TIMEZONE_UTC;
1143                        }
1144                        final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1145                        final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
1146                        final long lastLimitSnooze;
1147                        if (version >= VERSION_SPLIT_SNOOZE) {
1148                            lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1149                        } else if (version >= VERSION_ADDED_SNOOZE) {
1150                            lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
1151                        } else {
1152                            lastLimitSnooze = SNOOZE_NEVER;
1153                        }
1154                        final boolean metered;
1155                        if (version >= VERSION_ADDED_METERED) {
1156                            metered = readBooleanAttribute(in, ATTR_METERED);
1157                        } else {
1158                            switch (networkTemplate) {
1159                                case MATCH_MOBILE_3G_LOWER:
1160                                case MATCH_MOBILE_4G:
1161                                case MATCH_MOBILE_ALL:
1162                                    metered = true;
1163                                    break;
1164                                default:
1165                                    metered = false;
1166                            }
1167                        }
1168                        final long lastWarningSnooze;
1169                        if (version >= VERSION_SPLIT_SNOOZE) {
1170                            lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1171                        } else {
1172                            lastWarningSnooze = SNOOZE_NEVER;
1173                        }
1174                        final boolean inferred;
1175                        if (version >= VERSION_ADDED_INFERRED) {
1176                            inferred = readBooleanAttribute(in, ATTR_INFERRED);
1177                        } else {
1178                            inferred = false;
1179                        }
1180
1181                        final NetworkTemplate template = new NetworkTemplate(
1182                                networkTemplate, subscriberId, networkId);
1183                        mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1184                                cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1185                                lastLimitSnooze, metered, inferred));
1186
1187                    } else if (TAG_UID_POLICY.equals(tag) && version < VERSION_SWITCH_APP_ID) {
1188                        final int uid = readIntAttribute(in, ATTR_UID);
1189                        final int policy = readIntAttribute(in, ATTR_POLICY);
1190
1191                        final int appId = UserHandle.getAppId(uid);
1192                        if (UserHandle.isApp(appId)) {
1193                            setAppPolicyUnchecked(appId, policy, false);
1194                        } else {
1195                            Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1196                        }
1197                    } else if (TAG_APP_POLICY.equals(tag) && version >= VERSION_SWITCH_APP_ID) {
1198                        final int appId = readIntAttribute(in, ATTR_APP_ID);
1199                        final int policy = readIntAttribute(in, ATTR_POLICY);
1200
1201                        if (UserHandle.isApp(appId)) {
1202                            setAppPolicyUnchecked(appId, policy, false);
1203                        } else {
1204                            Slog.w(TAG, "unable to apply policy to appId " + appId + "; ignoring");
1205                        }
1206                    }
1207                }
1208            }
1209
1210        } catch (FileNotFoundException e) {
1211            // missing policy is okay, probably first boot
1212            upgradeLegacyBackgroundData();
1213        } catch (IOException e) {
1214            Log.wtf(TAG, "problem reading network policy", e);
1215        } catch (XmlPullParserException e) {
1216            Log.wtf(TAG, "problem reading network policy", e);
1217        } finally {
1218            IoUtils.closeQuietly(fis);
1219        }
1220    }
1221
1222    /**
1223     * Upgrade legacy background data flags, notifying listeners of one last
1224     * change to always-true.
1225     */
1226    private void upgradeLegacyBackgroundData() {
1227        mRestrictBackground = Settings.Secure.getInt(
1228                mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1229
1230        // kick off one last broadcast if restricted
1231        if (mRestrictBackground) {
1232            final Intent broadcast = new Intent(
1233                    ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1234            mContext.sendBroadcast(broadcast);
1235        }
1236    }
1237
1238    private void writePolicyLocked() {
1239        if (LOGV) Slog.v(TAG, "writePolicyLocked()");
1240
1241        FileOutputStream fos = null;
1242        try {
1243            fos = mPolicyFile.startWrite();
1244
1245            XmlSerializer out = new FastXmlSerializer();
1246            out.setOutput(fos, "utf-8");
1247            out.startDocument(null, true);
1248
1249            out.startTag(null, TAG_POLICY_LIST);
1250            writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
1251            writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
1252
1253            // write all known network policies
1254            for (NetworkPolicy policy : mNetworkPolicy.values()) {
1255                final NetworkTemplate template = policy.template;
1256
1257                out.startTag(null, TAG_NETWORK_POLICY);
1258                writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1259                final String subscriberId = template.getSubscriberId();
1260                if (subscriberId != null) {
1261                    out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
1262                }
1263                final String networkId = template.getNetworkId();
1264                if (networkId != null) {
1265                    out.attribute(null, ATTR_NETWORK_ID, networkId);
1266                }
1267                writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
1268                out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
1269                writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1270                writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
1271                writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1272                writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
1273                writeBooleanAttribute(out, ATTR_METERED, policy.metered);
1274                writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
1275                out.endTag(null, TAG_NETWORK_POLICY);
1276            }
1277
1278            // write all known uid policies
1279            for (int i = 0; i < mAppPolicy.size(); i++) {
1280                final int appId = mAppPolicy.keyAt(i);
1281                final int policy = mAppPolicy.valueAt(i);
1282
1283                // skip writing empty policies
1284                if (policy == POLICY_NONE) continue;
1285
1286                out.startTag(null, TAG_APP_POLICY);
1287                writeIntAttribute(out, ATTR_APP_ID, appId);
1288                writeIntAttribute(out, ATTR_POLICY, policy);
1289                out.endTag(null, TAG_APP_POLICY);
1290            }
1291
1292            out.endTag(null, TAG_POLICY_LIST);
1293            out.endDocument();
1294
1295            mPolicyFile.finishWrite(fos);
1296        } catch (IOException e) {
1297            if (fos != null) {
1298                mPolicyFile.failWrite(fos);
1299            }
1300        }
1301    }
1302
1303    @Override
1304    public void setAppPolicy(int appId, int policy) {
1305        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1306
1307        if (!UserHandle.isApp(appId)) {
1308            throw new IllegalArgumentException("cannot apply policy to appId " + appId);
1309        }
1310
1311        setAppPolicyUnchecked(appId, policy, true);
1312    }
1313
1314    private void setAppPolicyUnchecked(int appId, int policy, boolean persist) {
1315        final int oldPolicy;
1316        synchronized (mRulesLock) {
1317            oldPolicy = getAppPolicy(appId);
1318            mAppPolicy.put(appId, policy);
1319
1320            // uid policy changed, recompute rules and persist policy.
1321            updateRulesForAppLocked(appId);
1322            if (persist) {
1323                writePolicyLocked();
1324            }
1325        }
1326    }
1327
1328    @Override
1329    public int getAppPolicy(int appId) {
1330        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1331
1332        synchronized (mRulesLock) {
1333            return mAppPolicy.get(appId, POLICY_NONE);
1334        }
1335    }
1336
1337    @Override
1338    public int[] getAppsWithPolicy(int policy) {
1339        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1340
1341        int[] appIds = new int[0];
1342        synchronized (mRulesLock) {
1343            for (int i = 0; i < mAppPolicy.size(); i++) {
1344                final int appId = mAppPolicy.keyAt(i);
1345                final int appPolicy = mAppPolicy.valueAt(i);
1346                if (appPolicy == policy) {
1347                    appIds = appendInt(appIds, appId);
1348                }
1349            }
1350        }
1351        return appIds;
1352    }
1353
1354    @Override
1355    public void registerListener(INetworkPolicyListener listener) {
1356        // TODO: create permission for observing network policy
1357        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1358
1359        mListeners.register(listener);
1360
1361        // TODO: consider dispatching existing rules to new listeners
1362    }
1363
1364    @Override
1365    public void unregisterListener(INetworkPolicyListener listener) {
1366        // TODO: create permission for observing network policy
1367        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1368
1369        mListeners.unregister(listener);
1370    }
1371
1372    @Override
1373    public void setNetworkPolicies(NetworkPolicy[] policies) {
1374        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1375
1376        maybeRefreshTrustedTime();
1377        synchronized (mRulesLock) {
1378            mNetworkPolicy.clear();
1379            for (NetworkPolicy policy : policies) {
1380                mNetworkPolicy.put(policy.template, policy);
1381            }
1382
1383            updateNetworkEnabledLocked();
1384            updateNetworkRulesLocked();
1385            updateNotificationsLocked();
1386            writePolicyLocked();
1387        }
1388    }
1389
1390    private void addNetworkPolicyLocked(NetworkPolicy policy) {
1391        mNetworkPolicy.put(policy.template, policy);
1392
1393        updateNetworkEnabledLocked();
1394        updateNetworkRulesLocked();
1395        updateNotificationsLocked();
1396        writePolicyLocked();
1397    }
1398
1399    @Override
1400    public NetworkPolicy[] getNetworkPolicies() {
1401        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1402        mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
1403
1404        synchronized (mRulesLock) {
1405            return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1406        }
1407    }
1408
1409    @Override
1410    public void snoozeLimit(NetworkTemplate template) {
1411        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1412
1413        final long token = Binder.clearCallingIdentity();
1414        try {
1415            performSnooze(template, TYPE_LIMIT);
1416        } finally {
1417            Binder.restoreCallingIdentity(token);
1418        }
1419    }
1420
1421    private void performSnooze(NetworkTemplate template, int type) {
1422        maybeRefreshTrustedTime();
1423        final long currentTime = currentTimeMillis();
1424        synchronized (mRulesLock) {
1425            // find and snooze local policy that matches
1426            final NetworkPolicy policy = mNetworkPolicy.get(template);
1427            if (policy == null) {
1428                throw new IllegalArgumentException("unable to find policy for " + template);
1429            }
1430
1431            switch (type) {
1432                case TYPE_WARNING:
1433                    policy.lastWarningSnooze = currentTime;
1434                    break;
1435                case TYPE_LIMIT:
1436                    policy.lastLimitSnooze = currentTime;
1437                    break;
1438                default:
1439                    throw new IllegalArgumentException("unexpected type");
1440            }
1441
1442            updateNetworkEnabledLocked();
1443            updateNetworkRulesLocked();
1444            updateNotificationsLocked();
1445            writePolicyLocked();
1446        }
1447    }
1448
1449    @Override
1450    public void setRestrictBackground(boolean restrictBackground) {
1451        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1452
1453        maybeRefreshTrustedTime();
1454        synchronized (mRulesLock) {
1455            mRestrictBackground = restrictBackground;
1456            updateRulesForRestrictBackgroundLocked();
1457            updateNotificationsLocked();
1458            writePolicyLocked();
1459        }
1460
1461        mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1462                .sendToTarget();
1463    }
1464
1465    @Override
1466    public boolean getRestrictBackground() {
1467        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1468
1469        synchronized (mRulesLock) {
1470            return mRestrictBackground;
1471        }
1472    }
1473
1474    private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1475        for (NetworkPolicy policy : mNetworkPolicy.values()) {
1476            if (policy.template.matches(ident)) {
1477                return policy;
1478            }
1479        }
1480        return null;
1481    }
1482
1483    @Override
1484    public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1485        mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1486
1487        // only returns usage summary, so we don't require caller to have
1488        // READ_NETWORK_USAGE_HISTORY.
1489        final long token = Binder.clearCallingIdentity();
1490        try {
1491            return getNetworkQuotaInfoUnchecked(state);
1492        } finally {
1493            Binder.restoreCallingIdentity(token);
1494        }
1495    }
1496
1497    private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1498        final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1499
1500        final NetworkPolicy policy;
1501        synchronized (mRulesLock) {
1502            policy = findPolicyForNetworkLocked(ident);
1503        }
1504
1505        if (policy == null || !policy.hasCycle()) {
1506            // missing policy means we can't derive useful quota info
1507            return null;
1508        }
1509
1510        final long currentTime = currentTimeMillis();
1511
1512        // find total bytes used under policy
1513        final long start = computeLastCycleBoundary(currentTime, policy);
1514        final long end = currentTime;
1515        final long totalBytes = getTotalBytes(policy.template, start, end);
1516
1517        // report soft and hard limits under policy
1518        final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1519                : NetworkQuotaInfo.NO_LIMIT;
1520        final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1521                : NetworkQuotaInfo.NO_LIMIT;
1522
1523        return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1524    }
1525
1526    @Override
1527    public boolean isNetworkMetered(NetworkState state) {
1528        final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1529
1530        // roaming networks are always considered metered
1531        if (ident.getRoaming()) {
1532            return true;
1533        }
1534
1535        final NetworkPolicy policy;
1536        synchronized (mRulesLock) {
1537            policy = findPolicyForNetworkLocked(ident);
1538        }
1539
1540        if (policy != null) {
1541            return policy.metered;
1542        } else {
1543            final int type = state.networkInfo.getType();
1544            if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1545                return true;
1546            }
1547            return false;
1548        }
1549    }
1550
1551    @Override
1552    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1553        mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1554
1555        final IndentingPrintWriter fout = new IndentingPrintWriter(writer, "  ");
1556
1557        final HashSet<String> argSet = new HashSet<String>();
1558        for (String arg : args) {
1559            argSet.add(arg);
1560        }
1561
1562        synchronized (mRulesLock) {
1563            if (argSet.contains("--unsnooze")) {
1564                for (NetworkPolicy policy : mNetworkPolicy.values()) {
1565                    policy.clearSnooze();
1566                }
1567
1568                updateNetworkEnabledLocked();
1569                updateNetworkRulesLocked();
1570                updateNotificationsLocked();
1571                writePolicyLocked();
1572
1573                fout.println("Cleared snooze timestamps");
1574                return;
1575            }
1576
1577            fout.print("Restrict background: "); fout.println(mRestrictBackground);
1578            fout.println("Network policies:");
1579            fout.increaseIndent();
1580            for (NetworkPolicy policy : mNetworkPolicy.values()) {
1581                fout.println(policy.toString());
1582            }
1583            fout.decreaseIndent();
1584
1585            fout.println("Policy for apps:");
1586            fout.increaseIndent();
1587            int size = mAppPolicy.size();
1588            for (int i = 0; i < size; i++) {
1589                final int appId = mAppPolicy.keyAt(i);
1590                final int policy = mAppPolicy.valueAt(i);
1591                fout.print("appId=");
1592                fout.print(appId);
1593                fout.print(" policy=");
1594                dumpPolicy(fout, policy);
1595                fout.println();
1596            }
1597            fout.decreaseIndent();
1598
1599            final SparseBooleanArray knownUids = new SparseBooleanArray();
1600            collectKeys(mUidForeground, knownUids);
1601            collectKeys(mUidRules, knownUids);
1602
1603            fout.println("Status for known UIDs:");
1604            fout.increaseIndent();
1605            size = knownUids.size();
1606            for (int i = 0; i < size; i++) {
1607                final int uid = knownUids.keyAt(i);
1608                fout.print("UID=");
1609                fout.print(uid);
1610
1611                fout.print(" foreground=");
1612                final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1613                if (foregroundIndex < 0) {
1614                    fout.print("UNKNOWN");
1615                } else {
1616                    dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1617                }
1618
1619                fout.print(" rules=");
1620                final int rulesIndex = mUidRules.indexOfKey(uid);
1621                if (rulesIndex < 0) {
1622                    fout.print("UNKNOWN");
1623                } else {
1624                    dumpRules(fout, mUidRules.valueAt(rulesIndex));
1625                }
1626
1627                fout.println();
1628            }
1629            fout.decreaseIndent();
1630        }
1631    }
1632
1633    @Override
1634    public boolean isUidForeground(int uid) {
1635        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1636
1637        synchronized (mRulesLock) {
1638            // only really in foreground when screen is also on
1639            return mUidForeground.get(uid, false) && mScreenOn;
1640        }
1641    }
1642
1643    /**
1644     * Foreground for PID changed; recompute foreground at UID level. If
1645     * changed, will trigger {@link #updateRulesForUidLocked(int)}.
1646     */
1647    private void computeUidForegroundLocked(int uid) {
1648        final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1649
1650        // current pid is dropping foreground; examine other pids
1651        boolean uidForeground = false;
1652        final int size = pidForeground.size();
1653        for (int i = 0; i < size; i++) {
1654            if (pidForeground.valueAt(i)) {
1655                uidForeground = true;
1656                break;
1657            }
1658        }
1659
1660        final boolean oldUidForeground = mUidForeground.get(uid, false);
1661        if (oldUidForeground != uidForeground) {
1662            // foreground changed, push updated rules
1663            mUidForeground.put(uid, uidForeground);
1664            updateRulesForUidLocked(uid);
1665        }
1666    }
1667
1668    private void updateScreenOn() {
1669        synchronized (mRulesLock) {
1670            try {
1671                mScreenOn = mPowerManager.isScreenOn();
1672            } catch (RemoteException e) {
1673                // ignored; service lives in system_server
1674            }
1675            updateRulesForScreenLocked();
1676        }
1677    }
1678
1679    /**
1680     * Update rules that might be changed by {@link #mScreenOn} value.
1681     */
1682    private void updateRulesForScreenLocked() {
1683        // only update rules for anyone with foreground activities
1684        final int size = mUidForeground.size();
1685        for (int i = 0; i < size; i++) {
1686            if (mUidForeground.valueAt(i)) {
1687                final int uid = mUidForeground.keyAt(i);
1688                updateRulesForUidLocked(uid);
1689            }
1690        }
1691    }
1692
1693    /**
1694     * Update rules that might be changed by {@link #mRestrictBackground} value.
1695     */
1696    private void updateRulesForRestrictBackgroundLocked() {
1697        // update rules for all installed applications
1698        final PackageManager pm = mContext.getPackageManager();
1699        final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
1700        for (ApplicationInfo app : apps) {
1701            final int appId = UserHandle.getAppId(app.uid);
1702            updateRulesForAppLocked(appId);
1703        }
1704
1705        // limit data usage for some internal system services
1706        updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1707        updateRulesForUidLocked(android.os.Process.DRM_UID);
1708    }
1709
1710    private void updateRulesForAppLocked(int appId) {
1711        UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1712        for (UserInfo user : um.getUsers()) {
1713            final int uid = UserHandle.getUid(user.id, appId);
1714            updateRulesForUidLocked(uid);
1715        }
1716    }
1717
1718    private static boolean isUidValidForRules(int uid) {
1719        // allow rules on specific system services, and any apps
1720        if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
1721                || UserHandle.isApp(uid)) {
1722            return true;
1723        }
1724
1725        return false;
1726    }
1727
1728    private void updateRulesForUidLocked(int uid) {
1729        if (!isUidValidForRules(uid)) return;
1730
1731        final int appId = UserHandle.getAppId(uid);
1732        final int appPolicy = getAppPolicy(appId);
1733        final boolean uidForeground = isUidForeground(uid);
1734
1735        // derive active rules based on policy and active state
1736        int uidRules = RULE_ALLOW_ALL;
1737        if (!uidForeground && (appPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1738            // uid in background, and policy says to block metered data
1739            uidRules = RULE_REJECT_METERED;
1740        }
1741        if (!uidForeground && mRestrictBackground) {
1742            // uid in background, and global background disabled
1743            uidRules = RULE_REJECT_METERED;
1744        }
1745
1746        // TODO: only dispatch when rules actually change
1747
1748        if (uidRules == RULE_ALLOW_ALL) {
1749            mUidRules.delete(uid);
1750        } else {
1751            mUidRules.put(uid, uidRules);
1752        }
1753
1754        final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
1755        setUidNetworkRules(uid, rejectMetered);
1756
1757        // dispatch changed rule to existing listeners
1758        mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
1759
1760        try {
1761            // adjust stats accounting based on foreground status
1762            mNetworkStats.setUidForeground(uid, uidForeground);
1763        } catch (RemoteException e) {
1764            // ignored; service lives in system_server
1765        }
1766    }
1767
1768    private Handler.Callback mHandlerCallback = new Handler.Callback() {
1769        @Override
1770        public boolean handleMessage(Message msg) {
1771            switch (msg.what) {
1772                case MSG_RULES_CHANGED: {
1773                    final int uid = msg.arg1;
1774                    final int uidRules = msg.arg2;
1775                    final int length = mListeners.beginBroadcast();
1776                    for (int i = 0; i < length; i++) {
1777                        final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1778                        if (listener != null) {
1779                            try {
1780                                listener.onUidRulesChanged(uid, uidRules);
1781                            } catch (RemoteException e) {
1782                            }
1783                        }
1784                    }
1785                    mListeners.finishBroadcast();
1786                    return true;
1787                }
1788                case MSG_METERED_IFACES_CHANGED: {
1789                    final String[] meteredIfaces = (String[]) msg.obj;
1790                    final int length = mListeners.beginBroadcast();
1791                    for (int i = 0; i < length; i++) {
1792                        final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1793                        if (listener != null) {
1794                            try {
1795                                listener.onMeteredIfacesChanged(meteredIfaces);
1796                            } catch (RemoteException e) {
1797                            }
1798                        }
1799                    }
1800                    mListeners.finishBroadcast();
1801                    return true;
1802                }
1803                case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1804                    final int pid = msg.arg1;
1805                    final int uid = msg.arg2;
1806                    final boolean foregroundActivities = (Boolean) msg.obj;
1807
1808                    synchronized (mRulesLock) {
1809                        // because a uid can have multiple pids running inside, we need to
1810                        // remember all pid states and summarize foreground at uid level.
1811
1812                        // record foreground for this specific pid
1813                        SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1814                        if (pidForeground == null) {
1815                            pidForeground = new SparseBooleanArray(2);
1816                            mUidPidForeground.put(uid, pidForeground);
1817                        }
1818                        pidForeground.put(pid, foregroundActivities);
1819                        computeUidForegroundLocked(uid);
1820                    }
1821                    return true;
1822                }
1823                case MSG_PROCESS_DIED: {
1824                    final int pid = msg.arg1;
1825                    final int uid = msg.arg2;
1826
1827                    synchronized (mRulesLock) {
1828                        // clear records and recompute, when they exist
1829                        final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1830                        if (pidForeground != null) {
1831                            pidForeground.delete(pid);
1832                            computeUidForegroundLocked(uid);
1833                        }
1834                    }
1835                    return true;
1836                }
1837                case MSG_LIMIT_REACHED: {
1838                    final String iface = (String) msg.obj;
1839
1840                    maybeRefreshTrustedTime();
1841                    synchronized (mRulesLock) {
1842                        if (mMeteredIfaces.contains(iface)) {
1843                            try {
1844                                // force stats update to make sure we have
1845                                // numbers that caused alert to trigger.
1846                                mNetworkStats.forceUpdate();
1847                            } catch (RemoteException e) {
1848                                // ignored; service lives in system_server
1849                            }
1850
1851                            updateNetworkEnabledLocked();
1852                            updateNotificationsLocked();
1853                        }
1854                    }
1855                    return true;
1856                }
1857                case MSG_RESTRICT_BACKGROUND_CHANGED: {
1858                    final boolean restrictBackground = msg.arg1 != 0;
1859                    final int length = mListeners.beginBroadcast();
1860                    for (int i = 0; i < length; i++) {
1861                        final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1862                        if (listener != null) {
1863                            try {
1864                                listener.onRestrictBackgroundChanged(restrictBackground);
1865                            } catch (RemoteException e) {
1866                            }
1867                        }
1868                    }
1869                    mListeners.finishBroadcast();
1870                    return true;
1871                }
1872                case MSG_ADVISE_PERSIST_THRESHOLD: {
1873                    final long lowestRule = (Long) msg.obj;
1874                    try {
1875                        // make sure stats are recorded frequently enough; we aim
1876                        // for 2MB threshold for 2GB/month rules.
1877                        final long persistThreshold = lowestRule / 1000;
1878                        mNetworkStats.advisePersistThreshold(persistThreshold);
1879                    } catch (RemoteException e) {
1880                        // ignored; service lives in system_server
1881                    }
1882                    return true;
1883                }
1884                case MSG_SCREEN_ON_CHANGED: {
1885                    updateScreenOn();
1886                    return true;
1887                }
1888                default: {
1889                    return false;
1890                }
1891            }
1892        }
1893    };
1894
1895    private void setInterfaceQuota(String iface, long quotaBytes) {
1896        try {
1897            mNetworkManager.setInterfaceQuota(iface, quotaBytes);
1898        } catch (IllegalStateException e) {
1899            Log.wtf(TAG, "problem setting interface quota", e);
1900        } catch (RemoteException e) {
1901            // ignored; service lives in system_server
1902        }
1903    }
1904
1905    private void removeInterfaceQuota(String iface) {
1906        try {
1907            mNetworkManager.removeInterfaceQuota(iface);
1908        } catch (IllegalStateException e) {
1909            Log.wtf(TAG, "problem removing interface quota", e);
1910        } catch (RemoteException e) {
1911            // ignored; service lives in system_server
1912        }
1913    }
1914
1915    private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1916        try {
1917            mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
1918        } catch (IllegalStateException e) {
1919            Log.wtf(TAG, "problem setting uid rules", e);
1920        } catch (RemoteException e) {
1921            // ignored; service lives in system_server
1922        }
1923    }
1924
1925    /**
1926     * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
1927     */
1928    private void setPolicyDataEnable(int networkType, boolean enabled) {
1929        try {
1930            mConnManager.setPolicyDataEnable(networkType, enabled);
1931        } catch (RemoteException e) {
1932            // ignored; service lives in system_server
1933        }
1934    }
1935
1936    private long getTotalBytes(NetworkTemplate template, long start, long end) {
1937        try {
1938            return mNetworkStats.getNetworkTotalBytes(template, start, end);
1939        } catch (RuntimeException e) {
1940            Slog.w(TAG, "problem reading network stats: " + e);
1941            return 0;
1942        } catch (RemoteException e) {
1943            // ignored; service lives in system_server
1944            return 0;
1945        }
1946    }
1947
1948    private boolean isBandwidthControlEnabled() {
1949        final long token = Binder.clearCallingIdentity();
1950        try {
1951            return mNetworkManager.isBandwidthControlEnabled();
1952        } catch (RemoteException e) {
1953            // ignored; service lives in system_server
1954            return false;
1955        } finally {
1956            Binder.restoreCallingIdentity(token);
1957        }
1958    }
1959
1960    /**
1961     * Try refreshing {@link #mTime} when stale.
1962     */
1963    private void maybeRefreshTrustedTime() {
1964        if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
1965            mTime.forceRefresh();
1966        }
1967    }
1968
1969    private long currentTimeMillis() {
1970        return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
1971    }
1972
1973    private static Intent buildAllowBackgroundDataIntent() {
1974        return new Intent(ACTION_ALLOW_BACKGROUND);
1975    }
1976
1977    private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
1978        final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
1979        intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1980        return intent;
1981    }
1982
1983    private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
1984        final Intent intent = new Intent();
1985        intent.setComponent(new ComponentName(
1986                "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
1987        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1988        intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1989        return intent;
1990    }
1991
1992    private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
1993        final Intent intent = new Intent();
1994        intent.setComponent(new ComponentName(
1995                "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
1996        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1997        intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1998        return intent;
1999    }
2000
2001    // @VisibleForTesting
2002    public void addIdleHandler(IdleHandler handler) {
2003        mHandler.getLooper().getQueue().addIdleHandler(handler);
2004    }
2005
2006    private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2007        final int size = source.size();
2008        for (int i = 0; i < size; i++) {
2009            target.put(source.keyAt(i), true);
2010        }
2011    }
2012
2013    private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2014        final int size = source.size();
2015        for (int i = 0; i < size; i++) {
2016            target.put(source.keyAt(i), true);
2017        }
2018    }
2019
2020    private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2021        fout.print("[");
2022        final int size = value.size();
2023        for (int i = 0; i < size; i++) {
2024            fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2025            if (i < size - 1) fout.print(",");
2026        }
2027        fout.print("]");
2028    }
2029
2030    public static class XmlUtils {
2031        public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
2032            final String value = in.getAttributeValue(null, name);
2033            try {
2034                return Integer.parseInt(value);
2035            } catch (NumberFormatException e) {
2036                throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
2037            }
2038        }
2039
2040        public static void writeIntAttribute(XmlSerializer out, String name, int value)
2041                throws IOException {
2042            out.attribute(null, name, Integer.toString(value));
2043        }
2044
2045        public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
2046            final String value = in.getAttributeValue(null, name);
2047            try {
2048                return Long.parseLong(value);
2049            } catch (NumberFormatException e) {
2050                throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
2051            }
2052        }
2053
2054        public static void writeLongAttribute(XmlSerializer out, String name, long value)
2055                throws IOException {
2056            out.attribute(null, name, Long.toString(value));
2057        }
2058
2059        public static boolean readBooleanAttribute(XmlPullParser in, String name) {
2060            final String value = in.getAttributeValue(null, name);
2061            return Boolean.parseBoolean(value);
2062        }
2063
2064        public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
2065                throws IOException {
2066            out.attribute(null, name, Boolean.toString(value));
2067        }
2068    }
2069}
2070