1 /*
2 * Copyright (c) 2022-2023 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 #include "uri_handler.h"
16
17 #include "pasteboard_hilog.h"
18 #include "paste_data.h"
19
20 namespace OHOS::MiscServices {
GetRealPath(const std::string & inOriPath,std::string & outRealPath)21 bool UriHandler::GetRealPath(const std::string &inOriPath, std::string &outRealPath)
22 {
23 char realPath[PATH_MAX + 1] = { 0x00 };
24 if (inOriPath.size() > PATH_MAX || realpath(inOriPath.c_str(), realPath) == nullptr) {
25 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "get real path failed, len = %{public}zu.", inOriPath.size());
26 return false;
27 }
28 outRealPath = std::string(realPath);
29 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_CLIENT, "file path:%{public}s", outRealPath.c_str());
30 return true;
31 }
32
IsFile(const std::string & uri) const33 bool UriHandler::IsFile(const std::string &uri) const
34 {
35 if (uri.empty()) {
36 return false;
37 }
38 struct stat fileInfo {
39 };
40 if (stat(uri.c_str(), &fileInfo) == 0 && (fileInfo.st_mode & S_IFREG)) {
41 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_CLIENT, "valid uri");
42 return true;
43 }
44 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_CLIENT, "not file");
45 return false;
46 }
ToFd(const std::string & uri,bool isClient)47 int32_t UriHandler::ToFd(const std::string &uri, bool isClient)
48 {
49 std::string fileRealPath;
50 if (!GetRealPath(uri, fileRealPath)) {
51 return INVALID_FD;
52 }
53 if (!IsFile(fileRealPath)) {
54 return INVALID_FD;
55 }
56 if (!isClient && (PasteData::sharePath.size() == 0 || fileRealPath.rfind(PasteData::sharePath, 0) != 0)) {
57 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_CLIENT, "uri error, sharePath: %{public}s, fileRealPath: %{public}s",
58 PasteData::sharePath.c_str(), fileRealPath.c_str());
59 return INVALID_FD;
60 }
61
62 int32_t fd = open(fileRealPath.c_str(), O_RDONLY);
63 if (fd < 0) {
64 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_CLIENT, "open file failed, maybe its not a legal file path %{public}s",
65 fileRealPath.c_str());
66 }
67 return fd;
68 }
69
ReleaseFd(int32_t fd)70 void UriHandler::ReleaseFd(int32_t fd)
71 {
72 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "close fd: %{public}d", fd);
73 if (fd >= 0) {
74 close(fd);
75 }
76 }
IsPaste() const77 bool UriHandler::IsPaste() const
78 {
79 return isPaste_;
80 }
81 } // namespace OHOS::MiscServices