1 /*
2 * Copyright (c) 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 "os_api.h"
16
17 #include <climits>
18 #include <cstdlib>
19 #include <sys/stat.h>
20 #include <unistd.h>
21
22 #include "doc_errno.h"
23 #include "rd_log_print.h"
24 #include "securec.h"
25
26 namespace DocumentDB {
27 namespace {
28 const int ACCESS_MODE_EXISTENCE = 0;
29 }
30 namespace OSAPI {
CheckPathPermission(const std::string & filePath)31 bool CheckPathPermission(const std::string &filePath)
32 {
33 return (access(filePath.c_str(), R_OK) == 0) && (access(filePath.c_str(), W_OK) == 0);
34 }
35
IsPathExist(const std::string & filePath)36 bool IsPathExist(const std::string &filePath)
37 {
38 return (access(filePath.c_str(), ACCESS_MODE_EXISTENCE) == 0);
39 }
40
GetRealPath(const std::string & inOriPath,std::string & outRealPath)41 int GetRealPath(const std::string &inOriPath, std::string &outRealPath)
42 {
43 const unsigned int maxPathLength = PATH_MAX;
44 if (inOriPath.length() > maxPathLength) { // max limit is 64K(0x10000).
45 GLOGE("[OS_API] OriPath too long.");
46 return -E_INVALID_ARGS;
47 }
48
49 char *realPath = new (std::nothrow) char[maxPathLength + 1];
50 if (realPath == nullptr) {
51 return -E_OUT_OF_MEMORY;
52 }
53 if (memset_s(realPath, maxPathLength + 1, 0, maxPathLength + 1) != EOK) {
54 delete[] realPath;
55 return -E_SECUREC_ERROR;
56 }
57 #ifndef _WIN32
58 if (realpath(inOriPath.c_str(), realPath) == nullptr) {
59 GLOGE("[OS_API] Realpath error:%d.", errno);
60 delete[] realPath;
61 return -E_SYSTEM_API_FAIL;
62 }
63 #else
64 if (_fullpath(realPath, inOriPath.c_str(), maxPathLength) == nullptr) {
65 GLOGE("[OS] Realpath error:%d.", errno);
66 delete [] realPath;
67 return -E_SYSTEM_API_FAIL;
68 }
69 #endif
70 outRealPath = std::string(realPath);
71 delete[] realPath;
72 return E_OK;
73 }
74
SplitFilePath(const std::string & filePath,std::string & fieldir,std::string & fileName)75 void SplitFilePath(const std::string &filePath, std::string &fieldir, std::string &fileName)
76 {
77 if (filePath.empty()) {
78 return;
79 }
80
81 auto slashPos = filePath.find_last_of('/');
82 if (slashPos == std::string::npos) {
83 fileName = filePath;
84 fieldir = "";
85 return;
86 }
87
88 fieldir = filePath.substr(0, slashPos);
89 fileName = filePath.substr(slashPos + 1);
90 }
91 } // namespace OSAPI
92 } // namespace DocumentDB