• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 "ohos_resource_adapter_impl.h"
17 
18 #include <ctime>
19 #include <securec.h>
20 #include <sstream>
21 #include <cerrno>
22 #include <cstring>
23 #include <unistd.h>
24 #include <vector>
25 #include <fstream>
26 #include <json/json.h>
27 
28 #include "application_context.h"
29 #include "bundle_mgr_proxy.h"
30 #include "extractor.h"
31 #include "if_system_ability_manager.h"
32 #include "iservice_registry.h"
33 #include "locale_config.h"
34 #include "nweb_log.h"
35 #include "ohos_adapter_helper.h"
36 #include "parameter.h"
37 #include "parameters.h"
38 #include "system_ability_definition.h"
39 
40 using namespace OHOS::AbilityBase;
41 
42 namespace {
43 const std::string NWEB_HAP_PATH = "/system/app/com.ohos.nweb/NWeb.hap";
44 const std::string NWEB_HAP_PATH_1 = "/system/app/NWeb/NWeb.hap";
45 const std::string ARKWEBCORE_HAP_SANDBOX_PATH = "/data/storage/el1/bundle/nweb/entry.hap";
46 const std::string PERSIST_ARKWEBCORE_INSTALL_PATH = "persist.arkwebcore.install_path";
47 const std::string NWEB_HAP_PATH_MODULE_UPDATE = "/module_update/ArkWebCore/app/com.ohos.nweb/NWeb.hap";
48 const std::string HAP_REAL_PATH_PREFIX = "/data/app/el1/bundle/public/";
49 const std::string HAP_SANDBOX_PATH_PREFIX = "/data/storage/el1/bundle/nweb/";
50 
51 const std::string NWEB_BUNDLE_NAME = "com.ohos.nweb";
52 const std::string NWEB_PACKAGE = "entry";
53 const std::string RAWFILE_PREFIX = "resources/rawfile/";
54 const std::string BUNDLE_NAME_PREFIX = "bundleName:";
55 const std::string MODULE_NAME_PREFIX = "moduleName:";
56 constexpr uint32_t TM_YEAR_BITS = 9;
57 constexpr uint32_t TM_MON_BITS = 5;
58 constexpr uint32_t TM_MIN_BITS = 5;
59 constexpr uint32_t TM_HOUR_BITS = 11;
60 constexpr uint32_t START_YEAR = 1900;
61 } // namespace
62 
63 namespace OHOS::NWeb {
64 namespace {
GetResourceMgr(const std::string & bundleName,const std::string & moduleName)65 std::shared_ptr<Global::Resource::ResourceManager> GetResourceMgr(
66     const std::string& bundleName, const std::string& moduleName)
67 {
68     std::shared_ptr<AbilityRuntime::ApplicationContext> context =
69         AbilityRuntime::ApplicationContext::GetApplicationContext();
70     if (!context) {
71         WVLOG_E("Failed to get application context.");
72         return nullptr;
73     }
74 
75     if (bundleName.empty() || moduleName.empty()) {
76         return context->GetResourceManager();
77     }
78     auto moduleContext = context->CreateModuleContext(bundleName, moduleName);
79     if (!moduleContext) {
80         WVLOG_E("Failed to crate module context, bundleName: %{public}s, moduleName: %{public}s.",
81             bundleName.c_str(), moduleName.c_str());
82         return nullptr;
83     }
84     return moduleContext->GetResourceManager();
85 }
86 
ParseRawFile(const std::string & rawFile,std::string & bundleName,std::string & moduleName,std::string & fileName)87 bool ParseRawFile(const std::string& rawFile,
88     std::string& bundleName, std::string& moduleName, std::string& fileName)
89 {
90     if (rawFile.substr(0, RAWFILE_PREFIX.size()) != RAWFILE_PREFIX) {
91         WVLOG_D("ParseRawFile failed, rawfile: %{public}s", rawFile.c_str());
92         return false;
93     }
94 
95     std::string subStr = rawFile.substr(RAWFILE_PREFIX.size());
96     if (subStr.substr(0, BUNDLE_NAME_PREFIX.size()) != BUNDLE_NAME_PREFIX) {
97         return false;
98     }
99     subStr = subStr.substr(BUNDLE_NAME_PREFIX.size());
100     size_t pos = subStr.find('/');
101     if (pos == std::string::npos) {
102         WVLOG_D("ParseRawFile bundleName failed, rawfile: %{public}s", rawFile.c_str());
103         return false;
104     }
105     bundleName = subStr.substr(0, pos);
106 
107     subStr = subStr.substr(pos + 1);
108     if (subStr.substr(0, MODULE_NAME_PREFIX.size()) != MODULE_NAME_PREFIX) {
109         return false;
110     }
111     subStr = subStr.substr(MODULE_NAME_PREFIX.size());
112     pos = subStr.find('/');
113     if (pos == std::string::npos) {
114         WVLOG_D("ParseRawFile moduleName failed, rawfile: %{public}s", rawFile.c_str());
115         return false;
116     }
117     moduleName = subStr.substr(0, pos);
118 
119     fileName = subStr.substr(pos + 1);
120     if (fileName.empty()) {
121         WVLOG_D("ParseRawFile fileName failed, rawfile: %{public}s", rawFile.c_str());
122         return false;
123     }
124     return true;
125 }
126 
127 
GetArkWebHapPath(const std::string & arkWebCoreHapPathOverride,std::vector<std::pair<std::string,int>> & errorMessage)128 std::string GetArkWebHapPath(const std::string& arkWebCoreHapPathOverride,
129                              std::vector<std::pair<std::string, int>>& errorMessage)
130 {
131     std::string prefixPath = WEBVIEW_SANDBOX_PATH;
132     if (access(arkWebCoreHapPathOverride.c_str(), F_OK) == 0) {
133         std::string sandboxPath = OhosResourceAdapterImpl::ConvertToSandboxPath(arkWebCoreHapPathOverride, prefixPath);
134         if (access(sandboxPath.c_str(), F_OK) == 0) {
135             WVLOG_D("eixt HAP_arkWebCoreHapPathOverride");
136             return sandboxPath;
137         }
138     }
139     errorMessage.emplace_back("access arkWebCoreHapPathOverride path failed", errno);
140 
141     std::string installPath = OhosResourceAdapterImpl::ConvertToSandboxPath(
142         OHOS::system::GetParameter(PERSIST_ARKWEBCORE_INSTALL_PATH, ""), prefixPath);
143     if (access(installPath.c_str(), F_OK) == 0) {
144         WVLOG_D("exit install_path,%{public}s", installPath.c_str());
145         return installPath;
146     }
147     errorMessage.emplace_back("access nweb install path failed", errno);
148 
149     if (access(WEBVIEW_SANDBOX_HAP_PATH, F_OK) == 0) {
150         WVLOG_D("exit WEBVIEW_SANDBOX_HAP_PATH");
151         return WEBVIEW_SANDBOX_HAP_PATH;
152     }
153     errorMessage.emplace_back("access arkwebcore hap sandbox path failed", errno);
154     if (access(WEBVIEW_APP_HAP_PATH2, F_OK) == 0) {
155         WVLOG_D("exit WEBVIEW_APP_HAP_PATH2");
156         return WEBVIEW_APP_HAP_PATH2;
157     }
158     errorMessage.emplace_back("access ohos nweb hap path failed", errno);
159     if (access(WEBVIEW_APP_HAP_PATH, F_OK) == 0) {
160         WVLOG_D("exit WEBVIEW_APP_HAP_PATH");
161         return WEBVIEW_APP_HAP_PATH;
162     }
163     errorMessage.emplace_back("access nweb hap path failed", errno);
164     if (access(WEBVIEW_HAP_PATH, F_OK) == 0) {
165         WVLOG_D("exit WEBVIEW_HAP_PATH");
166         return WEBVIEW_HAP_PATH;
167     }
168     errorMessage.emplace_back("access nweb hap module update path failed", errno);
169     return "";
170 }
171 
172 } // namespace
173 
OhosFileMapperImpl(std::unique_ptr<OHOS::AbilityBase::FileMapper> fileMap,const std::shared_ptr<Extractor> & extractor)174 OhosFileMapperImpl::OhosFileMapperImpl(std::unique_ptr<OHOS::AbilityBase::FileMapper> fileMap,
175     const std::shared_ptr<Extractor>& extractor): extractor_(extractor), fileMap_(std::move(fileMap))
176 {
177 }
178 
GetFd()179 int32_t OhosFileMapperImpl::GetFd()
180 {
181     return -1;
182 }
183 
GetOffset()184 int32_t OhosFileMapperImpl::GetOffset()
185 {
186     return fileMap_ ? fileMap_->GetOffset(): -1;
187 }
188 
GetFileName()189 std::string OhosFileMapperImpl::GetFileName()
190 {
191     return fileMap_ ? fileMap_->GetFileName(): "";
192 }
193 
IsCompressed()194 bool OhosFileMapperImpl::IsCompressed()
195 {
196     return fileMap_ ? fileMap_->IsCompressed(): false;
197 }
198 
GetDataPtr()199 void* OhosFileMapperImpl::GetDataPtr()
200 {
201     return fileMap_ ? fileMap_->GetDataPtr(): nullptr;
202 }
203 
GetDataLen()204 size_t OhosFileMapperImpl::GetDataLen()
205 {
206     return fileMap_ ? fileMap_->GetDataLen(): 0;
207 }
208 
UnzipData(uint8_t ** dest,size_t & len)209 bool OhosFileMapperImpl::UnzipData(uint8_t** dest, size_t& len)
210 {
211     if (extractor_ && IsCompressed()) {
212         std::unique_ptr<uint8_t[]> data;
213         bool result = extractor_->UnzipData(std::move(fileMap_), data, len);
214         if (result) {
215             *dest = data.release();
216         }
217         return result;
218     }
219     return false;
220 }
221 
222 std::string OhosResourceAdapterImpl::arkWebCoreHapPathOverride_ = "";
ConvertToSandboxPath(const std::string & installPath,const std::string & prefixPath)223 std::string OhosResourceAdapterImpl::ConvertToSandboxPath(const std::string& installPath, const std::string& prefixPath)
224 {
225     if (installPath.empty()) {
226         return "";
227     }
228     size_t result = installPath.find(HAP_REAL_PATH_PREFIX);
229     if (result != std::string::npos) {
230         size_t pos = installPath.find_last_of('/');
231         if (pos != std::string::npos && pos != installPath.size() - 1) {
232             return prefixPath + installPath.substr(pos + 1);
233         }
234     }
235     return installPath;
236 }
237 
OhosResourceAdapterImpl(const std::string & hapPath)238 OhosResourceAdapterImpl::OhosResourceAdapterImpl(const std::string& hapPath)
239 {
240     Init(hapPath);
241 }
242 
Init(const std::string & hapPath)243 void OhosResourceAdapterImpl::Init(const std::string& hapPath)
244 {
245     bool newCreate = false;
246     std::vector<std::pair<std::string, int>> errorMessage;
247     std::string arkWebHapPath = GetArkWebHapPath(arkWebCoreHapPathOverride_, errorMessage);
248     if (!arkWebHapPath.empty()) {
249         sysExtractor_ = ExtractorUtil::GetExtractor(arkWebHapPath, newCreate);
250         if (!sysExtractor_) {
251             WVLOG_E("RuntimeExtractor create failed for %{public}s", arkWebHapPath.c_str());
252         }
253     }
254     for (const auto& err : errorMessage) {
255         WVLOG_E("%{public}s, errno(%{public}d): %{public}s", err.first.c_str(), err.second, strerror(err.second));
256     }
257     if (hapPath.empty()) {
258         return;
259     }
260     std::string loadPath = ExtractorUtil::GetLoadFilePath(hapPath);
261     extractor_ = ExtractorUtil::GetExtractor(loadPath, newCreate);
262     if (!extractor_) {
263         WVLOG_E("RuntimeExtractor create failed for %{public}s", hapPath.c_str());
264     }
265 }
266 
GetRawFileData(const std::string & rawFile,size_t & len,uint8_t ** dest,bool isSys)267 bool OhosResourceAdapterImpl::GetRawFileData(const std::string& rawFile, size_t& len,
268     uint8_t** dest, bool isSys)
269 {
270     std::unique_ptr<uint8_t[]> data;
271     bool result;
272     if (isSys) {
273         result =  GetRawFileData(sysExtractor_, rawFile, len, data);
274         if (result) {
275             *dest = data.release();
276         }
277         return result;
278     }
279     std::string bundleName;
280     std::string moduleName;
281     std::string fileName;
282     if (ParseRawFile(rawFile, bundleName, moduleName, fileName)) {
283         auto resourceManager = GetResourceMgr(bundleName, moduleName);
284         if (!resourceManager) {
285             result = GetRawFileData(extractor_, rawFile, len, data);
286             if (result) {
287                 *dest = data.release();
288             }
289             return result;
290         }
291         auto state = resourceManager->GetRawFileFromHap(fileName, len, data);
292         if (state != Global::Resource::SUCCESS) {
293             WVLOG_E("GetRawFileFromHap failed, state: %{public}d, fileName: %{public}s", state, fileName.c_str());
294             result = GetRawFileData(extractor_, rawFile, len, data);
295             if (result) {
296                 *dest = data.release();
297             }
298             return result;
299         }
300         *dest = data.release();
301         return true;
302     }
303 
304     result = GetRawFileData(extractor_, rawFile, len, data);
305     if (result) {
306         *dest = data.release();
307     }
308     return result;
309 }
310 
GetResourceString(const std::string & bundleName,const std::string & moduleName,const int32_t resId,std::string & result)311 bool OhosResourceAdapterImpl::GetResourceString(const std::string& bundleName,
312     const std::string& moduleName, const int32_t resId, std::string& result)
313 {
314     auto resourceManager = GetResourceMgr(bundleName, moduleName);
315     if (!resourceManager) {
316         return false;
317     }
318     if (resourceManager->GetStringById(resId, result) == Global::Resource::SUCCESS) {
319         return true;
320     }
321     return false;
322 }
323 
GetRawFileMapper(const std::string & rawFile,bool isSys)324 std::shared_ptr<OhosFileMapper> OhosResourceAdapterImpl::GetRawFileMapper(const std::string& rawFile,
325     bool isSys)
326 {
327     return GetRawFileMapper(isSys? sysExtractor_: extractor_, rawFile);
328 }
329 
IsRawFileExist(const std::string & rawFile,bool isSys)330 bool OhosResourceAdapterImpl::IsRawFileExist(const std::string& rawFile, bool isSys)
331 {
332     return HasEntry(isSys? sysExtractor_: extractor_, rawFile);
333 }
334 
GetRawFileLastModTime(const std::string & rawFile,uint16_t & date,uint16_t & time,bool isSys)335 bool OhosResourceAdapterImpl::GetRawFileLastModTime(const std::string& rawFile,
336     uint16_t& date, uint16_t& time, bool isSys)
337 {
338     FileInfo info;
339     if (GetFileInfo(isSys? sysExtractor_: extractor_, rawFile, info)) {
340         date = info.lastModDate;
341         time = info.lastModTime;
342         return true;
343     }
344     return false;
345 }
346 
GetRawFileLastModTime(const std::string & rawFile,time_t & time,bool isSys)347 bool OhosResourceAdapterImpl::GetRawFileLastModTime(const std::string& rawFile, time_t& time, bool isSys)
348 {
349     FileInfo info;
350     if (GetFileInfo(isSys? sysExtractor_: extractor_, rawFile, info)) {
351         uint16_t modifiedDate = info.lastModDate;
352         uint16_t modifiedTime = info.lastModTime;
353         struct tm newTime;
354         newTime.tm_year = ((modifiedDate >> TM_YEAR_BITS) & 0x7f) + START_YEAR;
355         newTime.tm_mon = (modifiedDate >> TM_MON_BITS) & 0xf;
356         newTime.tm_mday = modifiedDate & 0x1f;
357         newTime.tm_hour = (modifiedTime >> TM_HOUR_BITS) & 0x1f;
358         newTime.tm_min = (modifiedTime >> TM_MIN_BITS) & 0x2f;
359         newTime.tm_sec = (modifiedTime << 1) & 0x1f;
360         newTime.tm_isdst = 0;
361         time = mktime(&newTime);
362         return true;
363     }
364     return false;
365 }
366 
367 // static
HasEntry(const std::shared_ptr<OHOS::AbilityBase::Extractor> & manager,const std::string & rawFile)368 bool OhosResourceAdapterImpl::HasEntry(const std::shared_ptr<OHOS::AbilityBase::Extractor>& manager,
369     const std::string& rawFile)
370 {
371     if (!manager) {
372         return false;
373     }
374     return manager->HasEntry(rawFile);
375 }
376 
GetFileInfo(const std::shared_ptr<OHOS::AbilityBase::Extractor> & manager,const std::string & rawFile,OHOS::AbilityBase::FileInfo & info)377 bool OhosResourceAdapterImpl::GetFileInfo(const std::shared_ptr<OHOS::AbilityBase::Extractor>& manager,
378     const std::string& rawFile, OHOS::AbilityBase::FileInfo& info)
379 {
380     if (!manager) {
381         return false;
382     }
383     return manager->GetFileInfo(rawFile, info);
384 }
385 
GetModuleName(const char * configStr,size_t len)386 std::string OhosResourceAdapterImpl::GetModuleName(const char *configStr, size_t len)
387 {
388     if (configStr == nullptr) {
389         return std::string();
390     }
391     std::string config(configStr, len);
392     static const char *key = "\"moduleName\"";
393     auto idx = config.find(key);
394     if (idx == std::string::npos) {
395         return std::string();
396     }
397     auto start = config.find("\"", idx + strlen(key));
398     if (start == std::string::npos) {
399         return std::string();
400     }
401     auto end = config.find("\"", start + 1);
402     if (end == std::string::npos || end < start + 1) {
403         return std::string();
404     }
405 
406     std::string retStr = std::string(configStr + start + 1, end - start - 1);
407     return retStr;
408 }
409 
ParseModuleName(const std::shared_ptr<Extractor> & manager)410 std::string OhosResourceAdapterImpl::ParseModuleName(const std::shared_ptr<Extractor> &manager)
411 {
412     if (manager == nullptr) {
413         return std::string();
414     }
415     std::unique_ptr<uint8_t[]> configBuf;
416     size_t len;
417     bool ret = manager->ExtractToBufByName("config.json", configBuf, len);
418     if (!ret) {
419         WVLOG_E("failed to get config data from ability");
420         return std::string();
421     }
422     // parse config.json
423     std::string mName = GetModuleName(reinterpret_cast<char *>(configBuf.get()), len);
424     if (mName.size() == 0) {
425         WVLOG_E("parse moduleName from config.json error");
426         return std::string();
427     }
428     return mName;
429 }
430 
GetRawFileData(const std::shared_ptr<Extractor> & manager,const std::string & rawFile,size_t & len,std::unique_ptr<uint8_t[]> & dest)431 bool OhosResourceAdapterImpl::GetRawFileData(const std::shared_ptr<Extractor>& manager,
432     const std::string& rawFile, size_t& len, std::unique_ptr<uint8_t[]>& dest)
433 {
434     if (!manager) {
435         return false;
436     }
437     if (manager->IsStageModel()) {
438         return manager->ExtractToBufByName(rawFile, dest, len);
439     }
440     std::string moduleName = OhosResourceAdapterImpl::ParseModuleName(manager);
441     std::string rawFilePath("assets/");
442     rawFilePath.append(moduleName);
443     rawFilePath.append("/");
444     rawFilePath.append(rawFile);
445     WVLOG_E("fa filepath:%{public}s", rawFilePath.c_str());
446     return manager->ExtractToBufByName(rawFilePath, dest, len);
447 }
448 
GetRawFileMapper(const std::shared_ptr<OHOS::AbilityBase::Extractor> & manager,const std::string & rawFile)449 std::shared_ptr<OhosFileMapper> OhosResourceAdapterImpl::GetRawFileMapper(
450     const std::shared_ptr<OHOS::AbilityBase::Extractor>& manager,
451     const std::string& rawFile)
452 {
453     if (!manager) {
454         return nullptr;
455     }
456     std::unique_ptr<OHOS::AbilityBase::FileMapper> fileMap;
457     auto& systemPropertiesAdapter = OhosAdapterHelper::GetInstance().GetSystemPropertiesInstance();
458     if (systemPropertiesAdapter.GetWebOptimizationValue()) {
459         fileMap = manager->GetMmapData(rawFile);
460     } else {
461         fileMap = manager->GetData(rawFile);
462     }
463     if (fileMap == nullptr) {
464         return nullptr;
465     }
466     bool isCompressed = fileMap->IsCompressed();
467     return std::make_shared<OhosFileMapperImpl>(std::move(fileMap), isCompressed ? manager: nullptr);
468 }
469 
GetArkWebVersion()470 std::string OhosResourceAdapterImpl::GetArkWebVersion()
471 {
472     const std::string hapPaths[] = {
473         "/system/app/com.ohos.arkwebcore/ArkWebCore.hap"
474     };
475     const std::string packInfoPath = "pack.info";
476 
477     for (const auto& hapPath : hapPaths) {
478         OHOS::AbilityBase::Extractor extractor(hapPath);
479         if (!extractor.Init()) {
480             WVLOG_W("Failed to initialize extractor for HAP file: %{public}s", hapPath.c_str());
481             continue;
482         }
483 
484         std::ostringstream contentStream;
485         bool ret = extractor.ExtractByName(packInfoPath, contentStream);
486         if (!ret) {
487             WVLOG_W("Failed to extract pack.info from HAP: %{public}s", hapPath.c_str());
488             continue;
489         }
490 
491         std::string configContent = contentStream.str();
492 
493         Json::Value root;
494         Json::Reader reader;
495         if (!reader.parse(configContent, root)) {
496             WVLOG_W("Failed to parse pack.info from HAP: %{public}s", hapPath.c_str());
497             continue;
498         }
499 
500         if (root.isMember("summary") &&
501             root["summary"].isMember("app") &&
502             root["summary"]["app"].isMember("version") &&
503             root["summary"]["app"]["version"].isMember("name")) {
504             return root["summary"]["app"]["version"]["name"].asString();
505         }
506 
507         WVLOG_W("Version information not found in pack.info from HAP: %{public}s", hapPath.c_str());
508     }
509 
510     WVLOG_W("Failed to get ArkWeb version from any of the specified paths");
511     return "";
512 }
513 
SetArkWebCoreHapPathOverride(const std::string & hapPath)514 void OhosResourceAdapterImpl::SetArkWebCoreHapPathOverride(const std::string& hapPath)
515 {
516     arkWebCoreHapPathOverride_ = hapPath;
517 }
518 
GetSystemLanguage()519 std::string OhosResourceAdapterImpl::GetSystemLanguage()
520 {
521     return OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
522 }
523 
524 }  // namespace OHOS::NWeb
525