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_socket.h"
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 #include "beget_ext.h"
22 #include "securec.h"
23
24 #define N_DEC 10
25 #define MAX_SOCKET_ENV_PREFIX_LEN 64
26 #define MAX_SOCKET_DIR_LEN 128
27
GetControlFromEnv(const char * path,int length)28 static int GetControlFromEnv(const char *path, int length)
29 {
30 BEGET_CHECK_RETURN_VALUE(path != NULL && length > 0, -1);
31 const char *val = getenv(path);
32 BEGET_ERROR_CHECK(val != NULL, return -1, "Get environment from %s failed", path);
33 errno = 0;
34 int fd = strtol(val, NULL, N_DEC);
35 BEGET_ERROR_CHECK(errno == 0, return -1, "Failed strtol err=%d", errno);
36 BEGET_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "Failed fcntl err=%d ", errno);
37 return fd;
38 }
39
GetControlSocket(const char * name)40 int GetControlSocket(const char *name)
41 {
42 BEGET_CHECK_RETURN_VALUE(name != NULL, -1);
43 char path[MAX_SOCKET_ENV_PREFIX_LEN] = {0};
44 BEGET_CHECK_RETURN_VALUE(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_SOCKET_ENV_PREFIX"%s",
45 name) != -1, -1);
46 int fd = GetControlFromEnv(path, MAX_SOCKET_ENV_PREFIX_LEN);
47 BEGET_ERROR_CHECK(fd >= 0, return -1, "Get control fd from environment failed");
48 int addrFamily = 0;
49 socklen_t afLen = sizeof(addrFamily);
50 int ret = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &addrFamily, &afLen);
51 BEGET_ERROR_CHECK(ret == 0, return -1, "Get socket option fail, err=%d ", errno);
52 if (addrFamily != AF_UNIX) {
53 return fd;
54 }
55 struct sockaddr_un addr;
56 socklen_t addrlen = sizeof(addr);
57 ret = getsockname(fd, (struct sockaddr*)&addr, &addrlen);
58 BEGET_ERROR_CHECK(ret >= 0, return -1, "Failed getsockname err=%d ", errno);
59 char sockDir[MAX_SOCKET_DIR_LEN] = {0};
60 BEGET_CHECK_RETURN_VALUE(snprintf_s(sockDir, sizeof(sockDir), sizeof(sockDir) - 1, OHOS_SOCKET_DIR"/%s",
61 name) != -1, -1);
62 BEGET_LOGV("Compary sockDir %s and addr.sun_path %s", sockDir, addr.sun_path);
63 if (strncmp(sockDir, addr.sun_path, strlen(sockDir)) == 0) {
64 return fd;
65 }
66 return -1;
67 }
68