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 "init_file.h"
17
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <stdlib.h>
22
23#include "beget_ext.h"
24#include "init_utils.h"
25#include "securec.h"
26
27#define N_DEC 10
28
29int GetControlFile(const char *pathName)
30{
31    if (pathName == NULL) {
32        return -1;
33    }
34    char path[PATH_MAX] = { 0 };
35    BEGET_ERROR_CHECK(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_FILE_ENV_PREFIX "%s", pathName) >= 0,
36        return -1, "Failed snprintf_s err=%d", errno);
37    BEGET_ERROR_CHECK(StringReplaceChr(path, '/', '_') == 0,
38        return -1, "Failed string replace char");
39    BEGET_LOGI("Environment path is %s ", path);
40    const char *val = getenv(path);
41    BEGET_ERROR_CHECK(val != NULL, return -1, "Failed getenv err=%d", errno);
42    errno = 0;
43    int fd = strtol(val, NULL, N_DEC);
44    BEGET_ERROR_CHECK(errno == 0, return -1, "Failed strtol val");
45    BEGET_LOGI("Get environment fd is %d ", fd);
46    BEGET_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "Failed fcntl fd err=%d ", errno);
47    return fd;
48}
49