1 /*
2  * Copyright (c) 2022-2024 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 #define LOG_TAG "Upgrade"
16 #include "upgrade.h"
17 
18 #include <chrono>
19 #include <cinttypes>
20 
21 #include "accesstoken_kit.h"
22 #include "crypto_manager.h"
23 #include "device_manager_adapter.h"
24 #include "directory/directory_manager.h"
25 #include "kvdb_general_store.h"
26 #include "log_print.h"
27 #include "metadata/meta_data_manager.h"
28 #include "metadata/secret_key_meta_data.h"
29 namespace OHOS::DistributedKv {
30 using namespace OHOS::DistributedData;
31 using system_clock = std::chrono::system_clock;
32 using DMAdapter = DistributedData::DeviceManagerAdapter;
33 using DBKey = DistributedDB::Key;
34 
GetInstance()35 Upgrade &Upgrade::GetInstance()
36 {
37     static Upgrade upgrade;
38     return upgrade;
39 }
40 
UpdateStore(const StoreMeta & old,const StoreMeta & meta,const std::vector<uint8_t> & pwd)41 Upgrade::DBStatus Upgrade::UpdateStore(const StoreMeta &old, const StoreMeta &meta, const std::vector<uint8_t> &pwd)
42 {
43     if (old.version < StoreMeta::UUID_CHANGED_TAG && old.storeType == DEVICE_COLLABORATION) {
44         auto upStatus = Upgrade::GetInstance().UpdateUuid(old, meta, pwd);
45         if (upStatus != DBStatus::OK) {
46             return DBStatus::DB_ERROR;
47         }
48     }
49 
50     if (old.dataDir == meta.dataDir) {
51         return DBStatus::OK;
52     }
53 
54     if (!exporter_ || !cleaner_) {
55         return DBStatus::NOT_SUPPORT;
56     }
57 
58     DBPassword password;
59     auto backupFile = exporter_(old, password);
60     if (backupFile.empty()) {
61         return DBStatus::NOT_FOUND;
62     }
63 
64     auto kvStore = GetDBStore(meta, pwd);
65     if (kvStore == nullptr) {
66         return DBStatus::DB_ERROR;
67     }
68 
69     cleaner_(old);
70     return DBStatus::OK;
71 }
72 
ExportStore(const StoreMeta & old,const StoreMeta & meta)73 Upgrade::DBStatus Upgrade::ExportStore(const StoreMeta &old, const StoreMeta &meta)
74 {
75     if (old.dataDir == meta.dataDir) {
76         return DBStatus::OK;
77     }
78 
79     if (!exporter_) {
80         return DBStatus::NOT_SUPPORT;
81     }
82 
83     DBPassword password;
84     auto backupFile = exporter_(old, password);
85     if (backupFile.empty()) {
86         return DBStatus::NOT_FOUND;
87     }
88     return DBStatus::OK;
89 }
90 
UpdatePassword(const StoreMeta & meta,const std::vector<uint8_t> & password)91 void Upgrade::UpdatePassword(const StoreMeta &meta, const std::vector<uint8_t> &password)
92 {
93     if (!meta.isEncrypt) {
94         return;
95     }
96 
97     SecretKeyMetaData secretKey;
98     secretKey.storeType = meta.storeType;
99     secretKey.sKey = CryptoManager::GetInstance().Encrypt(password);
100     auto time = system_clock::to_time_t(system_clock::now());
101     secretKey.time = { reinterpret_cast<uint8_t *>(&time), reinterpret_cast<uint8_t *>(&time) + sizeof(time) };
102     MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), secretKey, true);
103 }
104 
UpdateUuid(const StoreMeta & old,const StoreMeta & meta,const std::vector<uint8_t> & pwd)105 Upgrade::DBStatus Upgrade::UpdateUuid(const StoreMeta &old, const StoreMeta &meta, const std::vector<uint8_t> &pwd)
106 {
107     auto kvStore = GetDBStore(meta, pwd);
108     if (kvStore == nullptr) {
109         return DBStatus::DB_ERROR;
110     }
111     kvStore->RemoveDeviceData();
112     auto uuid = GetEncryptedUuidByMeta(meta);
113     auto dbStatus = kvStore->UpdateKey([uuid](const DBKey &originKey, DBKey &newKey) {
114         newKey = originKey;
115         errno_t err = EOK;
116         err = memcpy_s(newKey.data(), newKey.size(), uuid.data(), uuid.size());
117         if (err != EOK) {
118             ZLOGE("memcpy_s failed, err:%{public}d", err);
119         }
120     });
121     if (dbStatus != DBStatus::OK) {
122         ZLOGE("fail to update Uuid, status:%{public}d", dbStatus);
123     }
124     return dbStatus;
125 }
126 
RegisterExporter(uint32_t version,Exporter exporter)127 bool Upgrade::RegisterExporter(uint32_t version, Exporter exporter)
128 {
129     (void)version;
130     exporter_ = std::move(exporter);
131     return exporter_ != nullptr;
132 }
133 
RegisterCleaner(uint32_t version,Cleaner cleaner)134 bool Upgrade::RegisterCleaner(uint32_t version, Cleaner cleaner)
135 {
136     (void)version;
137     cleaner_ = std::move(cleaner);
138     return cleaner_ != nullptr;
139 }
140 
GetDBStore(const StoreMeta & meta,const std::vector<uint8_t> & pwd)141 Upgrade::AutoStore Upgrade::GetDBStore(const StoreMeta &meta, const std::vector<uint8_t> &pwd)
142 {
143     DBManager manager(meta.appId, meta.user, meta.instanceId);
144     manager.SetKvStoreConfig({ DirectoryManager::GetInstance().GetStorePath(meta) });
145     auto release = [&manager](DBStore *store) { manager.CloseKvStore(store); };
146     DBPassword password;
147     password.SetValue(pwd.data(), pwd.size());
148     AutoStore dbStore(nullptr, release);
149     manager.GetKvStore(meta.storeId, KVDBGeneralStore::GetDBOption(meta, password),
150         [&dbStore](auto dbStatus, auto *tmpStore) {
151             dbStore.reset(tmpStore);
152         });
153     return dbStore;
154 }
155 
GetEncryptedUuidByMeta(const StoreMeta & meta)156 std::string Upgrade::GetEncryptedUuidByMeta(const StoreMeta &meta)
157 {
158     std::string keyUuid = meta.appId + meta.deviceId;
159     auto pair = calcUuid_.Find(keyUuid);
160     if (pair.first) {
161         return pair.second;
162     }
163     std::string uuid;
164     if (OHOS::Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(meta.tokenId) ==
165         OHOS::Security::AccessToken::TOKEN_HAP) {
166         uuid = DMAdapter::GetInstance().CalcClientUuid(meta.appId, meta.deviceId);
167         calcUuid_.Insert(keyUuid, uuid);
168         return uuid;
169     }
170     uuid = DMAdapter::GetInstance().CalcClientUuid(" ", meta.deviceId);
171     calcUuid_.Insert(keyUuid, uuid);
172     return uuid;
173 }
174 } // namespace OHOS::DistributedKv