1 /*
2  * Copyright (C) 2022 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.companion.utils;
18 
19 import static org.xmlpull.v1.XmlPullParser.END_TAG;
20 import static org.xmlpull.v1.XmlPullParser.START_TAG;
21 
22 import android.annotation.NonNull;
23 import android.annotation.UserIdInt;
24 import android.os.Environment;
25 import android.util.AtomicFile;
26 import android.util.Slog;
27 
28 import com.android.internal.util.FunctionalUtils.ThrowingConsumer;
29 
30 import org.xmlpull.v1.XmlPullParser;
31 import org.xmlpull.v1.XmlPullParserException;
32 
33 import java.io.ByteArrayOutputStream;
34 import java.io.File;
35 import java.io.FileInputStream;
36 import java.io.FileOutputStream;
37 import java.io.IOException;
38 
39 /**
40  * Util class for CDM data stores
41  */
42 public final class DataStoreUtils {
43     private static final String TAG = "CDM_DataStoreUtils";
44 
45     /**
46      * Check if the parser pointer is at the start of the tag
47      */
isStartOfTag(@onNull XmlPullParser parser, @NonNull String tag)48     public static boolean isStartOfTag(@NonNull XmlPullParser parser, @NonNull String tag)
49             throws XmlPullParserException {
50         return parser.getEventType() == START_TAG && tag.equals(parser.getName());
51     }
52 
53     /**
54      * Check if the parser pointer is at the end of the tag
55      */
isEndOfTag(@onNull XmlPullParser parser, @NonNull String tag)56     public static boolean isEndOfTag(@NonNull XmlPullParser parser, @NonNull String tag)
57             throws XmlPullParserException {
58         return parser.getEventType() == END_TAG && tag.equals(parser.getName());
59     }
60 
61     /**
62      * Creates {@link AtomicFile} object that represents the back-up for the given user.
63      *
64      * IMPORTANT: the method will ALWAYS return the same {@link AtomicFile} object, which makes it
65      * possible to synchronize reads and writes to the file using the returned object.
66      *
67      * @param userId the userId to retrieve the storage file
68      * @param fileName the storage file name
69      * @return an AtomicFile for the user
70      */
71     @NonNull
createStorageFileForUser(@serIdInt int userId, String fileName)72     public static AtomicFile createStorageFileForUser(@UserIdInt int userId, String fileName) {
73         return new AtomicFile(getBaseStorageFileForUser(userId, fileName));
74     }
75 
76     @NonNull
getBaseStorageFileForUser(@serIdInt int userId, String fileName)77     private static File getBaseStorageFileForUser(@UserIdInt int userId, String fileName) {
78         return new File(Environment.getDataSystemDeDirectory(userId), fileName);
79     }
80 
81     /**
82      * Writing to file could fail, for example, if the user has been recently removed and so was
83      * their DE (/data/system_de/[user-id]/) directory.
84      */
writeToFileSafely( @onNull AtomicFile file, @NonNull ThrowingConsumer<FileOutputStream> consumer)85     public static void writeToFileSafely(
86             @NonNull AtomicFile file, @NonNull ThrowingConsumer<FileOutputStream> consumer) {
87         try {
88             file.write(consumer);
89         } catch (Exception e) {
90             Slog.e(TAG, "Error while writing to file " + file, e);
91         }
92     }
93 
94     /**
95      * Read a file and return the byte array containing the bytes of the file.
96      */
97     @NonNull
fileToByteArray(@onNull AtomicFile file)98     public static byte[] fileToByteArray(@NonNull AtomicFile file) {
99         if (!file.getBaseFile().exists()) {
100             Slog.d(TAG, "File does not exist");
101             return new byte[0];
102         }
103         try (FileInputStream in = file.openRead()) {
104             ByteArrayOutputStream bytes = new ByteArrayOutputStream();
105             byte[] buffer = new byte[1024];
106             int read;
107             while ((read = in.read(buffer)) != -1) {
108                 bytes.write(buffer, 0, read);
109             }
110             return bytes.toByteArray();
111         } catch (IOException e) {
112             Slog.e(TAG, "Error while reading requests file", e);
113         }
114         return new byte[0];
115     }
116 
DataStoreUtils()117     private DataStoreUtils() {
118     }
119 }
120