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