1 /*
2  * Copyright (C) 2017 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 #ifndef STORAGE_MANAGER_H
18 #define STORAGE_MANAGER_H
19 
20 #include <android/util/ProtoOutputStream.h>
21 #include <utils/Log.h>
22 #include <utils/RefBase.h>
23 
24 #include "packages/UidMap.h"
25 
26 namespace android {
27 namespace os {
28 namespace statsd {
29 
30 using android::util::ProtoOutputStream;
31 
32 /**
33  * NOTE: these directories are protected by SELinux, any changes here must also update
34  * the SELinux policies.
35  */
36 #define TRAIN_INFO_DIR "/data/misc/train-info"
37 #define TRAIN_INFO_PATH "/data/misc/train-info/train-info.bin"
38 
39 // Magic word at the start of the train info file, change this if changing the file format
40 const uint32_t TRAIN_INFO_FILE_MAGIC = 0xfb7447bf;
41 
42 class StorageManager : public virtual RefBase {
43 public:
44     struct FileInfo {
FileInfoFileInfo45         FileInfo(const std::string& name, bool isHistory, int fileSize, long fileAge)
46             : mFileName(name),
47               mIsHistory(isHistory),
48               mFileSizeBytes(fileSize),
49               mFileAgeSec(fileAge) {
50         }
51         std::string mFileName;
52         bool mIsHistory;
53         int mFileSizeBytes;
54         long mFileAgeSec;
55     };
56 
57     /**
58      * Writes a given byte array as a file to the specified file path.
59      *
60      * A new file is created if the file does not already exist.
61      * If the file already exists, it is cleared and then overwritten.
62      */
63     static void writeFile(const char* file, const void* buffer, int numBytes);
64 
65     /**
66      * Writes train info.
67      */
68     static bool writeTrainInfo(const InstallTrainInfo& trainInfo);
69 
70     /**
71      * Reads train info.
72      */
73     static bool readTrainInfo(const std::string& trainName, InstallTrainInfo& trainInfo);
74 
75     /**
76      * Reads train info assuming lock is obtained.
77      */
78     static bool readTrainInfoLocked(const std::string& trainName, InstallTrainInfo& trainInfo);
79 
80     /**
81      * Reads all train info and returns a vector of train info.
82      */
83     static vector<InstallTrainInfo> readAllTrainInfo();
84 
85     /**
86      * Reads the file content to the buffer.
87      */
88     static bool readFileToString(const char* file, string* content);
89 
90     /**
91      * Deletes a single file given a file name.
92      */
93     static void deleteFile(const char* file);
94 
95     /**
96      * Deletes all files in a given directory.
97      */
98     static void deleteAllFiles(const char* path);
99 
100     /**
101      * Deletes all files whose name matches with a provided suffix.
102      */
103     static void deleteSuffixedFiles(const char* path, const char* suffix);
104 
105     /**
106      * Send broadcasts to relevant receiver for each data stored on disk.
107      */
108     static void sendBroadcast(const char* path,
109                               const std::function<void(const ConfigKey&)>& sendBroadcast);
110 
111     /**
112      * Returns true if there's at least one report on disk.
113      */
114     static bool hasConfigMetricsReport(const ConfigKey& key);
115 
116     /**
117      * Appends the ConfigMetricsReport found on disk to the specifid proto
118      * and, if erase_data, deletes it from disk.
119      *
120      * [isAdb]: if the caller is adb dump. This includes local adb dump or dumpsys by
121      * bugreport or incidentd. When true, we will append any local history data too.
122      *
123      * When
124      * erase_data=true, isAdb=true:   append history data to output, remove all data after read
125      * erase_data=false, isAdb=true:  append history data to output, keep data after read
126      * erase_data=true, isAdb=false:  do not append history data, and remove data after read
127      * erase_data=false, isAdb=false: do not append history data and *rename* all data files to
128      *                                history files.
129      */
130     static void appendConfigMetricsReport(const ConfigKey& key, ProtoOutputStream* proto,
131                                           bool erase_data, bool isAdb);
132 
133     /**
134      * Call to load the saved configs from disk.
135      */
136     static void readConfigFromDisk(std::map<ConfigKey, StatsdConfig>& configsMap);
137 
138     /**
139      * Call to load the specified config from disk. Returns false if the config file does not
140      * exist or error occurs when reading the file.
141      */
142     static bool readConfigFromDisk(const ConfigKey& key, StatsdConfig* config);
143     static bool readConfigFromDisk(const ConfigKey& key, string* config);
144 
145     /**
146      * Trims files in the provided directory to limit the total size, number of
147      * files, accumulation of outdated files.
148      */
149     static void trimToFit(const char* dir, bool parseTimestampOnly = false);
150 
151     /**
152      * Returns true if there already exists identical configuration on device.
153      */
154     static bool hasIdenticalConfig(const ConfigKey& key,
155                                    const vector<uint8_t>& config);
156 
157     /**
158      * Prints disk usage statistics related to statsd.
159      */
160     static void printStats(int out);
161 
162     static string getDataFileName(long wallClockSec, int uid, int64_t id);
163 
164     static string getDataHistoryFileName(long wallClockSec, int uid, int64_t id);
165 
166     static void sortFiles(vector<FileInfo>* fileNames);
167 
168     static void enforceDbGuardrails(const char* path, int64_t wallClockSec, int64_t maxBytes);
169 
170     static bool hasFile(const char* file);
171 
172 private:
173     /**
174      * Prints disk usage statistics about a directory related to statsd.
175      */
176     static void printDirStats(int out, const char* path);
177 
178     static std::mutex sTrainInfoMutex;
179 };
180 
181 }  // namespace statsd
182 }  // namespace os
183 }  // namespace android
184 
185 #endif  // STORAGE_MANAGER_H
186