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 #include "database_oper.h"
17 
18 #include "db_errno.h"
19 #include "db_constant.h"
20 #include "db_common.h"
21 #include "log_print.h"
22 #include "platform_specific.h"
23 #include "package_file.h"
24 #include "res_finalizer.h"
25 #include "runtime_context.h"
26 
27 namespace DistributedDB {
SetLocalDevId(const std::string & deviceId)28 void DatabaseOper::SetLocalDevId(const std::string &deviceId)
29 {
30     deviceId_ = deviceId;
31 }
32 
ExecuteRekey(const CipherPassword & passwd,const KvDBProperties & property)33 int DatabaseOper::ExecuteRekey(const CipherPassword &passwd, const KvDBProperties &property)
34 {
35     int errCode = E_OK;
36     if (!RekeyPreHandle(passwd, errCode)) {
37         LOGI("Finish rekey when RekeyPre Handle, errCode = [%d]", errCode);
38         return errCode;
39     }
40 
41     std::string ctrlFileName;
42     std::string newFileName;
43     errCode = CreateStatusCtrlFile(property, ctrlFileName, newFileName);
44     if (errCode != E_OK) {
45         return errCode;
46     }
47 
48     LOGI("Backup the current file while rekey.");
49     errCode = BackupDb(passwd);
50     if (errCode != E_OK) {
51         LOGE("ExecuteRekey backup db failed! errCode = [%d]", errCode);
52         (void)RekeyRecover(property);
53         return errCode;
54     }
55 
56     errCode = RenameStatusCtrlFile(ctrlFileName, newFileName);
57     if (errCode != E_OK) {
58         (void)RekeyRecover(property);
59         LOGE("ExecuteRekey rename status ctrl failed! errCode = [%d]", errCode);
60         return errCode;
61     }
62 
63     errCode = CloseStorages();
64     if (errCode != E_OK) {
65         return errCode;
66     }
67 
68     errCode = RekeyPostHandle(passwd);
69     if (errCode == -E_EKEYREVOKED) {
70         errCode = -E_FORBID_CACHEDB;
71         LOGI("Can not reopen database after rekey for the access controlled. errCode = [%d]", errCode);
72     }
73     return errCode;
74 }
75 
GetCtrlFilePrefix(const KvDBProperties & property,std::string & filePrefix) const76 int DatabaseOper::GetCtrlFilePrefix(const KvDBProperties &property, std::string &filePrefix) const
77 {
78     std::string baseDir;
79     int errCode = GetWorkDir(property, baseDir);
80     if (errCode != E_OK) {
81         return errCode;
82     }
83 
84     int dbType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::LOCAL_TYPE_SQLITE);
85     std::string dbSubDir = KvDBProperties::GetStoreSubDirectory(dbType);
86     filePrefix = baseDir + "/" + dbSubDir;
87     return E_OK;
88 }
89 
RekeyRecover(const KvDBProperties & property)90 int DatabaseOper::RekeyRecover(const KvDBProperties &property)
91 {
92     std::string workDir;
93     int errCode = GetWorkDir(property, workDir);
94     if (errCode != E_OK) {
95         return errCode;
96     }
97 
98     int dbType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::LOCAL_TYPE_SQLITE);
99     std::string dbSubDir = KvDBProperties::GetStoreSubDirectory(dbType);
100 
101     std::string preCtrlFileName = workDir + "/" + dbSubDir + DBConstant::REKEY_FILENAME_POSTFIX_PRE;
102     bool isPreCtrlFileExist = OS::CheckPathExistence(preCtrlFileName);
103 
104     std::string endCtrlFileName = workDir + "/" + dbSubDir + DBConstant::REKEY_FILENAME_POSTFIX_OK;
105     bool isEndCtrlFileExist = OS::CheckPathExistence(endCtrlFileName);
106 
107     std::string currentDir = workDir + "/" + dbSubDir;
108     bool isPrimeDbDirExist = OS::CheckPathExistence(currentDir);
109 
110     std::string backupDir = workDir + "/" + dbSubDir + DBConstant::PATH_BACKUP_POSTFIX;
111     bool isBackupDbDirExist = OS::CheckPathExistence(backupDir);
112 
113     // remove the backup directory and ctrl file if Rekey not finish
114     // name of ctrl file is pre
115     if (isPreCtrlFileExist) {
116         LOGI("Rekey recovery:Remove the backup files");
117         return RecoverPrehandle(dbType, backupDir, preCtrlFileName);
118     }
119     // no ctrl file means nothing need to do
120     if (!isEndCtrlFileExist) {
121         return E_OK;
122     }
123 
124     // name of ctrl file is ok
125     if (isBackupDbDirExist) {
126         if (isPrimeDbDirExist) {
127             // scenario 1: both prime and bak dir exist
128             // rm prime dir -> rename backup dir to prime dir -> rm ctrl file
129             LOGI("Rekey recovery:Remove the current files");
130             if (DBCommon::RemoveAllFilesOfDirectory(currentDir, true) != E_OK) {
131                 LOGE("Remove the prime dir failed: %d", errno);
132                 return -E_REMOVE_FILE;
133             }
134         }
135 
136         // scenario 2: only bak dir exist
137         // rename backup dir to prime dir -> rm ctrl file
138         if (rename(backupDir.c_str(), currentDir.c_str()) != E_OK) {
139             LOGE("Rename the bak dir to prime dir failed:%d.", errno);
140             return -E_SYSTEM_API_FAIL;
141         }
142     }
143     // scenario 3: only prime dir exist
144     // scenario 4: both prime and bak dir not exist
145     // remove ctrl file
146     if (RemoveFile(endCtrlFileName) != E_OK) {
147         LOGE("Remove the end ctrl file failed: %d", errno);
148         return -E_REMOVE_FILE;
149     }
150     return E_OK;
151 }
152 
CheckSecurityOption(const std::string & filePath,const KvDBProperties & property) const153 int DatabaseOper::CheckSecurityOption(const std::string &filePath, const KvDBProperties &property) const
154 {
155     SecurityOption secOption;
156     int errCode = RuntimeContext::GetInstance()->GetSecurityOption(filePath, secOption);
157     if (errCode != E_OK && errCode != -E_NOT_SUPPORT) {
158         LOGE("Get import package security option fail! errCode = [%d]", errCode);
159         return errCode;
160     }
161 
162     SecurityOption dbSecOpt;
163     dbSecOpt.securityFlag = property.GetSecFlag();
164     dbSecOpt.securityLabel = property.GetSecLabel();
165 
166     if (dbSecOpt == secOption || secOption.securityLabel == SecurityLabel::NOT_SET) {
167         return E_OK;
168     }
169     LOGE("Import package secOpt %d %d vs database %d %d",
170         secOption.securityFlag, secOption.securityLabel, dbSecOpt.securityFlag, dbSecOpt.securityLabel);
171     return -E_SECURITY_OPTION_CHECK_ERROR;
172 }
173 
ExecuteImport(const std::string & filePath,const CipherPassword & passwd,const KvDBProperties & property) const174 int DatabaseOper::ExecuteImport(const std::string &filePath, const CipherPassword &passwd,
175     const KvDBProperties &property) const
176 {
177     ImportFileInfo importInfo;
178     InitImportFileInfo(importInfo, property);
179 
180     int errCode = CheckSecurityOption(filePath, property);
181     if (errCode != E_OK) {
182         return errCode;
183     }
184 
185     // 1. unpack and check the file.
186     LOGI("Unpack the imported file");
187     errCode = UnpackAndCheckImportedFile(filePath, importInfo, property);
188     if (errCode != E_OK) {
189         return errCode;
190     }
191 
192     // Using RAII define tempState clean when object finalize execute
193     ResFinalizer tempStateClean([&errCode, &property, this]() {
194         int innerCode = this->ClearImportTempFile(property);
195         if (innerCode != E_OK) {
196             LOGE("Failed to clean the intermediate import files, errCode = [%d]", innerCode);
197         }
198         // Finish. reinitialize the database.
199         if (errCode != E_OK) {
200             innerCode = this->ImportPostHandle();
201             LOGE("Reinit the database after import, errCode = [%d]", innerCode);
202         }
203     });
204 
205     // 2. backup the current database.
206     LOGI("Backup the current database while import.");
207     errCode = BackupCurrentDatabase(importInfo);
208     if (errCode != E_OK) {
209         LOGE("Failed to backup current databases, errCode = [%d]", errCode);
210         return errCode;
211     }
212 
213     // 3. export the unpacked file to the current database.
214     LOGI("Import the unpacked database.");
215     errCode = ImportUnpackedDatabase(importInfo, passwd);
216     if (errCode != E_OK) {
217         LOGE("Failed to import from the unpacked databases, errCode = [%d]", errCode);
218     }
219     DBCommon::RemoveAllFilesOfDirectory(importInfo.unpackedDir);
220     return errCode;
221 }
222 
CreateBackupDirForExport(const KvDBProperties & property,std::string & currentDir,std::string & backupDir) const223 int DatabaseOper::CreateBackupDirForExport(const KvDBProperties &property, std::string &currentDir,
224     std::string &backupDir) const
225 {
226     std::string baseDir;
227     int errCode = GetWorkDir(property, baseDir);
228     if (errCode != E_OK) {
229         LOGE("Get work dir failed:%d.", errCode);
230         return errCode;
231     }
232 
233     int databaseType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::LOCAL_TYPE_SQLITE);
234     std::string subDir = KvDBProperties::GetStoreSubDirectory(databaseType);
235     currentDir = baseDir + "/" + subDir;
236 
237     backupDir = baseDir + "/" + subDir + DBConstant::PATH_POSTFIX_EXPORT_BACKUP + "/";
238     errCode = DBCommon::CreateDirectory(backupDir);
239     if (errCode != E_OK) {
240         return errCode;
241     }
242     std::vector<std::string> dbDir {DBConstant::MAINDB_DIR, DBConstant::METADB_DIR, DBConstant::CACHEDB_DIR};
243     for (const auto &item : dbDir) {
244         if (DBCommon::CreateDirectory(backupDir + "/" + item) != E_OK) {
245             return -E_SYSTEM_API_FAIL;
246         }
247     }
248     return errCode;
249 }
250 
ExecuteExport(const std::string & filePath,const CipherPassword & passwd,const KvDBProperties & property) const251 int DatabaseOper::ExecuteExport(const std::string &filePath, const CipherPassword &passwd,
252     const KvDBProperties &property) const
253 {
254     if (deviceId_.empty()) {
255         return -E_NOT_INIT;
256     }
257 
258     std::string currentDir;
259     std::string backupDir;
260     int errCode = CreateBackupDirForExport(property, currentDir, backupDir);
261     if (errCode != E_OK) {
262         return errCode;
263     }
264 
265     errCode = ExportAllDatabases(currentDir, passwd, backupDir);
266     if (errCode != E_OK) {
267         LOGE("Export databases fail!:%d.", errCode);
268         (void)ClearExportedTempFiles(property);
269         return errCode;
270     }
271 
272     errCode = PackExportedDatabase(backupDir, filePath, property);
273     if (errCode != E_OK) {
274         OS::RemoveFile(filePath); // Pack file failed, need rollback delete Intermediate state package file
275         LOGE("[DatabaseOper][ExecuteExport] Pack files fail! errCode = [%d], errno = [%d].", errCode, errno);
276         (void)ClearExportedTempFiles(property);
277         return errCode;
278     }
279 
280     SecurityOption secOption {property.GetSecLabel(), property.GetSecFlag()};
281     // RuntimeContext can make sure GetInstance not nullptr
282     errCode = RuntimeContext::GetInstance()->SetSecurityOption(filePath, secOption);
283     if (errCode != E_OK) {
284         if (errCode == -E_NOT_SUPPORT) {
285             (void)ClearExportedTempFiles(property);
286             return E_OK;
287         }
288         OS::RemoveFile(filePath);
289         LOGE("[DatabaseOper][ExecuteExport] Set security option fail! errCode = [%d].", errCode);
290     }
291 
292     (void)ClearExportedTempFiles(property);
293     return errCode;
294 }
295 
296 // private begin
CreateStatusCtrlFile(const KvDBProperties & property,std::string & orgCtrlFile,std::string & newCtrlFile)297 int DatabaseOper::CreateStatusCtrlFile(const KvDBProperties &property, std::string &orgCtrlFile,
298     std::string &newCtrlFile)
299 {
300     std::string filePrefix;
301     int errCode = GetCtrlFilePrefix(property, filePrefix);
302     if (errCode != E_OK) {
303         return errCode;
304     }
305 
306     // create control file
307     newCtrlFile = filePrefix + DBConstant::REKEY_FILENAME_POSTFIX_OK;
308     orgCtrlFile = filePrefix + DBConstant::REKEY_FILENAME_POSTFIX_PRE;
309     return OS::CreateFileByFileName(orgCtrlFile);
310 }
311 
RenameStatusCtrlFile(const std::string & orgCtrlFile,const std::string & newCtrlFile)312 int DatabaseOper::RenameStatusCtrlFile(const std::string &orgCtrlFile, const std::string &newCtrlFile)
313 {
314     int errCode = rename(orgCtrlFile.c_str(), newCtrlFile.c_str());
315     if (errCode != E_OK) {
316         LOGE("change ctrl file name to ok failed: %d.", errCode);
317         return -E_SYSTEM_API_FAIL;
318     }
319     return E_OK;
320 }
321 
RecoverPrehandle(int dbType,const std::string & dir,const std::string & fileName)322 int DatabaseOper::RecoverPrehandle(int dbType, const std::string &dir, const std::string &fileName)
323 {
324     if (DBCommon::RemoveAllFilesOfDirectory(dir, true) != E_OK) { // LCOV_EXCL_BR_LINE
325         LOGE("Remove the backup dir failed:%d", errno);
326         return -E_REMOVE_FILE;
327     }
328     if (RemoveFile(fileName) != E_OK) { // LCOV_EXCL_BR_LINE
329         LOGE("Remove the pre ctrl file failed:%d", errno);
330         return -E_REMOVE_FILE;
331     }
332     return E_OK;
333 }
334 
RemoveDbDir(const std::string & dir,int dbType,bool isNeedDelDir)335 int DatabaseOper::RemoveDbDir(const std::string &dir, int dbType, bool isNeedDelDir)
336 {
337     if (!OS::CheckPathExistence(dir)) { // LCOV_EXCL_BR_LINE
338         return E_OK;
339     }
340 
341     if (dbType == DBConstant::DB_TYPE_LOCAL) { // LCOV_EXCL_BR_LINE
342         std::vector<std::string> dbNameList = {
343             DBConstant::LOCAL_DATABASE_NAME
344         };
345         return RemoveDbFiles(dir, dbNameList, isNeedDelDir);
346     }
347     if (dbType == DBConstant::DB_TYPE_SINGLE_VER) { // LCOV_EXCL_BR_LINE
348         std::vector<std::string> dbNameList = {
349             DBConstant::SINGLE_VER_DATA_STORE
350         };
351         return RemoveDbFiles(dir, dbNameList, isNeedDelDir);
352     }
353     if (dbType == DBConstant::DB_TYPE_MULTI_VER) { // LCOV_EXCL_BR_LINE
354         std::vector<std::string> dbNameList = {
355             DBConstant::MULTI_VER_DATA_STORE, DBConstant::MULTI_VER_COMMIT_STORE,
356             DBConstant::MULTI_VER_VALUE_STORE, DBConstant::MULTI_VER_META_STORE
357         };
358         return RemoveDbFiles(dir, dbNameList, isNeedDelDir);
359     }
360     return -E_NOT_SUPPORT;
361 }
362 
RemoveFile(const std::string & fileName)363 int DatabaseOper::RemoveFile(const std::string &fileName)
364 {
365     if (!OS::CheckPathExistence(fileName)) {
366         return E_OK;
367     }
368 
369     if (OS::RemoveFile(fileName) != E_OK) {
370         LOGE("Remove file failed:%d", errno);
371         return -E_REMOVE_FILE;
372     }
373     return E_OK;
374 }
375 
GetWorkDir(const KvDBProperties & property,std::string & workDir)376 int DatabaseOper::GetWorkDir(const KvDBProperties &property, std::string &workDir)
377 {
378     std::string dataDir = property.GetStringProp(KvDBProperties::DATA_DIR, "");
379     std::string identifierDir = property.GetStringProp(KvDBProperties::IDENTIFIER_DIR, "");
380     if (dataDir.empty()) {
381         return -E_INVALID_ARGS;
382     }
383 
384     workDir = dataDir + "/" + identifierDir;
385     return E_OK;
386 }
387 
388 // Only for remove the backup directory while rekey.
RemoveDbFiles(const std::string & dir,const std::vector<std::string> & dbNameList,bool isNeedDelDir)389 int DatabaseOper::RemoveDbFiles(const std::string &dir, const std::vector<std::string> &dbNameList, bool isNeedDelDir)
390 {
391     for (const auto &iter : dbNameList) {
392         // remove
393         std::string dbFile = dir + "/" + iter + ".db";
394         if (RemoveFile(dbFile) != E_OK) { // LCOV_EXCL_BR_LINE
395             LOGE("Remove the db file failed:%d", errno);
396             return -E_REMOVE_FILE;
397         }
398 
399         dbFile = dir + "/" + iter + ".db-wal";
400         if (RemoveFile(dbFile) != E_OK) { // LCOV_EXCL_BR_LINE
401             LOGE("Remove the wal file failed:%d", errno);
402             return -E_REMOVE_FILE;
403         }
404 
405         dbFile = dir + "/" + iter + ".db-shm";
406         if (RemoveFile(dbFile) != E_OK) { // LCOV_EXCL_BR_LINE
407             LOGE("Remove the shm file failed:%d", errno);
408             return -E_REMOVE_FILE;
409         }
410     }
411     if (isNeedDelDir && OS::RemoveDBDirectory(dir) != E_OK) { // LCOV_EXCL_BR_LINE
412         LOGE("Remove directory:%d", errno);
413         return -E_REMOVE_FILE;
414     }
415     return E_OK;
416 }
417 
InitImportFileInfo(ImportFileInfo & info,const KvDBProperties & property)418 void DatabaseOper::InitImportFileInfo(ImportFileInfo &info, const KvDBProperties &property)
419 {
420     std::string dataDir = property.GetStringProp(KvDBProperties::DATA_DIR, "");
421     std::string identifierDir = property.GetStringProp(KvDBProperties::IDENTIFIER_DIR, "");
422     int databaseType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE_SQLITE);
423     std::string subDir = KvDBProperties::GetStoreSubDirectory(databaseType);
424 
425     std::string baseDir = dataDir + "/" + identifierDir + "/" + subDir;
426     info.backupDir = baseDir + DBConstant::PATH_POSTFIX_IMPORT_BACKUP + "/";
427     info.unpackedDir = baseDir + DBConstant::PATH_POSTFIX_UNPACKED + "/";
428     info.currentDir = baseDir + "/";
429     info.curValidFile = baseDir + DBConstant::PATH_POSTFIX_IMPORT_ORIGIN; // origin directory is valid.
430     info.backValidFile = baseDir + DBConstant::PATH_POSTFIX_IMPORT_DUP; // the back directory is valid.
431 }
432 
UnpackAndCheckImportedFile(const std::string & srcFile,const ImportFileInfo & info,const KvDBProperties & property) const433 int DatabaseOper::UnpackAndCheckImportedFile(const std::string &srcFile, const ImportFileInfo &info,
434     const KvDBProperties &property) const
435 {
436     int errCode = DBCommon::CreateDirectory(info.unpackedDir);
437     if (errCode != E_OK) {
438         return errCode;
439     }
440 
441     FileInfo fileInfo;
442     errCode = PackageFile::UnpackFile(srcFile, info.unpackedDir, fileInfo);
443     if (errCode != E_OK) {
444         DBCommon::RemoveAllFilesOfDirectory(info.unpackedDir);
445         LOGE("Failed to unpack the imported file:%d", errCode);
446         return errCode;
447     }
448     int dbType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::LOCAL_TYPE_SQLITE);
449     if (fileInfo.dbType != static_cast<uint32_t>(dbType)) {
450         DBCommon::RemoveAllFilesOfDirectory(info.unpackedDir);
451         LOGE("Check db type [%u] vs [%u] or devicesId fail!", fileInfo.dbType, static_cast<uint32_t>(dbType));
452         return -E_INVALID_FILE;
453     }
454     return E_OK;
455 }
456 
RecoverImportedBackFiles(const std::string & dir,const std::string & fileName,int dbType) const457 int DatabaseOper::RecoverImportedBackFiles(const std::string &dir, const std::string &fileName, int dbType) const
458 {
459     std::string backupDir = dir + DBConstant::PATH_POSTFIX_IMPORT_BACKUP;
460     // if backup directory is not existed
461     if (!OS::CheckPathExistence(backupDir)) {
462         goto END;
463     }
464 
465     if (DBCommon::RemoveAllFilesOfDirectory(dir, true) != E_OK) {
466         LOGE("Remove the current db dir failed");
467         return -E_REMOVE_FILE;
468     }
469 
470     if (rename(backupDir.c_str(), dir.c_str()) != E_OK) {
471         LOGE("Rename the backfile error:%d", errno);
472         return -E_SYSTEM_API_FAIL;
473     }
474 
475 END:
476     if (RemoveFile(fileName) != E_OK) {
477         LOGE("Remove the pre ctrl file failed:%d", errno);
478         return -E_REMOVE_FILE;
479     }
480     return E_OK;
481 }
482 
RemoveImportedBackFiles(const std::string & backupDir,const std::string & ctrlFileName,int dbType) const483 int DatabaseOper::RemoveImportedBackFiles(const std::string &backupDir, const std::string &ctrlFileName, int dbType)
484     const
485 {
486     if (DBCommon::RemoveAllFilesOfDirectory(backupDir, true) != E_OK) {
487         LOGE("Remove the backup dir failed");
488         return -E_REMOVE_FILE;
489     }
490 
491     if (RemoveFile(ctrlFileName) != E_OK) {
492         LOGE("Remove the pre ctrl file failed");
493         return -E_REMOVE_FILE;
494     }
495     return E_OK;
496 }
497 
ClearImportTempFile(const KvDBProperties & property) const498 int DatabaseOper::ClearImportTempFile(const KvDBProperties &property) const
499 {
500     // get work directory
501     std::string workDir;
502     int errCode = GetWorkDir(property, workDir);
503     if (errCode != E_OK) {
504         return errCode;
505     }
506 
507     int dbType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::LOCAL_TYPE_SQLITE);
508     std::string dbSubDir = KvDBProperties::GetStoreSubDirectory(dbType);
509 
510     std::string oriKeepFile = workDir + "/" + dbSubDir + DBConstant::PATH_POSTFIX_IMPORT_ORIGIN;
511     bool isOriKeepFileExist = OS::CheckPathExistence(oriKeepFile);
512 
513     std::string backKeepFile = workDir + "/" + dbSubDir + DBConstant::PATH_POSTFIX_IMPORT_DUP;
514     bool isBakKeepFileExist = OS::CheckPathExistence(backKeepFile);
515 
516     std::string currentDir = workDir + "/" + dbSubDir;
517     std::string backupDir = workDir + "/" + dbSubDir + DBConstant::PATH_POSTFIX_IMPORT_BACKUP;
518     bool isBackupDbDirExist = OS::CheckPathExistence(backupDir);
519     std::string exportBackupDir = workDir + "/" + dbSubDir + DBConstant::PATH_POSTFIX_UNPACKED;
520     DBCommon::RemoveAllFilesOfDirectory(exportBackupDir);
521 
522     if (isOriKeepFileExist && isBakKeepFileExist) {
523         LOGE("Origin and backup file shouldn't exist concurrently");
524     }
525 
526     // Clear the backup dir and the ctrl file
527     if (isOriKeepFileExist) {
528         return RemoveImportedBackFiles(backupDir, oriKeepFile, dbType);
529     }
530 
531     // remove the main directory and restore the backup files.
532     if (isBakKeepFileExist) {
533         return RecoverImportedBackFiles(currentDir, backKeepFile, dbType);
534     }
535 
536     if (isBackupDbDirExist) {
537         // Import success, clean backupdir
538         if (DBCommon::RemoveAllFilesOfDirectory(backupDir, true) != E_OK) {
539             LOGE("Remove the backup dir failed");
540             return -E_REMOVE_FILE;
541         }
542     }
543 
544     return E_OK;
545 }
546 
ClearExportedTempFiles(const KvDBProperties & property) const547 int DatabaseOper::ClearExportedTempFiles(const KvDBProperties &property) const
548 {
549     std::string workDir;
550     int errCode = GetWorkDir(property, workDir);
551     if (errCode != E_OK) {
552         return errCode;
553     }
554 
555     int dbType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::LOCAL_TYPE_SQLITE);
556     std::string dbSubDir = KvDBProperties::GetStoreSubDirectory(dbType);
557     std::string backupDir = workDir + "/" + dbSubDir + DBConstant::PATH_POSTFIX_EXPORT_BACKUP;
558     errCode = DBCommon::RemoveAllFilesOfDirectory(backupDir);
559     if (errCode != E_OK) {
560         LOGE("Remove the exported backup dir failed");
561         return -E_REMOVE_FILE;
562     }
563 
564     return errCode;
565 }
566 
PackExportedDatabase(const std::string & fileDir,const std::string & packedFile,const KvDBProperties & property) const567 int DatabaseOper::PackExportedDatabase(const std::string &fileDir, const std::string &packedFile,
568     const KvDBProperties &property) const
569 {
570     LOGD("Pack the exported database.");
571     int databaseType = property.GetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE_SQLITE);
572     FileInfo fileInfo = {static_cast<uint32_t>(databaseType), deviceId_};
573     int errCode = PackageFile::PackageFiles(fileDir, packedFile, fileInfo);
574     if (errCode != E_OK) {
575         LOGE("Pack the database error:%d", errCode);
576     }
577 
578     return errCode;
579 }
580 } // namespace DistributedDB
581