Home | History | Annotate | Download | only in net
      1 /*
      2  * Copyright (C) 2007 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 android.net;
     18 
     19 import android.annotation.SuppressLint;
     20 import android.annotation.SystemApi;
     21 import android.annotation.TestApi;
     22 import android.annotation.UnsupportedAppUsage;
     23 import android.app.DownloadManager;
     24 import android.app.backup.BackupManager;
     25 import android.app.usage.NetworkStatsManager;
     26 import android.content.Context;
     27 import android.media.MediaPlayer;
     28 import android.os.Build;
     29 import android.os.RemoteException;
     30 import android.os.ServiceManager;
     31 import android.util.DataUnit;
     32 
     33 import com.android.server.NetworkManagementSocketTagger;
     34 
     35 import dalvik.system.SocketTagger;
     36 
     37 import java.io.FileDescriptor;
     38 import java.io.IOException;
     39 import java.net.DatagramSocket;
     40 import java.net.Socket;
     41 import java.net.SocketException;
     42 
     43 /**
     44  * Class that provides network traffic statistics. These statistics include
     45  * bytes transmitted and received and network packets transmitted and received,
     46  * over all interfaces, over the mobile interface, and on a per-UID basis.
     47  * <p>
     48  * These statistics may not be available on all platforms. If the statistics are
     49  * not supported by this device, {@link #UNSUPPORTED} will be returned.
     50  * <p>
     51  * Note that the statistics returned by this class reset and start from zero
     52  * after every reboot. To access more robust historical network statistics data,
     53  * use {@link NetworkStatsManager} instead.
     54  */
     55 public class TrafficStats {
     56     /**
     57      * The return value to indicate that the device does not support the statistic.
     58      */
     59     public final static int UNSUPPORTED = -1;
     60 
     61     /** @hide @deprecated use {@link DataUnit} instead to clarify SI-vs-IEC */
     62     @Deprecated
     63     public static final long KB_IN_BYTES = 1024;
     64     /** @hide @deprecated use {@link DataUnit} instead to clarify SI-vs-IEC */
     65     @Deprecated
     66     public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
     67     /** @hide @deprecated use {@link DataUnit} instead to clarify SI-vs-IEC */
     68     @Deprecated
     69     public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
     70     /** @hide @deprecated use {@link DataUnit} instead to clarify SI-vs-IEC */
     71     @Deprecated
     72     public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
     73     /** @hide @deprecated use {@link DataUnit} instead to clarify SI-vs-IEC */
     74     @Deprecated
     75     public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
     76 
     77     /**
     78      * Special UID value used when collecting {@link NetworkStatsHistory} for
     79      * removed applications.
     80      *
     81      * @hide
     82      */
     83     public static final int UID_REMOVED = -4;
     84 
     85     /**
     86      * Special UID value used when collecting {@link NetworkStatsHistory} for
     87      * tethering traffic.
     88      *
     89      * @hide
     90      */
     91     public static final int UID_TETHERING = -5;
     92 
     93     /**
     94      * Tag values in this range are reserved for the network stack. The network stack is
     95      * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
     96      * module separate process, and as the system UID otherwise.
     97      */
     98     /** @hide */
     99     @SystemApi
    100     public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
    101     /** @hide */
    102     @SystemApi
    103     public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
    104 
    105     /**
    106      * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
    107      * like DownloadManager when performing traffic on behalf of an application.
    108      */
    109     // Please note there is no enforcement of these constants, so do not rely on them to
    110     // determine that the caller is a system caller.
    111     /** @hide */
    112     @SystemApi
    113     public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
    114     /** @hide */
    115     @SystemApi
    116     public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
    117 
    118     /**
    119      * Tag values between these ranges are reserved for the network stack to do traffic
    120      * on behalf of applications. It is a subrange of the range above.
    121      */
    122     /** @hide */
    123     @SystemApi
    124     public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
    125     /** @hide */
    126     @SystemApi
    127     public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
    128 
    129     /**
    130      * Default tag value for {@link DownloadManager} traffic.
    131      *
    132      * @hide
    133      */
    134     public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
    135 
    136     /**
    137      * Default tag value for {@link MediaPlayer} traffic.
    138      *
    139      * @hide
    140      */
    141     public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
    142 
    143     /**
    144      * Default tag value for {@link BackupManager} backup traffic; that is,
    145      * traffic from the device to the storage backend.
    146      *
    147      * @hide
    148      */
    149     public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
    150 
    151     /**
    152      * Default tag value for {@link BackupManager} restore traffic; that is,
    153      * app data retrieved from the storage backend at install time.
    154      *
    155      * @hide
    156      */
    157     public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
    158 
    159     /**
    160      * Default tag value for code (typically APKs) downloaded by an app store on
    161      * behalf of the app, such as updates.
    162      *
    163      * @hide
    164      */
    165     public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
    166 
    167     // TODO : remove this constant when Wifi code is updated
    168     /** @hide */
    169     public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
    170 
    171     private static INetworkStatsService sStatsService;
    172 
    173     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
    174     private synchronized static INetworkStatsService getStatsService() {
    175         if (sStatsService == null) {
    176             sStatsService = INetworkStatsService.Stub.asInterface(
    177                     ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
    178         }
    179         return sStatsService;
    180     }
    181 
    182     /**
    183      * Snapshot of {@link NetworkStats} when the currently active profiling
    184      * session started, or {@code null} if no session active.
    185      *
    186      * @see #startDataProfiling(Context)
    187      * @see #stopDataProfiling(Context)
    188      */
    189     private static NetworkStats sActiveProfilingStart;
    190 
    191     private static Object sProfilingLock = new Object();
    192 
    193     private static final String LOOPBACK_IFACE = "lo";
    194 
    195     /**
    196      * Set active tag to use when accounting {@link Socket} traffic originating
    197      * from the current thread. Only one active tag per thread is supported.
    198      * <p>
    199      * Changes only take effect during subsequent calls to
    200      * {@link #tagSocket(Socket)}.
    201      * <p>
    202      * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
    203      * used internally by system services like {@link DownloadManager} when
    204      * performing traffic on behalf of an application.
    205      *
    206      * @see #clearThreadStatsTag()
    207      */
    208     public static void setThreadStatsTag(int tag) {
    209         NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
    210     }
    211 
    212     /**
    213      * Set active tag to use when accounting {@link Socket} traffic originating
    214      * from the current thread. Only one active tag per thread is supported.
    215      * <p>
    216      * Changes only take effect during subsequent calls to
    217      * {@link #tagSocket(Socket)}.
    218      * <p>
    219      * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
    220      * used internally by system services like {@link DownloadManager} when
    221      * performing traffic on behalf of an application.
    222      *
    223      * @return the current tag for the calling thread, which can be used to
    224      *         restore any existing values after a nested operation is finished
    225      */
    226     public static int getAndSetThreadStatsTag(int tag) {
    227         return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
    228     }
    229 
    230     /**
    231      * Set active tag to use when accounting {@link Socket} traffic originating
    232      * from the current thread. The tag used internally is well-defined to
    233      * distinguish all backup-related traffic.
    234      *
    235      * @hide
    236      */
    237     @SystemApi
    238     public static void setThreadStatsTagBackup() {
    239         setThreadStatsTag(TAG_SYSTEM_BACKUP);
    240     }
    241 
    242     /**
    243      * Set active tag to use when accounting {@link Socket} traffic originating
    244      * from the current thread. The tag used internally is well-defined to
    245      * distinguish all restore-related traffic.
    246      *
    247      * @hide
    248      */
    249     @SystemApi
    250     public static void setThreadStatsTagRestore() {
    251         setThreadStatsTag(TAG_SYSTEM_RESTORE);
    252     }
    253 
    254     /**
    255      * Set active tag to use when accounting {@link Socket} traffic originating
    256      * from the current thread. The tag used internally is well-defined to
    257      * distinguish all code (typically APKs) downloaded by an app store on
    258      * behalf of the app, such as updates.
    259      *
    260      * @hide
    261      */
    262     @SystemApi
    263     public static void setThreadStatsTagApp() {
    264         setThreadStatsTag(TAG_SYSTEM_APP);
    265     }
    266 
    267     /**
    268      * Get the active tag used when accounting {@link Socket} traffic originating
    269      * from the current thread. Only one active tag per thread is supported.
    270      * {@link #tagSocket(Socket)}.
    271      *
    272      * @see #setThreadStatsTag(int)
    273      */
    274     public static int getThreadStatsTag() {
    275         return NetworkManagementSocketTagger.getThreadSocketStatsTag();
    276     }
    277 
    278     /**
    279      * Clear any active tag set to account {@link Socket} traffic originating
    280      * from the current thread.
    281      *
    282      * @see #setThreadStatsTag(int)
    283      */
    284     public static void clearThreadStatsTag() {
    285         NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
    286     }
    287 
    288     /**
    289      * Set specific UID to use when accounting {@link Socket} traffic
    290      * originating from the current thread. Designed for use when performing an
    291      * operation on behalf of another application, or when another application
    292      * is performing operations on your behalf.
    293      * <p>
    294      * Any app can <em>accept</em> blame for traffic performed on a socket
    295      * originally created by another app by calling this method with the
    296      * {@link android.system.Os#getuid()} value. However, only apps holding the
    297      * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
    298      * <em>assign</em> blame to another UIDs.
    299      * <p>
    300      * Changes only take effect during subsequent calls to
    301      * {@link #tagSocket(Socket)}.
    302      */
    303     @SuppressLint("Doclava125")
    304     public static void setThreadStatsUid(int uid) {
    305         NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
    306     }
    307 
    308     /**
    309      * Get the active UID used when accounting {@link Socket} traffic originating
    310      * from the current thread. Only one active tag per thread is supported.
    311      * {@link #tagSocket(Socket)}.
    312      *
    313      * @see #setThreadStatsUid(int)
    314      */
    315     public static int getThreadStatsUid() {
    316         return NetworkManagementSocketTagger.getThreadSocketStatsUid();
    317     }
    318 
    319     /**
    320      * Set specific UID to use when accounting {@link Socket} traffic
    321      * originating from the current thread as the calling UID. Designed for use
    322      * when another application is performing operations on your behalf.
    323      * <p>
    324      * Changes only take effect during subsequent calls to
    325      * {@link #tagSocket(Socket)}.
    326      *
    327      * @removed
    328      * @deprecated use {@link #setThreadStatsUid(int)} instead.
    329      */
    330     @Deprecated
    331     public static void setThreadStatsUidSelf() {
    332         setThreadStatsUid(android.os.Process.myUid());
    333     }
    334 
    335     /**
    336      * Clear any active UID set to account {@link Socket} traffic originating
    337      * from the current thread.
    338      *
    339      * @see #setThreadStatsUid(int)
    340      */
    341     @SuppressLint("Doclava125")
    342     public static void clearThreadStatsUid() {
    343         NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
    344     }
    345 
    346     /**
    347      * Tag the given {@link Socket} with any statistics parameters active for
    348      * the current thread. Subsequent calls always replace any existing
    349      * parameters. When finished, call {@link #untagSocket(Socket)} to remove
    350      * statistics parameters.
    351      *
    352      * @see #setThreadStatsTag(int)
    353      */
    354     public static void tagSocket(Socket socket) throws SocketException {
    355         SocketTagger.get().tag(socket);
    356     }
    357 
    358     /**
    359      * Remove any statistics parameters from the given {@link Socket}.
    360      * <p>
    361      * In Android 8.1 (API level 27) and lower, a socket is automatically
    362      * untagged when it's sent to another process using binder IPC with a
    363      * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
    364      * and higher, the socket tag is kept when the socket is sent to another
    365      * process using binder IPC. You can mimic the previous behavior by
    366      * calling {@code untagSocket()} before sending the socket to another
    367      * process.
    368      */
    369     public static void untagSocket(Socket socket) throws SocketException {
    370         SocketTagger.get().untag(socket);
    371     }
    372 
    373     /**
    374      * Tag the given {@link DatagramSocket} with any statistics parameters
    375      * active for the current thread. Subsequent calls always replace any
    376      * existing parameters. When finished, call
    377      * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
    378      * parameters.
    379      *
    380      * @see #setThreadStatsTag(int)
    381      */
    382     public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
    383         SocketTagger.get().tag(socket);
    384     }
    385 
    386     /**
    387      * Remove any statistics parameters from the given {@link DatagramSocket}.
    388      */
    389     public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
    390         SocketTagger.get().untag(socket);
    391     }
    392 
    393     /**
    394      * Tag the given {@link FileDescriptor} socket with any statistics
    395      * parameters active for the current thread. Subsequent calls always replace
    396      * any existing parameters. When finished, call
    397      * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
    398      * parameters.
    399      *
    400      * @see #setThreadStatsTag(int)
    401      */
    402     public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
    403         SocketTagger.get().tag(fd);
    404     }
    405 
    406     /**
    407      * Remove any statistics parameters from the given {@link FileDescriptor}
    408      * socket.
    409      */
    410     public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
    411         SocketTagger.get().untag(fd);
    412     }
    413 
    414     /**
    415      * Start profiling data usage for current UID. Only one profiling session
    416      * can be active at a time.
    417      *
    418      * @hide
    419      */
    420     public static void startDataProfiling(Context context) {
    421         synchronized (sProfilingLock) {
    422             if (sActiveProfilingStart != null) {
    423                 throw new IllegalStateException("already profiling data");
    424             }
    425 
    426             // take snapshot in time; we calculate delta later
    427             sActiveProfilingStart = getDataLayerSnapshotForUid(context);
    428         }
    429     }
    430 
    431     /**
    432      * Stop profiling data usage for current UID.
    433      *
    434      * @return Detailed {@link NetworkStats} of data that occurred since last
    435      *         {@link #startDataProfiling(Context)} call.
    436      * @hide
    437      */
    438     public static NetworkStats stopDataProfiling(Context context) {
    439         synchronized (sProfilingLock) {
    440             if (sActiveProfilingStart == null) {
    441                 throw new IllegalStateException("not profiling data");
    442             }
    443 
    444             // subtract starting values and return delta
    445             final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
    446             final NetworkStats profilingDelta = NetworkStats.subtract(
    447                     profilingStop, sActiveProfilingStart, null, null);
    448             sActiveProfilingStart = null;
    449             return profilingDelta;
    450         }
    451     }
    452 
    453     /**
    454      * Increment count of network operations performed under the accounting tag
    455      * currently active on the calling thread. This can be used to derive
    456      * bytes-per-operation.
    457      *
    458      * @param operationCount Number of operations to increment count by.
    459      */
    460     public static void incrementOperationCount(int operationCount) {
    461         final int tag = getThreadStatsTag();
    462         incrementOperationCount(tag, operationCount);
    463     }
    464 
    465     /**
    466      * Increment count of network operations performed under the given
    467      * accounting tag. This can be used to derive bytes-per-operation.
    468      *
    469      * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
    470      * @param operationCount Number of operations to increment count by.
    471      */
    472     public static void incrementOperationCount(int tag, int operationCount) {
    473         final int uid = android.os.Process.myUid();
    474         try {
    475             getStatsService().incrementOperationCount(uid, tag, operationCount);
    476         } catch (RemoteException e) {
    477             throw e.rethrowFromSystemServer();
    478         }
    479     }
    480 
    481     /** {@hide} */
    482     public static void closeQuietly(INetworkStatsSession session) {
    483         // TODO: move to NetworkStatsService once it exists
    484         if (session != null) {
    485             try {
    486                 session.close();
    487             } catch (RuntimeException rethrown) {
    488                 throw rethrown;
    489             } catch (Exception ignored) {
    490             }
    491         }
    492     }
    493 
    494     private static long addIfSupported(long stat) {
    495         return (stat == UNSUPPORTED) ? 0 : stat;
    496     }
    497 
    498     /**
    499      * Return number of packets transmitted across mobile networks since device
    500      * boot. Counts packets across all mobile network interfaces, and always
    501      * increases monotonically since device boot. Statistics are measured at the
    502      * network layer, so they include both TCP and UDP usage.
    503      * <p>
    504      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    505      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    506      */
    507     public static long getMobileTxPackets() {
    508         long total = 0;
    509         for (String iface : getMobileIfaces()) {
    510             total += addIfSupported(getTxPackets(iface));
    511         }
    512         return total;
    513     }
    514 
    515     /**
    516      * Return number of packets received across mobile networks since device
    517      * boot. Counts packets across all mobile network interfaces, and always
    518      * increases monotonically since device boot. Statistics are measured at the
    519      * network layer, so they include both TCP and UDP usage.
    520      * <p>
    521      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    522      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    523      */
    524     public static long getMobileRxPackets() {
    525         long total = 0;
    526         for (String iface : getMobileIfaces()) {
    527             total += addIfSupported(getRxPackets(iface));
    528         }
    529         return total;
    530     }
    531 
    532     /**
    533      * Return number of bytes transmitted across mobile networks since device
    534      * boot. Counts packets across all mobile network interfaces, and always
    535      * increases monotonically since device boot. Statistics are measured at the
    536      * network layer, so they include both TCP and UDP usage.
    537      * <p>
    538      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    539      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    540      */
    541     public static long getMobileTxBytes() {
    542         long total = 0;
    543         for (String iface : getMobileIfaces()) {
    544             total += addIfSupported(getTxBytes(iface));
    545         }
    546         return total;
    547     }
    548 
    549     /**
    550      * Return number of bytes received across mobile networks since device boot.
    551      * Counts packets across all mobile network interfaces, and always increases
    552      * monotonically since device boot. Statistics are measured at the network
    553      * layer, so they include both TCP and UDP usage.
    554      * <p>
    555      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    556      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    557      */
    558     public static long getMobileRxBytes() {
    559         long total = 0;
    560         for (String iface : getMobileIfaces()) {
    561             total += addIfSupported(getRxBytes(iface));
    562         }
    563         return total;
    564     }
    565 
    566     /** {@hide} */
    567     @UnsupportedAppUsage
    568     public static long getMobileTcpRxPackets() {
    569         long total = 0;
    570         for (String iface : getMobileIfaces()) {
    571             long stat = UNSUPPORTED;
    572             try {
    573                 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
    574             } catch (RemoteException e) {
    575                 throw e.rethrowFromSystemServer();
    576             }
    577             total += addIfSupported(stat);
    578         }
    579         return total;
    580     }
    581 
    582     /** {@hide} */
    583     @UnsupportedAppUsage
    584     public static long getMobileTcpTxPackets() {
    585         long total = 0;
    586         for (String iface : getMobileIfaces()) {
    587             long stat = UNSUPPORTED;
    588             try {
    589                 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
    590             } catch (RemoteException e) {
    591                 throw e.rethrowFromSystemServer();
    592             }
    593             total += addIfSupported(stat);
    594         }
    595         return total;
    596     }
    597 
    598     /** {@hide} */
    599     public static long getTxPackets(String iface) {
    600         try {
    601             return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
    602         } catch (RemoteException e) {
    603             throw e.rethrowFromSystemServer();
    604         }
    605     }
    606 
    607     /** {@hide} */
    608     public static long getRxPackets(String iface) {
    609         try {
    610             return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
    611         } catch (RemoteException e) {
    612             throw e.rethrowFromSystemServer();
    613         }
    614     }
    615 
    616     /** {@hide} */
    617     @UnsupportedAppUsage
    618     public static long getTxBytes(String iface) {
    619         try {
    620             return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
    621         } catch (RemoteException e) {
    622             throw e.rethrowFromSystemServer();
    623         }
    624     }
    625 
    626     /** {@hide} */
    627     @UnsupportedAppUsage
    628     public static long getRxBytes(String iface) {
    629         try {
    630             return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
    631         } catch (RemoteException e) {
    632             throw e.rethrowFromSystemServer();
    633         }
    634     }
    635 
    636     /** {@hide} */
    637     @TestApi
    638     public static long getLoopbackTxPackets() {
    639         try {
    640             return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
    641         } catch (RemoteException e) {
    642             throw e.rethrowFromSystemServer();
    643         }
    644     }
    645 
    646     /** {@hide} */
    647     @TestApi
    648     public static long getLoopbackRxPackets() {
    649         try {
    650             return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
    651         } catch (RemoteException e) {
    652             throw e.rethrowFromSystemServer();
    653         }
    654     }
    655 
    656     /** {@hide} */
    657     @TestApi
    658     public static long getLoopbackTxBytes() {
    659         try {
    660             return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
    661         } catch (RemoteException e) {
    662             throw e.rethrowFromSystemServer();
    663         }
    664     }
    665 
    666     /** {@hide} */
    667     @TestApi
    668     public static long getLoopbackRxBytes() {
    669         try {
    670             return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
    671         } catch (RemoteException e) {
    672             throw e.rethrowFromSystemServer();
    673         }
    674     }
    675 
    676     /**
    677      * Return number of packets transmitted since device boot. Counts packets
    678      * across all network interfaces, and always increases monotonically since
    679      * device boot. Statistics are measured at the network layer, so they
    680      * include both TCP and UDP usage.
    681      * <p>
    682      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    683      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    684      */
    685     public static long getTotalTxPackets() {
    686         try {
    687             return getStatsService().getTotalStats(TYPE_TX_PACKETS);
    688         } catch (RemoteException e) {
    689             throw e.rethrowFromSystemServer();
    690         }
    691     }
    692 
    693     /**
    694      * Return number of packets received since device boot. Counts packets
    695      * across all network interfaces, and always increases monotonically since
    696      * device boot. Statistics are measured at the network layer, so they
    697      * include both TCP and UDP usage.
    698      * <p>
    699      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    700      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    701      */
    702     public static long getTotalRxPackets() {
    703         try {
    704             return getStatsService().getTotalStats(TYPE_RX_PACKETS);
    705         } catch (RemoteException e) {
    706             throw e.rethrowFromSystemServer();
    707         }
    708     }
    709 
    710     /**
    711      * Return number of bytes transmitted since device boot. Counts packets
    712      * across all network interfaces, and always increases monotonically since
    713      * device boot. Statistics are measured at the network layer, so they
    714      * include both TCP and UDP usage.
    715      * <p>
    716      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    717      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    718      */
    719     public static long getTotalTxBytes() {
    720         try {
    721             return getStatsService().getTotalStats(TYPE_TX_BYTES);
    722         } catch (RemoteException e) {
    723             throw e.rethrowFromSystemServer();
    724         }
    725     }
    726 
    727     /**
    728      * Return number of bytes received since device boot. Counts packets across
    729      * all network interfaces, and always increases monotonically since device
    730      * boot. Statistics are measured at the network layer, so they include both
    731      * TCP and UDP usage.
    732      * <p>
    733      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    734      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    735      */
    736     public static long getTotalRxBytes() {
    737         try {
    738             return getStatsService().getTotalStats(TYPE_RX_BYTES);
    739         } catch (RemoteException e) {
    740             throw e.rethrowFromSystemServer();
    741         }
    742     }
    743 
    744     /**
    745      * Return number of bytes transmitted by the given UID since device boot.
    746      * Counts packets across all network interfaces, and always increases
    747      * monotonically since device boot. Statistics are measured at the network
    748      * layer, so they include both TCP and UDP usage.
    749      * <p>
    750      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
    751      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
    752      * <p>
    753      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
    754      * report traffic statistics for the calling UID. It will return
    755      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
    756      * historical network statistics belonging to other UIDs, use
    757      * {@link NetworkStatsManager}.
    758      *
    759      * @see android.os.Process#myUid()
    760      * @see android.content.pm.ApplicationInfo#uid
    761      */
    762     public static long getUidTxBytes(int uid) {
    763         // This isn't actually enforcing any security; it just returns the
    764         // unsupported value. The real filtering is done at the kernel level.
    765         final int callingUid = android.os.Process.myUid();
    766         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
    767             try {
    768                 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
    769             } catch (RemoteException e) {
    770                 throw e.rethrowFromSystemServer();
    771             }
    772         } else {
    773             return UNSUPPORTED;
    774         }
    775     }
    776 
    777     /**
    778      * Return number of bytes received by the given UID since device boot.
    779      * Counts packets across all network interfaces, and always increases
    780      * monotonically since device boot. Statistics are measured at the network
    781      * layer, so they include both TCP and UDP usage.
    782      * <p>
    783      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
    784      * {@link #UNSUPPORTED} on devices where statistics aren't available.
    785      * <p>
    786      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
    787      * report traffic statistics for the calling UID. It will return
    788      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
    789      * historical network statistics belonging to other UIDs, use
    790      * {@link NetworkStatsManager}.
    791      *
    792      * @see android.os.Process#myUid()
    793      * @see android.content.pm.ApplicationInfo#uid
    794      */
    795     public static long getUidRxBytes(int uid) {
    796         // This isn't actually enforcing any security; it just returns the
    797         // unsupported value. The real filtering is done at the kernel level.
    798         final int callingUid = android.os.Process.myUid();
    799         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
    800             try {
    801                 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
    802             } catch (RemoteException e) {
    803                 throw e.rethrowFromSystemServer();
    804             }
    805         } else {
    806             return UNSUPPORTED;
    807         }
    808     }
    809 
    810     /**
    811      * Return number of packets transmitted by the given UID since device boot.
    812      * Counts packets across all network interfaces, and always increases
    813      * monotonically since device boot. Statistics are measured at the network
    814      * layer, so they include both TCP and UDP usage.
    815      * <p>
    816      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
    817      * {@link #UNSUPPORTED} on devices where statistics aren't available.
    818      * <p>
    819      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
    820      * report traffic statistics for the calling UID. It will return
    821      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
    822      * historical network statistics belonging to other UIDs, use
    823      * {@link NetworkStatsManager}.
    824      *
    825      * @see android.os.Process#myUid()
    826      * @see android.content.pm.ApplicationInfo#uid
    827      */
    828     public static long getUidTxPackets(int uid) {
    829         // This isn't actually enforcing any security; it just returns the
    830         // unsupported value. The real filtering is done at the kernel level.
    831         final int callingUid = android.os.Process.myUid();
    832         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
    833             try {
    834                 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
    835             } catch (RemoteException e) {
    836                 throw e.rethrowFromSystemServer();
    837             }
    838         } else {
    839             return UNSUPPORTED;
    840         }
    841     }
    842 
    843     /**
    844      * Return number of packets received by the given UID since device boot.
    845      * Counts packets across all network interfaces, and always increases
    846      * monotonically since device boot. Statistics are measured at the network
    847      * layer, so they include both TCP and UDP usage.
    848      * <p>
    849      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
    850      * {@link #UNSUPPORTED} on devices where statistics aren't available.
    851      * <p>
    852      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
    853      * report traffic statistics for the calling UID. It will return
    854      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
    855      * historical network statistics belonging to other UIDs, use
    856      * {@link NetworkStatsManager}.
    857      *
    858      * @see android.os.Process#myUid()
    859      * @see android.content.pm.ApplicationInfo#uid
    860      */
    861     public static long getUidRxPackets(int uid) {
    862         // This isn't actually enforcing any security; it just returns the
    863         // unsupported value. The real filtering is done at the kernel level.
    864         final int callingUid = android.os.Process.myUid();
    865         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
    866             try {
    867                 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
    868             } catch (RemoteException e) {
    869                 throw e.rethrowFromSystemServer();
    870             }
    871         } else {
    872             return UNSUPPORTED;
    873         }
    874     }
    875 
    876     /**
    877      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    878      *             transport layer statistics are no longer available, and will
    879      *             always return {@link #UNSUPPORTED}.
    880      * @see #getUidTxBytes(int)
    881      */
    882     @Deprecated
    883     public static long getUidTcpTxBytes(int uid) {
    884         return UNSUPPORTED;
    885     }
    886 
    887     /**
    888      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    889      *             transport layer statistics are no longer available, and will
    890      *             always return {@link #UNSUPPORTED}.
    891      * @see #getUidRxBytes(int)
    892      */
    893     @Deprecated
    894     public static long getUidTcpRxBytes(int uid) {
    895         return UNSUPPORTED;
    896     }
    897 
    898     /**
    899      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    900      *             transport layer statistics are no longer available, and will
    901      *             always return {@link #UNSUPPORTED}.
    902      * @see #getUidTxBytes(int)
    903      */
    904     @Deprecated
    905     public static long getUidUdpTxBytes(int uid) {
    906         return UNSUPPORTED;
    907     }
    908 
    909     /**
    910      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    911      *             transport layer statistics are no longer available, and will
    912      *             always return {@link #UNSUPPORTED}.
    913      * @see #getUidRxBytes(int)
    914      */
    915     @Deprecated
    916     public static long getUidUdpRxBytes(int uid) {
    917         return UNSUPPORTED;
    918     }
    919 
    920     /**
    921      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    922      *             transport layer statistics are no longer available, and will
    923      *             always return {@link #UNSUPPORTED}.
    924      * @see #getUidTxPackets(int)
    925      */
    926     @Deprecated
    927     public static long getUidTcpTxSegments(int uid) {
    928         return UNSUPPORTED;
    929     }
    930 
    931     /**
    932      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    933      *             transport layer statistics are no longer available, and will
    934      *             always return {@link #UNSUPPORTED}.
    935      * @see #getUidRxPackets(int)
    936      */
    937     @Deprecated
    938     public static long getUidTcpRxSegments(int uid) {
    939         return UNSUPPORTED;
    940     }
    941 
    942     /**
    943      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    944      *             transport layer statistics are no longer available, and will
    945      *             always return {@link #UNSUPPORTED}.
    946      * @see #getUidTxPackets(int)
    947      */
    948     @Deprecated
    949     public static long getUidUdpTxPackets(int uid) {
    950         return UNSUPPORTED;
    951     }
    952 
    953     /**
    954      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
    955      *             transport layer statistics are no longer available, and will
    956      *             always return {@link #UNSUPPORTED}.
    957      * @see #getUidRxPackets(int)
    958      */
    959     @Deprecated
    960     public static long getUidUdpRxPackets(int uid) {
    961         return UNSUPPORTED;
    962     }
    963 
    964     /**
    965      * Return detailed {@link NetworkStats} for the current UID. Requires no
    966      * special permission.
    967      */
    968     private static NetworkStats getDataLayerSnapshotForUid(Context context) {
    969         // TODO: take snapshot locally, since proc file is now visible
    970         final int uid = android.os.Process.myUid();
    971         try {
    972             return getStatsService().getDataLayerSnapshotForUid(uid);
    973         } catch (RemoteException e) {
    974             throw e.rethrowFromSystemServer();
    975         }
    976     }
    977 
    978     /**
    979      * Return set of any ifaces associated with mobile networks since boot.
    980      * Interfaces are never removed from this list, so counters should always be
    981      * monotonic.
    982      */
    983     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
    984     private static String[] getMobileIfaces() {
    985         try {
    986             return getStatsService().getMobileIfaces();
    987         } catch (RemoteException e) {
    988             throw e.rethrowFromSystemServer();
    989         }
    990     }
    991 
    992     // NOTE: keep these in sync with android_net_TrafficStats.cpp
    993     private static final int TYPE_RX_BYTES = 0;
    994     private static final int TYPE_RX_PACKETS = 1;
    995     private static final int TYPE_TX_BYTES = 2;
    996     private static final int TYPE_TX_PACKETS = 3;
    997     private static final int TYPE_TCP_RX_PACKETS = 4;
    998     private static final int TYPE_TCP_TX_PACKETS = 5;
    999 }
   1000