• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2025 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 "uri_helper.h"
17 #include <cstring>
18 #include <climits>
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <type_traits>
23 #include "media_errors.h"
24 #include "media_log.h"
25 #include "osal/filesystem/file_system.h"
26 
27 namespace {
28 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN_PLAYER, "UriHelper"};
29 constexpr unsigned int HMDFS_IOC = 0xf2;
30 }
31 
32 namespace OHOS {
33 namespace Media {
34 #define HMDFS_IOC_GET_LOCATION _IOR(HMDFS_IOC, 7, unsigned int)
35 static const std::map<std::string_view, uint8_t> g_validUriTypes = {
36     {"", UriHelper::UriType::URI_TYPE_FILE }, // empty uri head is treated as the file type uri.
37     {"file", UriHelper::UriType::URI_TYPE_FILE},
38     {"fd", UriHelper::UriType::URI_TYPE_FD},
39     {"http", UriHelper::UriType::URI_TYPE_HTTP}
40 };
41 
PathToRealFileUrl(const std::string_view & path,std::string & realPath)42 static bool PathToRealFileUrl(const std::string_view &path, std::string &realPath)
43 {
44     CHECK_AND_RETURN_RET_LOG(!path.empty(), false, "path is empty!");
45     CHECK_AND_RETURN_RET_LOG(path.length() < PATH_MAX, false,
46         "path len is error, the len is: [%{public}zu]", path.length());
47 
48     char tmpPath[PATH_MAX] = {0};
49     char *pathAddr = realpath(path.data(), tmpPath);
50     CHECK_AND_RETURN_RET_LOG(pathAddr != nullptr, false,
51         "path to realpath error, %{public}s", path.data());
52 
53     int ret = access(tmpPath, F_OK);
54     CHECK_AND_RETURN_RET_LOG(ret == 0, false,
55         "check realpath (%{private}s) error", tmpPath);
56 
57     realPath = std::string("file://") + tmpPath;
58     return true;
59 }
60 
61 template<typename T, typename = std::enable_if_t<std::is_same_v<int64_t, T> || std::is_same_v<int32_t, T>>>
StrToInt(const std::string_view & str,T & value)62 bool StrToInt(const std::string_view& str, T& value)
63 {
64     CHECK_AND_RETURN_RET(!str.empty() && (isdigit(str.front()) || (str.front() == '-')), false);
65     std::string valStr(str);
66     char* end = nullptr;
67     errno = 0;
68     const char* addr = valStr.c_str();
69     long long result = strtoll(addr, &end, 10); /* 10 means decimal */
70     CHECK_AND_RETURN_RET_LOG(result >= LLONG_MIN && result <= LLONG_MAX, false,
71         "call StrToInt func false,  input str is: %{public}s!", valStr.c_str());
72     CHECK_AND_RETURN_RET_LOG(end != addr && end[0] == '\0' && errno != ERANGE, false,
73         "call StrToInt func false,  input str is: %{public}s!", valStr.c_str());
74     if constexpr (std::is_same<int32_t, T>::value) {
75         CHECK_AND_RETURN_RET_LOG(result >= INT_MIN && result <= INT_MAX, false,
76             "call StrToInt func false,  input str is: %{public}s!", valStr.c_str());
77         value = static_cast<int32_t>(result);
78         return true;
79     }
80     value = result;
81     return true;
82 }
83 
84 __attribute__((no_sanitize("cfi")))
SplitUriHeadAndBody(const std::string_view & str)85 std::pair<std::string_view, std::string_view> SplitUriHeadAndBody(const std::string_view &str)
86 {
87     std::string_view::size_type start = str.find_first_not_of(' ');
88     std::string_view::size_type end = str.find_last_not_of(' ');
89     std::pair<std::string_view, std::string_view> result;
90     std::string_view noSpaceStr;
91     if (start == std::string_view::npos && end == std::string_view::npos) {
92         result.first = "";
93         result.second = "";
94         return result;
95     }
96     if (end == std::string_view::npos) {
97         noSpaceStr = str.substr(start);
98     } else {
99         if (end >= start) {
100             noSpaceStr = str.substr(start, end - start + 1);
101         }
102     }
103     std::string_view delimiter = "://";
104     std::string_view::size_type pos = noSpaceStr.find(delimiter);
105     if (pos == std::string_view::npos) {
106         result.first = "";
107         result.second = noSpaceStr;
108     } else {
109         result.first = noSpaceStr.substr(0, pos);
110         result.second = noSpaceStr.substr(pos + delimiter.size());
111     }
112     return result;
113 }
114 
UriHelper(const std::string_view & uri)115 UriHelper::UriHelper(const std::string_view &uri)
116 {
117     FormatMeForUri(uri);
118 }
119 
UriHelper(int32_t fd,int64_t offset,int64_t size)120 UriHelper::UriHelper(int32_t fd, int64_t offset, int64_t size) : fd_(dup(fd)), offset_(offset), size_(size)
121 {
122     FormatMeForFd();
123 }
124 
~UriHelper()125 UriHelper::~UriHelper()
126 {
127     if (fd_ >= 0) {
128         (void)::close(fd_);
129         fd_ = -1;
130     }
131 }
132 
FormatMeForUri(const std::string_view & uri)133 void UriHelper::FormatMeForUri(const std::string_view &uri) noexcept
134 {
135     CHECK_AND_RETURN_LOG(formattedUri_.empty(),
136         "formattedUri is valid:%{public}s", formattedUri_.c_str());
137     CHECK_AND_RETURN_LOG(!uri.empty(), "uri is empty");
138     auto [head, body] = SplitUriHeadAndBody(uri);
139     CHECK_AND_RETURN(g_validUriTypes.count(head) != 0);
140     type_ = g_validUriTypes.at(head);
141     // verify whether the uri is readable and generate the formatted uri.
142     switch (type_) {
143         case URI_TYPE_FILE: {
144             if (!PathToRealFileUrl(body, formattedUri_)) {
145                 type_ = URI_TYPE_UNKNOWN;
146                 formattedUri_ = body;
147             }
148             rawFileUri_ = formattedUri_;
149             if (rawFileUri_.size() > strlen("file://")) {
150                 rawFileUri_ = rawFileUri_.substr(strlen("file://"));
151             }
152             break;
153         }
154         case URI_TYPE_FD: {
155             if (!ParseFdUri(body)) {
156                 type_ = URI_TYPE_UNKNOWN;
157                 formattedUri_ = "";
158             }
159             break;
160         }
161         default:
162             formattedUri_ = std::string(head);
163             formattedUri_ += body;
164             break;
165     }
166     MEDIA_LOGD("0x%{public}06" PRIXPTR " formatted uri: %{private}s", FAKE_POINTER(this), formattedUri_.c_str());
167 }
168 
FormatMeForFd()169 void UriHelper::FormatMeForFd() noexcept
170 {
171     MEDIA_LOGI("0x%{public}06" PRIXPTR " UriHelper FormatMeForFd fd is %{public}d", FAKE_POINTER(this), fd_);
172     CHECK_AND_RETURN_LOG(formattedUri_.empty(),
173         "formattedUri is valid:%{public}s", formattedUri_.c_str());
174     type_ = URI_TYPE_FD;
175     (void)CorrectFdParam();
176 }
177 
CorrectFdParam()178 bool UriHelper::CorrectFdParam()
179 {
180     int flags = fcntl(fd_, F_GETFL);
181     CHECK_AND_RETURN_RET_LOG(flags != -1, false, "Fail to get File Status Flags");
182     struct stat64 st;
183     CHECK_AND_RETURN_RET_LOG(fstat64(fd_, &st) == 0, false,
184         "can not get file state");
185     int64_t fdSize = static_cast<int64_t>(st.st_size);
186     int64_t stIno = static_cast<int64_t>(st.st_ino);
187     int64_t stSec = static_cast<int64_t>(st.st_atim.tv_sec);
188     MEDIA_LOGI("CorrectFdParam fd: %{public}d, fdSize: %{public}" PRId64 ", stIno: %{public}" PRId64
189         ", stSec: %{public}" PRId64, fd_, fdSize, stIno, stSec);
190     if (offset_ < 0 || offset_ > fdSize) {
191         offset_ = 0;
192     }
193     if ((size_ <= 0) || (size_ > fdSize - offset_)) {
194         size_ = fdSize - offset_;
195     }
196     formattedUri_ = std::string("fd://") + std::to_string(fd_) + "?offset=" +
197         std::to_string(offset_) + "&size=" + std::to_string(size_);
198     MEDIA_LOGI("CorrectFdParam formattedUri: %{public}s", formattedUri_.c_str());
199     DetermineFdLocation();
200     return true;
201 }
202 
DetermineFdLocation()203 void UriHelper::DetermineFdLocation()
204 {
205     CHECK_AND_RETURN(fd_ > 0);
206     int loc = 1;
207     ioctl(fd_, HMDFS_IOC_GET_LOCATION, &loc);
208 
209     fdLocation_ = static_cast<FdLocation>(loc);
210 }
211 
GetFdLocation()212 FdLocation UriHelper::GetFdLocation()
213 {
214     return fdLocation_;
215 }
216 
UriType() const217 uint8_t UriHelper::UriType() const
218 {
219     return type_;
220 }
221 
FormattedUri() const222 std::string UriHelper::FormattedUri() const
223 {
224     return formattedUri_;
225 }
226 
AccessCheck(uint8_t flag) const227 bool UriHelper::AccessCheck(uint8_t flag) const
228 {
229     CHECK_AND_RETURN_RET_LOG(type_ != URI_TYPE_UNKNOWN, false, "type is unknown");
230     if (type_ == URI_TYPE_FILE) {
231         uint32_t mode = (flag & URI_READ) ? R_OK : 0;
232         mode |= (flag & URI_WRITE) ? W_OK : 0;
233         int ret = access(rawFileUri_.data(), static_cast<int>(mode));
234         CHECK_AND_RETURN_RET_LOG(ret == 0, false,
235             "Fail to access path: %{public}s", rawFileUri_.data());
236         return true;
237     } else if (type_ == URI_TYPE_FD) {
238         CHECK_AND_RETURN_RET_LOG(fd_ > 0, false, "Fail to get file descriptor from uri, fd %{public}d", fd_);
239         int flags = fcntl(fd_, F_GETFL);
240         CHECK_AND_RETURN_RET_LOG(flags != -1, false, "Fail to get File Status Flags, fd %{public}d", fd_);
241         uint32_t mode = (flag & URI_WRITE) ? O_RDWR : O_RDONLY;
242         return ((static_cast<unsigned int>(flags) & mode) != mode) ? false : true;
243     }
244     return true; // Not implemented, defaultly return true.
245 }
246 
ParseFdUri(std::string_view uri)247 bool UriHelper::ParseFdUri(std::string_view uri)
248 {
249     static constexpr std::string_view::size_type delim1Len = std::string_view("?offset=").size();
250     static constexpr std::string_view::size_type delim2Len = std::string_view("&size=").size();
251     std::string_view::size_type delim1 = uri.find("?");
252     std::string_view::size_type delim2 = uri.find("&");
253     if (delim1 == std::string_view::npos && delim2 == std::string_view::npos) {
254         CHECK_AND_RETURN_RET_LOG(StrToInt(uri, fd_), false, "Invalid fd url");
255     } else if (delim1 != std::string_view::npos && delim2 != std::string_view::npos) {
256         std::string_view fdstr = uri.substr(0, delim1);
257         int32_t fd = -1;
258         CHECK_AND_RETURN_RET_LOG(StrToInt(fdstr, fd) && delim1 + delim1Len < uri.size()
259             && delim2 - delim1 - delim1Len > 0, false, "Invalid fd url");
260         std::string_view offsetStr = uri.substr(delim1 + delim1Len, delim2 - delim1 - delim1Len);
261         CHECK_AND_RETURN_RET_LOG(StrToInt(offsetStr, offset_) && delim2 + delim2Len < uri.size(), false,
262             "Invalid fd url");
263         std::string_view sizeStr = uri.substr(delim2 + delim2Len);
264         CHECK_AND_RETURN_RET_LOG(StrToInt(sizeStr, size_), false, "Invalid fd url");
265         MEDIA_LOGI("UriHelper ParseFdUri try close fd, fd is %{public}d, Set fd: %{public}d", fd_, fd);
266         if (fd_ >= 0) {
267             close(fd_);
268             fd_ = -1;
269         }
270         fd_ = dup(fd);
271         MEDIA_LOGI("UriHelper ParseFdUri dup, fd is %{public}d", fd_);
272     } else {
273         MEDIA_LOGE("invalid fd uri: %{private}s", uri.data());
274         return false;
275     }
276 
277     MEDIA_LOGD("parse fd uri, fd: %{public}d, offset: %{public}" PRIi64 ", size: %{public}" PRIi64,
278                fd_, offset_, size_);
279     return CorrectFdParam();
280 }
281 } // namespace Media
282 } // namespace OHOS
283