summaryrefslogtreecommitdiff
path: root/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java
blob: 76ee097c8c9354d8f5c6a01497366f41d05f9878 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.netstats;

import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
import static android.net.NetworkStats.SET_DEFAULT;
import static android.net.NetworkStats.TAG_NONE;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;

import android.annotation.NonNull;
import android.annotation.StringDef;
import android.annotation.SystemApi;
import android.net.NetworkIdentity;
import android.net.NetworkStatsCollection;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
import android.os.Environment;
import android.util.AtomicFile;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.FastDataInput;

import libcore.io.IoUtils;

import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * Helper class to read old version of persistent network statistics.
 *
 * The implementation is intended to be modified by OEM partners to
 * accommodate their custom changes.
 *
 * @hide
 */
@SystemApi(client = MODULE_LIBRARIES)
public class NetworkStatsDataMigrationUtils {
    /**
     * Prefix of the files which are used to store per network interface statistics.
     */
    public static final String PREFIX_XT = "xt";
    /**
     * Prefix of the files which are used to store per uid statistics.
     */
    public static final String PREFIX_UID = "uid";
    /**
     * Prefix of the files which are used to store per uid tagged traffic statistics.
     */
    public static final String PREFIX_UID_TAG = "uid_tag";

    /** @hide */
    @StringDef(prefix = {"PREFIX_"}, value = {
        PREFIX_XT,
        PREFIX_UID,
        PREFIX_UID_TAG,
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface Prefix {}

    private static final HashMap<String, String> sPrefixLegacyFileNameMap =
            new HashMap<String, String>() {{
                put(PREFIX_XT, "netstats_xt.bin");
                put(PREFIX_UID, "netstats_uid.bin");
                put(PREFIX_UID_TAG, "netstats_uid.bin");
            }};

    // These version constants are copied from NetworkStatsCollection/History, which is okay for
    // OEMs to modify to adapt their own logic.
    private static class CollectionVersion {
        static final int VERSION_NETWORK_INIT = 1;

        static final int VERSION_UID_INIT = 1;
        static final int VERSION_UID_WITH_IDENT = 2;
        static final int VERSION_UID_WITH_TAG = 3;
        static final int VERSION_UID_WITH_SET = 4;

        static final int VERSION_UNIFIED_INIT = 16;
    }

    private static class HistoryVersion {
        static final int VERSION_INIT = 1;
        static final int VERSION_ADD_PACKETS = 2;
        static final int VERSION_ADD_ACTIVE = 3;
    }

    private static class IdentitySetVersion {
        static final int VERSION_INIT = 1;
        static final int VERSION_ADD_ROAMING = 2;
        static final int VERSION_ADD_NETWORK_ID = 3;
        static final int VERSION_ADD_METERED = 4;
        static final int VERSION_ADD_DEFAULT_NETWORK = 5;
        static final int VERSION_ADD_OEM_MANAGED_NETWORK = 6;
        static final int VERSION_ADD_SUB_ID = 7;
    }

    /**
     * File header magic number: "ANET". The definition is copied from NetworkStatsCollection,
     * but it is fine for OEM to re-define to their own value to adapt the legacy file reading
     * logic.
     */
    private static final int FILE_MAGIC = 0x414E4554;
    /** Default buffer size from BufferedInputStream */
    private static final int BUFFER_SIZE = 8192;

    // Constructing this object is not allowed.
    private NetworkStatsDataMigrationUtils() {
    }

    // Used to read files at /data/system/netstats_*.bin.
    @NonNull
    private static File getPlatformSystemDir() {
        return new File(Environment.getDataDirectory(), "system");
    }

    // Used to read files at /data/system/netstats/<tag>.<start>-<end>.
    @NonNull
    private static File getPlatformBaseDir() {
        File baseDir = new File(getPlatformSystemDir(), "netstats");
        baseDir.mkdirs();
        return baseDir;
    }

    // Get /data/system/netstats_*.bin legacy files. Does not check for existence.
    @NonNull
    private static File getLegacyBinFileForPrefix(@NonNull @Prefix String prefix) {
        return new File(getPlatformSystemDir(), sPrefixLegacyFileNameMap.get(prefix));
    }

    // List /data/system/netstats/[xt|uid|uid_tag].<start>-<end> legacy files.
    @NonNull
    private static ArrayList<File> getPlatformFileListForPrefix(@NonNull @Prefix String prefix) {
        final ArrayList<File> list = new ArrayList<>();
        final File platformFiles = getPlatformBaseDir();
        if (platformFiles.exists()) {
            final String[] files = platformFiles.list();
            if (files == null) return list;
            Arrays.sort(files);
            for (String name : files) {
                // Skip when prefix doesn't match.
                if (!name.startsWith(prefix + ".")) continue;

                list.add(new File(platformFiles, name));
            }
        }
        return list;
    }

    /**
     * Read legacy persisted network stats from disk.
     *
     * This function provides the implementation to read legacy network stats
     * from disk. It is used for migration of legacy network stats into the
     * stats provided by the Connectivity module.
     * This function needs to know about the previous format(s) of the network
     * stats data that might be stored on this device so it can be read and
     * conserved upon upgrade to Android 13 or above.
     *
     * This function will be called multiple times sequentially, all on the
     * same thread, and will not be called multiple times concurrently. This
     * function is expected to do a substantial amount of disk access, and
     * doesn't need to return particularly fast, but the first boot after
     * an upgrade to Android 13+ will be held until migration is done. As
     * migration is only necessary once, after the first boot following the
     * upgrade, this delay is not incurred.
     *
     * If this function fails in any way, it should throw an exception. If this
     * happens, the system can't know about the data that was stored in the
     * legacy files, but it will still count data usage happening on this
     * session. On the next boot, the system will try migration again, and
     * merge the returned data with the data used with the previous session.
     * The system will only try the migration up to three (3) times. The remaining
     * count is stored in the netstats_import_legacy_file_needed device config. The
     * legacy data is never deleted by the mainline module to avoid any possible
     * data loss.
     *
     * It is possible to set the netstats_import_legacy_file_needed device config
     * to any positive integer to force the module to perform the migration. This
     * can be achieved by calling the following command before rebooting :
     *     adb shell device_config put connectivity netstats_import_legacy_file_needed 1
     *
     * The AOSP implementation provides code to read persisted network stats as
     * they were written by AOSP prior to Android 13.
     * OEMs who have used the AOSP implementation of persisting network stats
     * to disk don't need to change anything.
     * OEM that had modifications to this format should modify this function
     * to read from their custom file format or locations if necessary.
     *
     * @param prefix         Type of data which is being read by the service.
     * @param bucketDuration Duration of the buckets of the object, in milliseconds.
     * @return {@link NetworkStatsCollection} instance.
     */
    @NonNull
    public static NetworkStatsCollection readPlatformCollection(
            @NonNull @Prefix String prefix, long bucketDuration) throws IOException {
        final NetworkStatsCollection.Builder builder =
                new NetworkStatsCollection.Builder(bucketDuration);

        // Import /data/system/netstats_uid.bin legacy files if exists.
        switch (prefix) {
            case PREFIX_UID:
            case PREFIX_UID_TAG:
                final File uidFile = getLegacyBinFileForPrefix(prefix);
                if (uidFile.exists()) {
                    readLegacyUid(builder, uidFile, PREFIX_UID_TAG.equals(prefix) ? true : false);
                }
                break;
            default:
                // Ignore other types.
        }

        // Import /data/system/netstats/[xt|uid|uid_tag].<start>-<end> legacy files if exists.
        final ArrayList<File> platformFiles = getPlatformFileListForPrefix(prefix);
        for (final File platformFile : platformFiles) {
            if (platformFile.exists()) {
                readPlatformCollection(builder, platformFile);
            }
        }

        return builder.build();
    }

    private static void readPlatformCollection(@NonNull NetworkStatsCollection.Builder builder,
            @NonNull File file) throws IOException {
        final FileInputStream is = new FileInputStream(file);
        final FastDataInput dataIn = new FastDataInput(is, BUFFER_SIZE);
        try {
            readPlatformCollection(builder, dataIn);
        } finally {
            IoUtils.closeQuietly(dataIn);
        }
    }

    /**
     * Helper function to read old version of NetworkStatsCollections that resided in the platform.
     *
     * @hide
     */
    @VisibleForTesting
    public static void readPlatformCollection(@NonNull NetworkStatsCollection.Builder builder,
            @NonNull DataInput in) throws IOException {
        // verify file magic header intact
        final int magic = in.readInt();
        if (magic != FILE_MAGIC) {
            throw new ProtocolException("unexpected magic: " + magic);
        }

        final int version = in.readInt();
        switch (version) {
            case CollectionVersion.VERSION_UNIFIED_INIT: {
                // uid := size *(NetworkIdentitySet size *(uid set tag NetworkStatsHistory))
                final int identSize = in.readInt();
                for (int i = 0; i < identSize; i++) {
                    final Set<NetworkIdentity> ident = readPlatformNetworkIdentitySet(in);

                    final int size = in.readInt();
                    for (int j = 0; j < size; j++) {
                        final int uid = in.readInt();
                        final int set = in.readInt();
                        final int tag = in.readInt();

                        final NetworkStatsCollection.Key key = new NetworkStatsCollection.Key(
                                ident, uid, set, tag);
                        final NetworkStatsHistory history = readPlatformHistory(in);
                        builder.addEntry(key, history);
                    }
                }
                break;
            }
            default: {
                throw new ProtocolException("unexpected version: " + version);
            }
        }
    }

    // Copied from NetworkStatsHistory#DataStreamUtils.
    private static long[] readFullLongArray(DataInput in) throws IOException {
        final int size = in.readInt();
        if (size < 0) throw new ProtocolException("negative array size");
        final long[] values = new long[size];
        for (int i = 0; i < values.length; i++) {
            values[i] = in.readLong();
        }
        return values;
    }

    // Copied from NetworkStatsHistory#DataStreamUtils.
    private static long[] readVarLongArray(@NonNull DataInput in) throws IOException {
        final int size = in.readInt();
        if (size == -1) return null;
        if (size < 0) throw new ProtocolException("negative array size");
        final long[] values = new long[size];
        for (int i = 0; i < values.length; i++) {
            values[i] = readVarLong(in);
        }
        return values;
    }

    /**
     * Read variable-length {@link Long} using protobuf-style approach.
     */
    // Copied from NetworkStatsHistory#DataStreamUtils.
    private static long readVarLong(DataInput in) throws IOException {
        int shift = 0;
        long result = 0;
        while (shift < 64) {
            byte b = in.readByte();
            result |= (long) (b & 0x7F) << shift;
            if ((b & 0x80) == 0) {
                return result;
            }
            shift += 7;
        }
        throw new ProtocolException("malformed var long");
    }

    // Copied from NetworkIdentitySet.
    private static String readOptionalString(DataInput in) throws IOException {
        if (in.readByte() != 0) {
            return in.readUTF();
        } else {
            return null;
        }
    }

    /**
     * This is copied from NetworkStatsHistory#NetworkStatsHistory(DataInput in). But it is fine
     * for OEM to re-write the logic to adapt the legacy file reading.
     */
    @NonNull
    private static NetworkStatsHistory readPlatformHistory(@NonNull DataInput in)
            throws IOException {
        final long bucketDuration;
        final long[] bucketStart;
        final long[] rxBytes;
        final long[] rxPackets;
        final long[] txBytes;
        final long[] txPackets;
        final long[] operations;
        final int bucketCount;
        long[] activeTime = new long[0];

        final int version = in.readInt();
        switch (version) {
            case HistoryVersion.VERSION_INIT: {
                bucketDuration = in.readLong();
                bucketStart = readFullLongArray(in);
                rxBytes = readFullLongArray(in);
                rxPackets = new long[bucketStart.length];
                txBytes = readFullLongArray(in);
                txPackets = new long[bucketStart.length];
                operations = new long[bucketStart.length];
                bucketCount = bucketStart.length;
                break;
            }
            case HistoryVersion.VERSION_ADD_PACKETS:
            case HistoryVersion.VERSION_ADD_ACTIVE: {
                bucketDuration = in.readLong();
                bucketStart = readVarLongArray(in);
                activeTime = (version >= HistoryVersion.VERSION_ADD_ACTIVE)
                        ? readVarLongArray(in)
                        : new long[bucketStart.length];
                rxBytes = readVarLongArray(in);
                rxPackets = readVarLongArray(in);
                txBytes = readVarLongArray(in);
                txPackets = readVarLongArray(in);
                operations = readVarLongArray(in);
                bucketCount = bucketStart.length;
                break;
            }
            default: {
                throw new ProtocolException("unexpected version: " + version);
            }
        }

        final NetworkStatsHistory.Builder historyBuilder =
                new NetworkStatsHistory.Builder(bucketDuration, bucketCount);
        for (int i = 0; i < bucketCount; i++) {
            final NetworkStatsHistory.Entry entry = new NetworkStatsHistory.Entry(
                    bucketStart[i], activeTime[i],
                    rxBytes[i], rxPackets[i], txBytes[i], txPackets[i], operations[i]);
            historyBuilder.addEntry(entry);
        }

        return historyBuilder.build();
    }

    @NonNull
    private static Set<NetworkIdentity> readPlatformNetworkIdentitySet(@NonNull DataInput in)
            throws IOException {
        final int version = in.readInt();
        final int size = in.readInt();
        final Set<NetworkIdentity> set = new HashSet<>();
        for (int i = 0; i < size; i++) {
            if (version <= IdentitySetVersion.VERSION_INIT) {
                final int ignored = in.readInt();
            }
            final int type = in.readInt();
            final int ratType = in.readInt();
            final String subscriberId = readOptionalString(in);
            final String networkId;
            if (version >= IdentitySetVersion.VERSION_ADD_NETWORK_ID) {
                networkId = readOptionalString(in);
            } else {
                networkId = null;
            }
            final boolean roaming;
            if (version >= IdentitySetVersion.VERSION_ADD_ROAMING) {
                roaming = in.readBoolean();
            } else {
                roaming = false;
            }

            final boolean metered;
            if (version >= IdentitySetVersion.VERSION_ADD_METERED) {
                metered = in.readBoolean();
            } else {
                // If this is the old data and the type is mobile, treat it as metered. (Note that
                // if this is a mobile network, TYPE_MOBILE is the only possible type that could be
                // used.)
                metered = (type == TYPE_MOBILE);
            }

            final boolean defaultNetwork;
            if (version >= IdentitySetVersion.VERSION_ADD_DEFAULT_NETWORK) {
                defaultNetwork = in.readBoolean();
            } else {
                defaultNetwork = true;
            }

            final int oemNetCapabilities;
            if (version >= IdentitySetVersion.VERSION_ADD_OEM_MANAGED_NETWORK) {
                oemNetCapabilities = in.readInt();
            } else {
                oemNetCapabilities = NetworkTemplate.OEM_MANAGED_NO;
            }

            final int subId;
            if (version >= IdentitySetVersion.VERSION_ADD_SUB_ID) {
                subId = in.readInt();
            } else {
                subId = INVALID_SUBSCRIPTION_ID;
            }

            // Legacy files might contain TYPE_MOBILE_* types which were deprecated in later
            // releases. For backward compatibility, record them as TYPE_MOBILE instead.
            final int collapsedLegacyType = getCollapsedLegacyType(type);
            final NetworkIdentity.Builder builder = new NetworkIdentity.Builder()
                    .setType(collapsedLegacyType)
                    .setSubscriberId(subscriberId)
                    .setWifiNetworkKey(networkId)
                    .setRoaming(roaming).setMetered(metered)
                    .setDefaultNetwork(defaultNetwork)
                    .setOemManaged(oemNetCapabilities)
                    .setSubId(subId);
            if (type == TYPE_MOBILE && ratType != NetworkTemplate.NETWORK_TYPE_ALL) {
                builder.setRatType(ratType);
            }
            set.add(builder.build());
        }
        return set;
    }

    private static int getCollapsedLegacyType(int networkType) {
        // The constants are referenced from ConnectivityManager#TYPE_MOBILE_*.
        switch (networkType) {
            case TYPE_MOBILE:
            case TYPE_MOBILE_SUPL:
            case TYPE_MOBILE_MMS:
            case TYPE_MOBILE_DUN:
            case TYPE_MOBILE_HIPRI:
            case 10 /* TYPE_MOBILE_FOTA */:
            case 11 /* TYPE_MOBILE_IMS */:
            case 12 /* TYPE_MOBILE_CBS */:
            case 14 /* TYPE_MOBILE_IA */:
            case 15 /* TYPE_MOBILE_EMERGENCY */:
                return TYPE_MOBILE;
        }
        return networkType;
    }

    private static void readLegacyUid(@NonNull NetworkStatsCollection.Builder builder,
            @NonNull File uidFile, boolean onlyTaggedData) throws IOException {
        final AtomicFile inputFile = new AtomicFile(uidFile);
        DataInputStream in = new DataInputStream(new BufferedInputStream(inputFile.openRead()));
        try {
            readLegacyUid(builder, in, onlyTaggedData);
        } finally {
            IoUtils.closeQuietly(in);
        }
    }

    /**
     * Read legacy Uid statistics file format into the collection.
     *
     * This is copied from {@code NetworkStatsCollection#readLegacyUid}.
     * See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}.
     *
     * @param taggedData whether to read only tagged data (true) or only non-tagged data
     *                   (false). For legacy uid files, the tagged data was stored in
     *                   the same binary file with non-tagged data. But in later releases,
     *                   these data should be kept in different recorders.
     * @hide
     */
    @VisibleForTesting
    public static void readLegacyUid(@NonNull NetworkStatsCollection.Builder builder,
            @NonNull DataInput in, boolean taggedData) throws IOException {
        try {
            // verify file magic header intact
            final int magic = in.readInt();
            if (magic != FILE_MAGIC) {
                throw new ProtocolException("unexpected magic: " + magic);
            }

            final int version = in.readInt();
            switch (version) {
                case CollectionVersion.VERSION_UID_INIT: {
                    // uid := size *(UID NetworkStatsHistory)
                    // drop this data version, since we don't have a good
                    // mapping into NetworkIdentitySet.
                    break;
                }
                case CollectionVersion.VERSION_UID_WITH_IDENT: {
                    // uid := size *(NetworkIdentitySet size *(UID NetworkStatsHistory))
                    // drop this data version, since this version only existed
                    // for a short time.
                    break;
                }
                case CollectionVersion.VERSION_UID_WITH_TAG:
                case CollectionVersion.VERSION_UID_WITH_SET: {
                    // uid := size *(NetworkIdentitySet size *(uid set tag NetworkStatsHistory))
                    final int identSize = in.readInt();
                    for (int i = 0; i < identSize; i++) {
                        final Set<NetworkIdentity> ident = readPlatformNetworkIdentitySet(in);

                        final int size = in.readInt();
                        for (int j = 0; j < size; j++) {
                            final int uid = in.readInt();
                            final int set = (version >= CollectionVersion.VERSION_UID_WITH_SET)
                                    ? in.readInt()
                                    : SET_DEFAULT;
                            final int tag = in.readInt();

                            final NetworkStatsCollection.Key key = new NetworkStatsCollection.Key(
                                    ident, uid, set, tag);
                            final NetworkStatsHistory history = readPlatformHistory(in);

                            if ((tag == TAG_NONE) != taggedData) {
                                builder.addEntry(key, history);
                            }
                        }
                    }
                    break;
                }
                default: {
                    throw new ProtocolException("unknown version: " + version);
                }
            }
        } catch (FileNotFoundException | ProtocolException e) {
            // missing stats is okay, probably first boot
        }
    }
}