1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OMIT_MULTI_VER
17 #include "multi_ver_database_oper.h"
18 
19 #include "db_errno.h"
20 #include "log_print.h"
21 #include "db_constant.h"
22 #include "db_common.h"
23 #include "platform_specific.h"
24 #include "sqlite_multi_ver_data_storage.h"
25 #include "multi_ver_natural_store_commit_storage.h"
26 
27 namespace DistributedDB {
MultiVerDatabaseOper(MultiVerNaturalStore * multiVerNaturalStore,IKvDBMultiVerDataStorage * multiVerData,IKvDBCommitStorage * commitHistory,MultiVerKvDataStorage * multiVerKvStorage)28 MultiVerDatabaseOper::MultiVerDatabaseOper(MultiVerNaturalStore *multiVerNaturalStore,
29     IKvDBMultiVerDataStorage *multiVerData, IKvDBCommitStorage *commitHistory, MultiVerKvDataStorage *multiVerKvStorage)
30     : multiVerNaturalStore_(multiVerNaturalStore),
31       multiVerData_(multiVerData),
32       commitHistory_(commitHistory),
33       multiVerKvStorage_(multiVerKvStorage)
34 {}
35 
Rekey(const CipherPassword & passwd)36 int MultiVerDatabaseOper::Rekey(const CipherPassword &passwd)
37 {
38     if (multiVerNaturalStore_ == nullptr || multiVerData_ == nullptr || commitHistory_ == nullptr ||
39         multiVerKvStorage_ == nullptr) {
40         return -E_INVALID_DB;
41     }
42 
43     return ExecuteRekey(passwd, multiVerNaturalStore_->GetDbProperties());
44 }
45 
Import(const std::string & filePath,const CipherPassword & passwd)46 int MultiVerDatabaseOper::Import(const std::string &filePath, const CipherPassword &passwd)
47 {
48     if (multiVerNaturalStore_ == nullptr || multiVerData_ == nullptr || commitHistory_ == nullptr ||
49         multiVerKvStorage_ == nullptr) {
50         return -E_INVALID_DB;
51     }
52 
53     return ExecuteImport(filePath, passwd, multiVerNaturalStore_->GetDbProperties());
54 }
55 
Export(const std::string & filePath,const CipherPassword & passwd) const56 int MultiVerDatabaseOper::Export(const std::string &filePath, const CipherPassword &passwd) const
57 {
58     if (multiVerNaturalStore_ == nullptr || multiVerData_ == nullptr || commitHistory_ == nullptr ||
59         multiVerKvStorage_ == nullptr) {
60         return -E_INVALID_DB;
61     }
62     return ExecuteExport(filePath, passwd, multiVerNaturalStore_->GetDbProperties());
63 }
64 
RekeyPreHandle(const CipherPassword & passwd,int & errCode)65 bool MultiVerDatabaseOper::RekeyPreHandle(const CipherPassword &passwd, int &errCode)
66 {
67     CipherType cipherType;
68     CipherPassword cachePasswd;
69     multiVerNaturalStore_->GetDbProperties().GetPassword(cipherType, cachePasswd);
70 
71     if (cachePasswd.GetSize() == 0 && passwd.GetSize() == 0) {
72         errCode = E_OK;
73         return false;
74     }
75 
76     return true;
77 }
78 
BackupDb(const CipherPassword & passwd) const79 int MultiVerDatabaseOper::BackupDb(const CipherPassword &passwd) const
80 {
81     std::string filePrefix;
82     int errCode = GetCtrlFilePrefix(multiVerNaturalStore_->GetDbProperties(), filePrefix);
83     if (errCode != E_OK) {
84         return errCode;
85     }
86 
87     // create backup dir
88     std::string currentDir = filePrefix;
89     std::string backupDir = filePrefix + DBConstant::PATH_BACKUP_POSTFIX;
90 
91     // export db to backup
92     return ExportAllDatabases(currentDir, passwd, backupDir);
93 }
94 
CloseStorages()95 int MultiVerDatabaseOper::CloseStorages()
96 {
97     if (commitHistory_ != nullptr) {
98         commitHistory_->Close();
99     }
100     if (multiVerData_ != nullptr) {
101         multiVerData_->Close();
102     }
103     if (multiVerKvStorage_ != nullptr) {
104         multiVerKvStorage_->Close();
105     }
106 
107     // rm old dir -> rename backup dir to prime dir -> rm ctrl file
108     int errCode = RekeyRecover(multiVerNaturalStore_->GetDbProperties());
109     if (errCode != E_OK) {
110         LOGE("Recover failed after run all export ok: %d.", errCode);
111     }
112     return errCode;
113 }
114 
RekeyPostHandle(const CipherPassword & passwd)115 int MultiVerDatabaseOper::RekeyPostHandle(const CipherPassword &passwd)
116 {
117     CipherType cipherType;
118     CipherPassword oldPasswd;
119     multiVerNaturalStore_->GetDbPropertyForUpdate().GetPassword(cipherType, oldPasswd);
120     multiVerNaturalStore_->GetDbPropertyForUpdate().SetPassword(cipherType, passwd);
121 
122     int errCode = multiVerNaturalStore_->InitStorages(multiVerNaturalStore_->GetDbProperties());
123     if (errCode != E_OK) {
124         return errCode;
125     }
126     return RekeyRecover(multiVerNaturalStore_->GetDbProperties());
127 }
128 
ExportAllDatabases(const std::string & currentDir,const CipherPassword & passwd,const std::string & dbDir) const129 int MultiVerDatabaseOper::ExportAllDatabases(const std::string &currentDir, const CipherPassword &passwd,
130     const std::string &dbDir) const
131 {
132     int errCode = DBCommon::CreateDirectory(dbDir);
133     if (errCode != E_OK) {
134         return errCode;
135     }
136     CipherType cipherType;
137     CipherPassword oldPasswd;
138     multiVerNaturalStore_->GetDbPropertyForUpdate().GetPassword(cipherType, oldPasswd);
139     errCode = static_cast<SQLiteMultiVerDataStorage *>(multiVerData_)->RunExportLogic(cipherType, passwd, dbDir);
140     if (errCode != E_OK) {
141         return errCode;
142     }
143     errCode = static_cast<MultiVerNaturalStoreCommitStorage *>(commitHistory_)->RunExportLogic(cipherType,
144         passwd, dbDir);
145     if (errCode != E_OK) {
146         return errCode;
147     }
148     errCode = multiVerKvStorage_->RunExportLogic(cipherType, passwd, dbDir);
149     if (errCode != E_OK) {
150         return errCode;
151     }
152 
153     std::string versionFile = currentDir + "/version";
154     if (OS::CheckPathExistence(versionFile)) {
155         std::string targetVerFile = dbDir + "/version";
156         DBCommon::CopyFile(versionFile, targetVerFile);
157     }
158 
159     return E_OK;
160 }
161 
BackupCurrentDatabase(const ImportFileInfo & info) const162 int MultiVerDatabaseOper::BackupCurrentDatabase(const ImportFileInfo &info) const
163 {
164     if (multiVerKvStorage_ == nullptr || commitHistory_ == nullptr || multiVerData_ == nullptr) {
165         return -E_INVALID_DB;
166     }
167     commitHistory_->Close();
168     multiVerData_->Close();
169     multiVerKvStorage_->Close();
170 
171     // Create the file which imply that the current database files is valid.
172     int errCode = OS::CreateFileByFileName(info.curValidFile);
173     if (errCode != E_OK) {
174         LOGE("Create current valid file failed:%d.", errCode);
175         return errCode;
176     }
177 
178     std::string dataDir = multiVerNaturalStore_->GetDbProperties().GetStringProp(KvDBProperties::DATA_DIR, "");
179     std::string id = multiVerNaturalStore_->GetDbProperties().GetStringProp(KvDBProperties::IDENTIFIER_DIR, "");
180     bool isNeedCreate = multiVerNaturalStore_->GetDbProperties().GetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, true);
181 
182     CipherType cipherType;
183     CipherPassword passwd;
184     multiVerNaturalStore_->GetDbProperties().GetPassword(cipherType, passwd);
185 
186     IKvDBMultiVerDataStorage::Property multiVerProp = {dataDir, id, isNeedCreate, cipherType, passwd};
187     IKvDBCommitStorage::Property commitProp = {dataDir, id, isNeedCreate, cipherType, passwd};
188     MultiVerKvDataStorage::Property multiVerKvProp = {dataDir, id, isNeedCreate, cipherType, passwd};
189 
190     errCode = DBCommon::CreateDirectory(info.backupDir);
191     if (errCode != E_OK) {
192         LOGE("Create backup dir failed");
193         RemoveFile(info.curValidFile);
194         return errCode;
195     }
196 
197     errCode = multiVerData_->BackupCurrentDatabase(multiVerProp, info.backupDir);
198     if (errCode != E_OK) {
199         return errCode;
200     }
201 
202     errCode = commitHistory_->BackupCurrentDatabase(commitProp, info.backupDir);
203     if (errCode != E_OK) {
204         return errCode;
205     }
206 
207     errCode = multiVerKvStorage_->BackupCurrentDatabase(multiVerKvProp, info.backupDir);
208     if (errCode != E_OK) {
209         return errCode;
210     }
211 
212     (void)DBCommon::CopyFile(info.currentDir + "/version", info.backupDir + "/version");
213     int innerCode = rename(info.curValidFile.c_str(), info.backValidFile.c_str());
214     if (innerCode != 0) {
215         LOGE("Failed to rename the file after the backup:%d", errno);
216         return -E_SYSTEM_API_FAIL;
217     }
218     return E_OK;
219 }
220 
ImportUnpackedDatabase(const ImportFileInfo & info,const CipherPassword & srcPasswd) const221 int MultiVerDatabaseOper::ImportUnpackedDatabase(const ImportFileInfo &info, const CipherPassword &srcPasswd) const
222 {
223     // create backup dir
224     int errCode = DBCommon::RemoveAllFilesOfDirectory(info.currentDir, false);
225     if (errCode != E_OK) {
226         return errCode;
227     }
228 
229     errCode = ImportDatabase(info.unpackedDir, srcPasswd);
230     DBCommon::CopyFile(info.unpackedDir + "/version", info.currentDir + "/version");
231     (void)DBCommon::RemoveAllFilesOfDirectory(info.unpackedDir);
232     if (errCode != E_OK) {
233         LOGE("export the unpacked database to current error:%d", errCode);
234         errCode = -E_INVALID_FILE;
235         return errCode;
236     }
237 
238     // reinitialize the database, and delete the backup database.
239     errCode = multiVerNaturalStore_->InitStorages(multiVerNaturalStore_->GetDbProperties(), true);
240     if (errCode != E_OK) {
241         LOGE("InitStorages error:%d", errCode);
242         return errCode;
243     }
244 
245     // rename the flag file.
246     int innerCode = rename(info.backValidFile.c_str(), info.curValidFile.c_str());
247     if (innerCode != E_OK) {
248         LOGE("Failed to rename after the import operation:%d", errno);
249         errCode = -E_SYSTEM_API_FAIL;
250     }
251 
252     return errCode;
253 }
254 
ImportPostHandle() const255 int MultiVerDatabaseOper::ImportPostHandle() const
256 {
257     return multiVerNaturalStore_->InitStorages(multiVerNaturalStore_->GetDbProperties());
258 }
259 
260 // private
ImportDatabase(const std::string & dir,const CipherPassword & passwd) const261 int MultiVerDatabaseOper::ImportDatabase(const std::string &dir, const CipherPassword &passwd) const
262 {
263     if (multiVerKvStorage_ == nullptr || commitHistory_ == nullptr || multiVerData_ == nullptr) {
264         return -E_INVALID_DB;
265     }
266 
267     std::string dataDir = multiVerNaturalStore_->GetDbProperties().GetStringProp(KvDBProperties::DATA_DIR, "");
268     std::string id = multiVerNaturalStore_->GetDbProperties().GetStringProp(KvDBProperties::IDENTIFIER_DIR, "");
269 
270     CipherType cipherType;
271     CipherPassword currPasswd;
272     multiVerNaturalStore_->GetDbProperties().GetPassword(cipherType, currPasswd);
273 
274     IKvDBMultiVerDataStorage::Property multiVerProp = {dataDir, id, true, cipherType, currPasswd};
275     IKvDBCommitStorage::Property commitProp = {dataDir, id, true, cipherType, currPasswd};
276     MultiVerKvDataStorage::Property multiVerKvProp = {dataDir, id, true, cipherType, currPasswd};
277     int errCode = multiVerData_->ImportDatabase(multiVerProp, dir, passwd);
278     if (errCode != E_OK) {
279         return errCode;
280     }
281 
282     errCode = commitHistory_->ImportDatabase(commitProp, dir, passwd);
283     if (errCode != E_OK) {
284         return errCode;
285     }
286     return multiVerKvStorage_->ImportDatabase(multiVerKvProp, dir, passwd);
287 }
288 } // namespace DistributedDB
289 #endif