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