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