1 /* 2 * Copyright (C) 2016 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 17 package com.android.server.net; 18 19 import static android.app.usage.NetworkStatsManager.MIN_THRESHOLD_BYTES; 20 21 import android.annotation.NonNull; 22 import android.app.usage.NetworkStatsManager; 23 import android.content.Context; 24 import android.content.pm.PackageManager; 25 import android.net.DataUsageRequest; 26 import android.net.NetworkIdentitySet; 27 import android.net.NetworkStack; 28 import android.net.NetworkStats; 29 import android.net.NetworkStatsAccess; 30 import android.net.NetworkStatsCollection; 31 import android.net.NetworkStatsHistory; 32 import android.net.NetworkTemplate; 33 import android.net.netstats.IUsageCallback; 34 import android.os.Handler; 35 import android.os.HandlerThread; 36 import android.os.IBinder; 37 import android.os.Looper; 38 import android.os.Message; 39 import android.os.Process; 40 import android.os.RemoteException; 41 import android.util.ArrayMap; 42 import android.util.IndentingPrintWriter; 43 import android.util.Log; 44 import android.util.SparseArray; 45 46 import com.android.internal.annotations.VisibleForTesting; 47 import com.android.net.module.util.PerUidCounter; 48 49 import java.util.concurrent.atomic.AtomicInteger; 50 51 /** 52 * Manages observers of {@link NetworkStats}. Allows observers to be notified when 53 * data usage has been reported in {@link NetworkStatsService}. An observer can set 54 * a threshold of how much data it cares about to be notified. 55 */ 56 class NetworkStatsObservers { 57 private static final String TAG = "NetworkStatsObservers"; 58 private static final boolean LOG = true; 59 private static final boolean LOGV = false; 60 61 private static final int MSG_REGISTER = 1; 62 private static final int MSG_UNREGISTER = 2; 63 private static final int MSG_UPDATE_STATS = 3; 64 65 private static final int DUMP_USAGE_REQUESTS_COUNT = 200; 66 67 // The maximum number of request allowed per uid before an exception is thrown. 68 @VisibleForTesting 69 static final int MAX_REQUESTS_PER_UID = 100; 70 71 // All access to this map must be done from the handler thread. 72 // indexed by DataUsageRequest#requestId 73 private final SparseArray<RequestInfo> mDataUsageRequests = new SparseArray<>(); 74 75 // Request counters per uid, this is thread safe. 76 private final PerUidCounter mDataUsageRequestsPerUid = new PerUidCounter(MAX_REQUESTS_PER_UID); 77 78 // Sequence number of DataUsageRequests 79 private final AtomicInteger mNextDataUsageRequestId = new AtomicInteger(); 80 81 // Lazily instantiated when an observer is registered. 82 private volatile Handler mHandler; 83 84 /** 85 * Creates a wrapper that contains the caller context and a normalized request. 86 * The request should be returned to the caller app, and the wrapper should be sent to this 87 * object through #addObserver by the service handler. 88 * 89 * <p>It will register the observer asynchronously, so it is safe to call from any thread. 90 * 91 * @return the normalized request wrapped within {@link RequestInfo}. 92 */ register(@onNull Context context, @NonNull DataUsageRequest inputRequest, @NonNull IUsageCallback callback, int callingPid, int callingUid, @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel)93 public DataUsageRequest register(@NonNull Context context, 94 @NonNull DataUsageRequest inputRequest, @NonNull IUsageCallback callback, 95 int callingPid, int callingUid, @NonNull String callingPackage, 96 @NetworkStatsAccess.Level int accessLevel) { 97 DataUsageRequest request = buildRequest(context, inputRequest, callingUid); 98 RequestInfo requestInfo = buildRequestInfo(request, callback, callingPid, callingUid, 99 callingPackage, accessLevel); 100 if (LOG) Log.d(TAG, "Registering observer for " + requestInfo); 101 mDataUsageRequestsPerUid.incrementCountOrThrow(callingUid); 102 103 getHandler().sendMessage(mHandler.obtainMessage(MSG_REGISTER, requestInfo)); 104 return request; 105 } 106 107 /** 108 * Unregister a data usage observer. 109 * 110 * <p>It will unregister the observer asynchronously, so it is safe to call from any thread. 111 */ unregister(DataUsageRequest request, int callingUid)112 public void unregister(DataUsageRequest request, int callingUid) { 113 getHandler().sendMessage(mHandler.obtainMessage(MSG_UNREGISTER, callingUid, 0 /* ignore */, 114 request)); 115 } 116 117 /** 118 * Updates data usage statistics of registered observers and notifies if limits are reached. 119 * 120 * <p>It will update stats asynchronously, so it is safe to call from any thread. 121 */ updateStats(NetworkStats xtSnapshot, NetworkStats uidSnapshot, ArrayMap<String, NetworkIdentitySet> activeIfaces, ArrayMap<String, NetworkIdentitySet> activeUidIfaces, long currentTime)122 public void updateStats(NetworkStats xtSnapshot, NetworkStats uidSnapshot, 123 ArrayMap<String, NetworkIdentitySet> activeIfaces, 124 ArrayMap<String, NetworkIdentitySet> activeUidIfaces, 125 long currentTime) { 126 StatsContext statsContext = new StatsContext(xtSnapshot, uidSnapshot, activeIfaces, 127 activeUidIfaces, currentTime); 128 getHandler().sendMessage(mHandler.obtainMessage(MSG_UPDATE_STATS, statsContext)); 129 } 130 getHandler()131 private Handler getHandler() { 132 if (mHandler == null) { 133 synchronized (this) { 134 if (mHandler == null) { 135 if (LOGV) Log.v(TAG, "Creating handler"); 136 mHandler = new Handler(getHandlerLooperLocked(), mHandlerCallback); 137 } 138 } 139 } 140 return mHandler; 141 } 142 143 @VisibleForTesting getHandlerLooperLocked()144 protected Looper getHandlerLooperLocked() { 145 HandlerThread handlerThread = new HandlerThread(TAG); 146 handlerThread.start(); 147 return handlerThread.getLooper(); 148 } 149 150 private Handler.Callback mHandlerCallback = new Handler.Callback() { 151 @Override 152 public boolean handleMessage(Message msg) { 153 switch (msg.what) { 154 case MSG_REGISTER: { 155 handleRegister((RequestInfo) msg.obj); 156 return true; 157 } 158 case MSG_UNREGISTER: { 159 handleUnregister((DataUsageRequest) msg.obj, msg.arg1 /* callingUid */); 160 return true; 161 } 162 case MSG_UPDATE_STATS: { 163 handleUpdateStats((StatsContext) msg.obj); 164 return true; 165 } 166 default: { 167 return false; 168 } 169 } 170 } 171 }; 172 173 /** 174 * Adds a {@link RequestInfo} as an observer. 175 * Should only be called from the handler thread otherwise there will be a race condition 176 * on mDataUsageRequests. 177 */ handleRegister(RequestInfo requestInfo)178 private void handleRegister(RequestInfo requestInfo) { 179 mDataUsageRequests.put(requestInfo.mRequest.requestId, requestInfo); 180 } 181 182 /** 183 * Removes a {@link DataUsageRequest} if the calling uid is authorized. 184 * Should only be called from the handler thread otherwise there will be a race condition 185 * on mDataUsageRequests. 186 */ handleUnregister(DataUsageRequest request, int callingUid)187 private void handleUnregister(DataUsageRequest request, int callingUid) { 188 RequestInfo requestInfo; 189 requestInfo = mDataUsageRequests.get(request.requestId); 190 if (requestInfo == null) { 191 if (LOG) Log.d(TAG, "Trying to unregister unknown request " + request); 192 return; 193 } 194 if (Process.SYSTEM_UID != callingUid && requestInfo.mCallingUid != callingUid) { 195 Log.w(TAG, "Caller uid " + callingUid + " is not owner of " + request); 196 return; 197 } 198 199 if (LOG) Log.d(TAG, "Unregistering " + requestInfo); 200 mDataUsageRequests.remove(request.requestId); 201 mDataUsageRequestsPerUid.decrementCountOrThrow(requestInfo.mCallingUid); 202 requestInfo.unlinkDeathRecipient(); 203 requestInfo.callCallback(NetworkStatsManager.CALLBACK_RELEASED); 204 } 205 handleUpdateStats(StatsContext statsContext)206 private void handleUpdateStats(StatsContext statsContext) { 207 if (mDataUsageRequests.size() == 0) { 208 return; 209 } 210 211 for (int i = 0; i < mDataUsageRequests.size(); i++) { 212 RequestInfo requestInfo = mDataUsageRequests.valueAt(i); 213 requestInfo.updateStats(statsContext); 214 } 215 } 216 buildRequest(Context context, DataUsageRequest request, int callingUid)217 private DataUsageRequest buildRequest(Context context, DataUsageRequest request, 218 int callingUid) { 219 // For non-NETWORK_STACK permission uid, cap the minimum threshold to a safe default to 220 // avoid too many callbacks. 221 final long thresholdInBytes = (context.checkPermission( 222 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, Process.myPid(), callingUid) 223 == PackageManager.PERMISSION_GRANTED ? request.thresholdInBytes 224 : Math.max(MIN_THRESHOLD_BYTES, request.thresholdInBytes)); 225 if (thresholdInBytes > request.thresholdInBytes) { 226 Log.w(TAG, "Threshold was too low for " + request 227 + ". Overriding to a safer default of " + thresholdInBytes + " bytes"); 228 } 229 return new DataUsageRequest(mNextDataUsageRequestId.incrementAndGet(), 230 request.template, thresholdInBytes); 231 } 232 buildRequestInfo(DataUsageRequest request, IUsageCallback callback, int callingPid, int callingUid, @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel)233 private RequestInfo buildRequestInfo(DataUsageRequest request, IUsageCallback callback, 234 int callingPid, int callingUid, @NonNull String callingPackage, 235 @NetworkStatsAccess.Level int accessLevel) { 236 if (accessLevel <= NetworkStatsAccess.Level.USER) { 237 return new UserUsageRequestInfo(this, request, callback, callingPid, 238 callingUid, callingPackage, accessLevel); 239 } else { 240 // Safety check in case a new access level is added and we forgot to update this 241 if (accessLevel < NetworkStatsAccess.Level.DEVICESUMMARY) { 242 throw new IllegalArgumentException( 243 "accessLevel " + accessLevel + " is less than DEVICESUMMARY."); 244 } 245 return new NetworkUsageRequestInfo(this, request, callback, callingPid, 246 callingUid, callingPackage, accessLevel); 247 } 248 } 249 250 /** 251 * Tracks information relevant to a data usage observer. 252 * It will notice when the calling process dies so we can self-expire. 253 */ 254 private abstract static class RequestInfo implements IBinder.DeathRecipient { 255 private final NetworkStatsObservers mStatsObserver; 256 protected final DataUsageRequest mRequest; 257 private final IUsageCallback mCallback; 258 protected final int mCallingPid; 259 protected final int mCallingUid; 260 protected final String mCallingPackage; 261 protected final @NetworkStatsAccess.Level int mAccessLevel; 262 protected NetworkStatsRecorder mRecorder; 263 protected NetworkStatsCollection mCollection; 264 RequestInfo(NetworkStatsObservers statsObserver, DataUsageRequest request, IUsageCallback callback, int callingPid, int callingUid, @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel)265 RequestInfo(NetworkStatsObservers statsObserver, DataUsageRequest request, 266 IUsageCallback callback, int callingPid, int callingUid, 267 @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel) { 268 mStatsObserver = statsObserver; 269 mRequest = request; 270 mCallback = callback; 271 mCallingPid = callingPid; 272 mCallingUid = callingUid; 273 mCallingPackage = callingPackage; 274 mAccessLevel = accessLevel; 275 276 try { 277 mCallback.asBinder().linkToDeath(this, 0); 278 } catch (RemoteException e) { 279 binderDied(); 280 } 281 } 282 283 @Override binderDied()284 public void binderDied() { 285 if (LOGV) { 286 Log.v(TAG, "RequestInfo binderDied(" + mRequest + ", " + mCallback + ")"); 287 } 288 mStatsObserver.unregister(mRequest, Process.SYSTEM_UID); 289 callCallback(NetworkStatsManager.CALLBACK_RELEASED); 290 } 291 292 @Override toString()293 public String toString() { 294 return "RequestInfo from pid/uid:" + mCallingPid + "/" + mCallingUid 295 + "(" + mCallingPackage + ")" 296 + " for " + mRequest + " accessLevel:" + mAccessLevel; 297 } 298 unlinkDeathRecipient()299 private void unlinkDeathRecipient() { 300 mCallback.asBinder().unlinkToDeath(this, 0); 301 } 302 303 /** 304 * Update stats given the samples and interface to identity mappings. 305 */ updateStats(StatsContext statsContext)306 private void updateStats(StatsContext statsContext) { 307 if (mRecorder == null) { 308 // First run; establish baseline stats 309 resetRecorder(); 310 recordSample(statsContext); 311 return; 312 } 313 recordSample(statsContext); 314 315 if (checkStats()) { 316 resetRecorder(); 317 callCallback(NetworkStatsManager.CALLBACK_LIMIT_REACHED); 318 } 319 } 320 callCallback(int callbackType)321 private void callCallback(int callbackType) { 322 try { 323 if (LOGV) { 324 Log.v(TAG, "sending notification " + callbackTypeToName(callbackType) 325 + " for " + mRequest); 326 } 327 switch (callbackType) { 328 case NetworkStatsManager.CALLBACK_LIMIT_REACHED: 329 mCallback.onThresholdReached(mRequest); 330 break; 331 case NetworkStatsManager.CALLBACK_RELEASED: 332 mCallback.onCallbackReleased(mRequest); 333 break; 334 } 335 } catch (RemoteException e) { 336 // May occur naturally in the race of binder death. 337 Log.w(TAG, "RemoteException caught trying to send a callback msg for " + mRequest); 338 } 339 } 340 resetRecorder()341 private void resetRecorder() { 342 mRecorder = new NetworkStatsRecorder(); 343 mCollection = mRecorder.getSinceBoot(); 344 } 345 checkStats()346 protected abstract boolean checkStats(); 347 recordSample(StatsContext statsContext)348 protected abstract void recordSample(StatsContext statsContext); 349 callbackTypeToName(int callbackType)350 private String callbackTypeToName(int callbackType) { 351 switch (callbackType) { 352 case NetworkStatsManager.CALLBACK_LIMIT_REACHED: 353 return "LIMIT_REACHED"; 354 case NetworkStatsManager.CALLBACK_RELEASED: 355 return "RELEASED"; 356 default: 357 return "UNKNOWN"; 358 } 359 } 360 } 361 362 private static class NetworkUsageRequestInfo extends RequestInfo { NetworkUsageRequestInfo(NetworkStatsObservers statsObserver, DataUsageRequest request, IUsageCallback callback, int callingPid, int callingUid, @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel)363 NetworkUsageRequestInfo(NetworkStatsObservers statsObserver, DataUsageRequest request, 364 IUsageCallback callback, int callingPid, int callingUid, 365 @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel) { 366 super(statsObserver, request, callback, callingPid, callingUid, callingPackage, 367 accessLevel); 368 } 369 370 @Override checkStats()371 protected boolean checkStats() { 372 long bytesSoFar = getTotalBytesForNetwork(mRequest.template); 373 if (LOGV) { 374 Log.v(TAG, bytesSoFar + " bytes so far since notification for " 375 + mRequest.template); 376 } 377 if (bytesSoFar > mRequest.thresholdInBytes) { 378 return true; 379 } 380 return false; 381 } 382 383 @Override recordSample(StatsContext statsContext)384 protected void recordSample(StatsContext statsContext) { 385 // Recorder does not need to be locked in this context since only the handler 386 // thread will update it. We pass a null VPN array because usage is aggregated by uid 387 // for this snapshot, so VPN traffic can't be reattributed to responsible apps. 388 mRecorder.recordSnapshotLocked(statsContext.mXtSnapshot, statsContext.mActiveIfaces, 389 statsContext.mCurrentTime); 390 } 391 392 /** 393 * Reads stats matching the given template. {@link NetworkStatsCollection} will aggregate 394 * over all buckets, which in this case should be only one since we built it big enough 395 * that it will outlive the caller. If it doesn't, then there will be multiple buckets. 396 */ getTotalBytesForNetwork(NetworkTemplate template)397 private long getTotalBytesForNetwork(NetworkTemplate template) { 398 NetworkStats stats = mCollection.getSummary(template, 399 Long.MIN_VALUE /* start */, Long.MAX_VALUE /* end */, 400 mAccessLevel, mCallingUid); 401 return stats.getTotalBytes(); 402 } 403 } 404 405 private static class UserUsageRequestInfo extends RequestInfo { UserUsageRequestInfo(NetworkStatsObservers statsObserver, DataUsageRequest request, IUsageCallback callback, int callingPid, int callingUid, @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel)406 UserUsageRequestInfo(NetworkStatsObservers statsObserver, DataUsageRequest request, 407 IUsageCallback callback, int callingPid, int callingUid, 408 @NonNull String callingPackage, @NetworkStatsAccess.Level int accessLevel) { 409 super(statsObserver, request, callback, callingPid, callingUid, 410 callingPackage, accessLevel); 411 } 412 413 @Override checkStats()414 protected boolean checkStats() { 415 int[] uidsToMonitor = mCollection.getRelevantUids(mAccessLevel, mCallingUid); 416 417 for (int i = 0; i < uidsToMonitor.length; i++) { 418 long bytesSoFar = getTotalBytesForNetworkUid(mRequest.template, uidsToMonitor[i]); 419 if (bytesSoFar > mRequest.thresholdInBytes) { 420 return true; 421 } 422 } 423 return false; 424 } 425 426 @Override recordSample(StatsContext statsContext)427 protected void recordSample(StatsContext statsContext) { 428 // Recorder does not need to be locked in this context since only the handler 429 // thread will update it. We pass the VPN info so VPN traffic is reattributed to 430 // responsible apps. 431 mRecorder.recordSnapshotLocked(statsContext.mUidSnapshot, statsContext.mActiveUidIfaces, 432 statsContext.mCurrentTime); 433 } 434 435 /** 436 * Reads all stats matching the given template and uid. Ther history will likely only 437 * contain one bucket per ident since we build it big enough that it will outlive the 438 * caller lifetime. 439 */ getTotalBytesForNetworkUid(NetworkTemplate template, int uid)440 private long getTotalBytesForNetworkUid(NetworkTemplate template, int uid) { 441 try { 442 NetworkStatsHistory history = mCollection.getHistory(template, null, uid, 443 NetworkStats.SET_ALL, NetworkStats.TAG_NONE, 444 NetworkStatsHistory.FIELD_ALL, 445 Long.MIN_VALUE /* start */, Long.MAX_VALUE /* end */, 446 mAccessLevel, mCallingUid); 447 return history.getTotalBytes(); 448 } catch (SecurityException e) { 449 if (LOGV) { 450 Log.w(TAG, "CallerUid " + mCallingUid + " may have lost access to uid " 451 + uid); 452 } 453 return 0; 454 } 455 } 456 } 457 458 private static class StatsContext { 459 NetworkStats mXtSnapshot; 460 NetworkStats mUidSnapshot; 461 ArrayMap<String, NetworkIdentitySet> mActiveIfaces; 462 ArrayMap<String, NetworkIdentitySet> mActiveUidIfaces; 463 long mCurrentTime; 464 StatsContext(NetworkStats xtSnapshot, NetworkStats uidSnapshot, ArrayMap<String, NetworkIdentitySet> activeIfaces, ArrayMap<String, NetworkIdentitySet> activeUidIfaces, long currentTime)465 StatsContext(NetworkStats xtSnapshot, NetworkStats uidSnapshot, 466 ArrayMap<String, NetworkIdentitySet> activeIfaces, 467 ArrayMap<String, NetworkIdentitySet> activeUidIfaces, 468 long currentTime) { 469 mXtSnapshot = xtSnapshot; 470 mUidSnapshot = uidSnapshot; 471 mActiveIfaces = activeIfaces; 472 mActiveUidIfaces = activeUidIfaces; 473 mCurrentTime = currentTime; 474 } 475 } 476 dump(IndentingPrintWriter pw)477 public void dump(IndentingPrintWriter pw) { 478 for (int i = 0; i < Math.min(mDataUsageRequests.size(), DUMP_USAGE_REQUESTS_COUNT); i++) { 479 pw.println(mDataUsageRequests.valueAt(i)); 480 } 481 } 482 } 483